Compare commits

...

109 Commits

Author SHA1 Message Date
Igor Lins e Silva 2bc18837ee update hpm 2022-11-15 19:51:00 -03:00
Igor Lins e Silva 0c25e25efa update ecosystem files 2022-11-14 15:37:57 -03:00
Igor Lins e Silva 96dc2a3b7d update example connections.json 2022-11-12 05:14:24 -03:00
Igor Lins e Silva 8c158b00cf indexer controller api
remove pm2io actions
general optimizations
allow multiple ship endpoints with reader load balancing
2022-11-12 05:12:29 -03:00
Igor Lins e Silva 3f26ef3dbb update packages 2022-11-11 21:50:11 -03:00
Igor Lins e Silva cb66494871 - automatically sets the chain config if only a single chain config file is defined on the config/chains directory
- allows using CONFIG_NAME=<chain_name> or CONFIG_JSON=<absolute_path>
2022-11-11 21:44:49 -03:00
Igor Lins e Silva 956989557b typescript coverage 2022-11-08 06:24:49 -03:00
Igor Lins e Silva 1d7371ab71 [wip] improve typescript coverage 2022-11-07 05:12:18 -03:00
Igor Lins e Silva 75186ddaf1 [wip] improve typescript coverage 2022-11-05 03:38:07 -03:00
Igor Lins e Silva 7c0c187841 Merge branch 'v3.4-dev' of https://github.com/eosrio/hyperion-history-api into v3.4-dev 2022-11-04 10:49:47 -03:00
Igor Lins e Silva ba01979cfe [wip] improve typings 2022-11-04 10:49:26 -03:00
Igor Lins e Silva 4466df5d1a [wip] improve typings 2022-11-04 10:49:22 -03:00
Igor Lins e Silva 451bd18f44 [wip] improve typings 2022-11-04 10:35:16 -03:00
Igor Lins e Silva 27c497ecfa merge dev changes on 3.4 2022-11-04 04:46:59 -03:00
Igor Lins e Silva c96818908d cleanup 2022-11-03 06:00:55 -03:00
Igor Lins e Silva de9a42bc02 update .gitignore 2022-11-02 21:27:49 -03:00
Igor Lins e Silva 13759e4314 update example 2022-11-02 21:23:04 -03:00
Igor Lins e Silva 9a347615b4 fix hyp-config init tool 2022-11-02 21:20:11 -03:00
Igor Lins e Silva d3af0322c8 update packages 2022-10-19 19:48:30 -03:00
Igor Lins e Silva 65639a2372 cleanup 2022-10-19 08:39:47 -03:00
Igor Lins e Silva 2a2912e907 Typescript ESM + NodeNext refactor 2022-10-19 08:05:42 -03:00
Igor Lins e Silva e65bebae11 update license to MIT 2022-10-19 08:04:49 -03:00
Igor Lins e Silva a60c0f2c1e Update .gitignore 2022-10-19 08:04:23 -03:00
Igor Lins e Silva f0c45826b9 upgrade node-abieos 2022-10-17 09:02:50 -03:00
Igor Lins e Silva 97bf46bd82 Delete connections.json.bak 2022-03-27 21:07:04 -03:00
Igor Lins e Silva 49e591ee55 temporary local node-abieos 2022-03-22 22:30:49 -03:00
Igor Lins e Silva 11b87d37b6 strict ESM conversion 2022-03-22 19:24:34 -03:00
Igor Lins e Silva 82cf383b71 strict ESM conversion 2022-03-22 06:04:33 -03:00
Igor Lins e Silva 470f0be873 strict ESM conversion 2022-03-22 04:50:59 -03:00
Igor Lins e Silva 3c72b0919d fix error message on "new chain" 2022-03-22 03:14:21 -03:00
Igor Lins e Silva 38d7e835d5 v3.4.0
new commands:
- hyp-config init
- hyp-config connections test
- hyp-config connections reset
2022-03-22 03:09:38 -03:00
Igor Lins e Silva 1d865d5c5d update helper permissions 2022-03-21 23:54:55 -03:00
Igor Lins e Silva b9e7c21cac update packages and lock fixes 2022-03-21 23:52:59 -03:00
Igor Lins e Silva 448d4a629f v3.4-dev
ES 8.1 upgrades
2022-03-18 22:59:55 -03:00
Igor Lins e Silva 62ee9b2ac7 Merge pull request #82 from eosrio/v3.3.5-fix-install-env
Fix install env script
2022-02-09 11:31:52 -03:00
Thiago Souza 6d0c91c6a4 move rabbitmq installation script to correct place 2022-02-09 11:50:09 +00:00
Thiago Souza 73876475ea use jvm.options.d to configure elasticsearch 2022-02-09 11:05:49 +00:00
Igor Lins e Silva 7d14977702 Merge pull request #80 from bensig/v3.3.5
install_env.sh: Remove comment from es user
2022-02-05 01:06:15 -03:00
bensig 9cdf8db87a Update to node 16 2022-02-04 20:02:14 -08:00
bensig 68c1497e74 install_env.sh: Remove comment from es user
hyp-config: fix ts error
install_env.sh fix dl.bintray.com issue

Signed-off-by: bensig <bensig@gmail.com>
2022-02-04 19:12:21 -08:00
Igor Lins e Silva a7df9fb826 Merge pull request #76 from ankh2054/v3.3.5
Updated code to reflect log file text of no blocks processed.
2022-01-15 19:15:21 -03:00
Igor Lins e Silva c570b6e4c4 add settings.es_replicas
define number of replicas for the templates
2022-01-12 10:40:10 -03:00
Charles Holtzkampf 884d944937 changes to how logfile text displays of no block processed 2021-12-29 11:03:49 +05:00
Charles Holtzkampf 5711353471 changes to how logfile text displays of no block processed 2021-12-29 10:57:50 +05:00
Igor Lins e Silva bd8fe99594 Merge pull request #70 from ankh2054/v3.3.5
Update README.MD - specify version of Elasticsearch.
2021-12-09 17:05:47 -03:00
Charles Holtzkampf 9cfea6bb72 Update README.MD 2021-12-07 06:31:35 +00:00
Charles Holtzkampf 6825b743b6 Update README.MD 2021-12-06 20:38:43 +00:00
Igor Lins e Silva 12fc936075 allow injecting IPC handlers from plugins to master 2021-11-29 03:06:52 -03:00
Igor Lins e Silva 2e5bd27e1b include plugin initOnce entrypoint 2021-11-26 02:32:33 -03:00
Igor Lins e Silva a3420a27c0 add support for plugin stream handlers 2021-11-26 01:31:40 -03:00
Igor Lins e Silva 7212ca8397 update & cleanup 2021-11-25 23:48:19 -03:00
Igor Lins e Silva c1366bad75 move tooling scripts to separate folders 2021-11-25 23:48:02 -03:00
Igor Lins e Silva ba273f96d1 Merge pull request #68 from ankh2054/v3.3.5
python script to identify and fix missing blocks
2021-11-25 23:44:01 -03:00
Charles Holtzkampf 03ce188b96 python fix block thingy 2021-11-15 09:28:09 +00:00
Igor Lins e Silva 8633c19792 include signatures on get_actions schema 2021-11-04 12:56:38 -03:00
Igor Lins e Silva 7eb46ece9d cleanup + no-explorer launch fix 2021-10-11 16:13:44 -03:00
Igor Lins e Silva 862817bbe3 Update deserializer.ts 2021-10-11 14:38:50 -03:00
Igor Lins e Silva 917a17b392 Update deserializer.ts 2021-10-11 14:36:23 -03:00
Igor Lins e Silva 3f26e0d518 Update deserializer.ts 2021-10-11 14:29:43 -03:00
Igor Lins e Silva 139a3b85e8 allow passing POST requests to cache manager 2021-09-19 05:12:16 +04:00
Igor Lins e Silva b82382fc5e Merge pull request #64 from poplexity/v3.3.5
Add support for git repo URLs
2021-09-17 20:00:41 -03:00
Jesse Schulman 67b1da2c82 Add support for git repo URLs 2021-09-17 15:58:17 -07:00
João Barbosa fc0e57ca57 Small change on hyp-config list chains output 2021-09-17 15:19:37 -03:00
Igor Lins e Silva 13ad1445e5 remove ecosystem file from gitignore 2021-09-16 23:47:14 -03:00
Igor Lins e Silva 4c127a4d39 3.3.5 2021-09-16 12:06:19 -03:00
Igor Lins e Silva 03a56359da Update package.json 2021-09-13 15:53:37 -03:00
Igor Lins e Silva 6afb85fd57 3.3.5 cleanup 2021-09-13 15:53:00 -03:00
Igor Lins e Silva 2c95cfbcf5 Update .gitignore 2021-09-13 04:16:05 -03:00
Igor Lins e Silva 8552dbf31e Update example.config.json 2021-09-13 04:14:46 -03:00
Igor Lins e Silva f545aad172 Update .gitignore 2021-09-13 04:14:36 -03:00
Igor Lins e Silva 5e68b54610 Update .gitignore 2021-09-13 04:14:16 -03:00
Igor Lins e Silva 1e79521ccc add 1 to the total indexed blocks to counter the missing block 1 on ship 2021-09-09 22:32:23 -03:00
Igor Lins e Silva 18ef675b88 cleanup 2021-09-09 03:27:14 -03:00
Igor Lins e Silva 0947f43b38 fix missing deltas on 2.1 2021-09-09 03:23:23 -03:00
Igor Lins e Silva 0d5d438378 fix heatmap mode 2021-09-09 02:54:13 -03:00
Igor Lins e Silva e678678fef assert queue to avoid race condition 2021-09-08 23:37:36 -03:00
Igor Lins e Silva 0eaba697eb Update get_abi_snapshot.ts 2021-09-08 23:18:56 -03:00
Igor Lins e Silva 80bd4adc8c 3.3.4-rc7
- include config disable_rate_limit
- minor package upgrades
- date parser fix
2021-09-06 10:23:58 -03:00
Igor Lins e Silva 81ae93b1bd Merge pull request #62 from eosrio/es-8-alpha
Es 8 alpha
2021-09-06 10:12:43 -03:00
Igor Lins e Silva 49d3b3434c Update elastic-routes.ts 2021-09-06 10:11:04 -03:00
Igor Lins e Silva 350d2107fe 3.3.4-rc7
validate date inputs before forwarding to ES
avoid duplicated checking of failed token balances
2021-09-06 10:04:24 -03:00
Igor Lins e Silva eda6655600 implement tx caching on v1 get_transaction 2021-08-26 01:39:39 -03:00
Igor Lins e Silva 8ed55f003d allow pre-deserialized block struct 2021-08-22 22:53:00 -03:00
Igor Lins e Silva db3c18fdf9 Update ecosystem_settings.js 2021-08-20 00:17:30 -03:00
Igor Lins e Silva 2d58c18048 Update ecosystem_settings.js 2021-08-20 00:16:32 -03:00
Igor Lins e Silva e21e3dd314 update packages 2021-08-17 00:38:51 -03:00
Igor Lins e Silva d854b339f9 cleanup 2021-08-17 00:32:55 -03:00
Igor Lins e Silva 3026ab9d25 remove type on bulk request 2021-08-17 00:31:22 -03:00
Igor Lins e Silva 9a7ee17508 Update elastic-routes.ts 2021-08-17 00:24:13 -03:00
Igor Lins e Silva 41dce730db Update elastic-routes.ts 2021-08-17 00:15:45 -03:00
Igor Lins e Silva 4bbc92d888 Update elastic-routes.ts 2021-08-17 00:14:00 -03:00
Igor Lins e Silva b08448812e re-introduce delta present as byte 2021-08-10 07:46:06 -03:00
Igor Lins e Silva 82f31f82ba merge tx_cache feature 2021-08-05 21:54:04 -03:00
Igor Lins e Silva 2a82e5842a v3.3.4-rc6
- update ws to v8
- add indexer.disable_delta_rm option
2021-08-05 20:50:15 -03:00
Igor Lins e Silva f27f5ca2a9 Update server.ts 2021-08-05 13:28:44 -03:00
Igor Lins e Silva cc87fab9cd update packages 3.3.4-rc6 2021-08-05 13:27:37 -03:00
Igor Lins e Silva 5242a757ac cleanup 2021-08-05 13:27:13 -03:00
Igor Lins e Silva d2a16e6059 fix get_transaction empty output + implement cached_lib + allow block_hint 2021-08-05 13:17:30 -03:00
Igor Lins e Silva 99c43af7bf docker updates 2021-07-31 04:45:52 -03:00
Igor Lins e Silva a8452d7906 Update fix-permissions.js 2021-07-27 06:03:39 -03:00
Igor Lins e Silva b8104a1f0c require node v16 2021-07-27 05:59:24 -03:00
Igor Lins e Silva d3b4e75513 Update .gitignore 2021-07-27 05:58:08 -03:00
Igor Lins e Silva 204bb63bd7 3.3.4-rc5 2021-07-21 07:40:02 -03:00
Igor Lins e Silva 034dccfbab Update index.d.ts 2021-07-20 06:17:15 -03:00
Igor Lins e Silva aafd4a3d63 Update routes.ts 2021-07-20 06:17:06 -03:00
Igor Lins e Silva cbe37827fc fix error handling on amqp 2021-07-12 14:23:40 -03:00
Igor Lins e Silva aa3487b238 Update example-connections.json 2021-07-12 00:15:49 -03:00
Igor Lins e Silva c090822d3b re-add frameMax patch 2021-07-12 00:14:30 -03:00
Igor Lins e Silva 0564efd4ac Update .gitignore 2021-07-09 07:22:50 -03:00
291 changed files with 16121 additions and 24908 deletions
+21 -94
View File
@@ -1,9 +1,8 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
node_modules/
.npm
.idea
package-lock.json
*.tsbuildinfo
# Runtime data
pids
@@ -11,99 +10,27 @@ pids
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
# next.js build output
.next
.idea
*.pem
ecosystem.config.js
package-lock.json
connections.json
connections.json2
api_access.log
api_error.log
explorer
api/explorer
.ecosystem.config.js.swp
chains/*
!chains/example.config.json
# plugins
plugins
api/**/*.js
api/**/*.js.map
api/tests
# docker storage
docker/redis/data
docker/elasticsearch/data
docker/rabbitmq/data
docker/eosio/data
hyperion-launcher.js
hyperion-launcher.js.map
# transpiled output
dist
launcher.js
launcher.js.map
# configuration
config
!config/chains/example.config.json
connections/**/*.js
connections/**/*.js.map
# logging
logs
definitions/**/*.js
definitions/**/*.js.map
workers/**/*.js
workers/**/*.js.map
helpers/**/*.js
helpers/**/*.js.map
interfaces/**/*.js
interfaces/**/*.js.map
modules/**/*.js
modules/**/*.js.map
addons/**/*.js
addons/**/*.js.map
plugins/repos
# chain state temp files
state
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019-2022 Rio Blocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-50
View File
@@ -1,50 +0,0 @@
import { Abi, PushTransactionArgs } from './eosjs-rpc-interfaces';
/** Arguments to `getRequiredKeys` */
export interface AuthorityProviderArgs {
/** Transaction that needs to be signed */
transaction: any;
/** Public keys associated with the private keys that the `SignatureProvider` holds */
availableKeys: string[];
}
/** Get subset of `availableKeys` needed to meet authorities in `transaction` */
export interface AuthorityProvider {
/** Get subset of `availableKeys` needed to meet authorities in `transaction` */
getRequiredKeys: (args: AuthorityProviderArgs) => Promise<string[]>;
}
/** Retrieves raw ABIs for a specified accountName */
export interface AbiProvider {
/** Retrieve the BinaryAbi */
getRawAbi: (accountName: string) => Promise<BinaryAbi>;
}
/** Structure for the raw form of ABIs */
export interface BinaryAbi {
/** account which has deployed the ABI */
accountName: string;
/** abi in binary form */
abi: Uint8Array;
}
/** Holds a fetched abi */
export interface CachedAbi {
/** abi in binary form */
rawAbi: Uint8Array;
/** abi in structured form */
abi: Abi;
}
/** Arguments to `sign` */
export interface SignatureProviderArgs {
/** Chain transaction is for */
chainId: string;
/** Public keys associated with the private keys needed to sign the transaction */
requiredKeys: string[];
/** Transaction to sign */
serializedTransaction: Uint8Array;
/** ABIs for all contracts with actions included in `serializedTransaction` */
abis: BinaryAbi[];
}
/** Signs transactions */
export interface SignatureProvider {
/** Public keys associated with the private keys that the `SignatureProvider` holds */
getAvailableKeys: () => Promise<string[]>;
/** Sign a transaction */
sign: (args: SignatureProviderArgs) => Promise<PushTransactionArgs>;
}
@@ -1,4 +0,0 @@
"use strict";
// copyright defined in eosjs/LICENSE.txt
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=eosjs-api-interfaces.js.map
@@ -1 +0,0 @@
{"version":3,"file":"eosjs-api-interfaces.js","sourceRoot":"","sources":["../src/eosjs-api-interfaces.ts"],"names":[],"mappings":";AAAA,yCAAyC"}
-92
View File
@@ -1,92 +0,0 @@
/**
* @module API
*/
import { AbiProvider, AuthorityProvider, BinaryAbi, CachedAbi, SignatureProvider } from './eosjs-api-interfaces';
import { JsonRpc } from './eosjs-jsonrpc';
import { Abi, PushTransactionArgs } from './eosjs-rpc-interfaces';
import * as ser from './eosjs-serialize';
export declare class Api {
/** Issues RPC calls */
rpc: JsonRpc;
/** Get subset of `availableKeys` needed to meet authorities in a `transaction` */
authorityProvider: AuthorityProvider;
/** Supplies ABIs in raw form (binary) */
abiProvider: AbiProvider;
/** Signs transactions */
signatureProvider: SignatureProvider;
/** Identifies chain */
chainId: string;
textEncoder: TextEncoder;
textDecoder: TextDecoder;
/** Converts abi files between binary and structured form (`abi.abi.json`) */
abiTypes: Map<string, ser.Type>;
/** Converts transactions between binary and structured form (`transaction.abi.json`) */
transactionTypes: Map<string, ser.Type>;
/** Holds information needed to serialize contract actions */
contracts: Map<string, ser.Contract>;
/** Fetched abis */
cachedAbis: Map<string, CachedAbi>;
/**
* @param args
* * `rpc`: Issues RPC calls
* * `authorityProvider`: Get public keys needed to meet authorities in a transaction
* * `abiProvider`: Supplies ABIs in raw form (binary)
* * `signatureProvider`: Signs transactions
* * `chainId`: Identifies chain
* * `textEncoder`: `TextEncoder` instance to use. Pass in `null` if running in a browser
* * `textDecoder`: `TextDecoder` instance to use. Pass in `null` if running in a browser
*/
constructor(args: {
rpc: JsonRpc;
authorityProvider?: AuthorityProvider;
abiProvider?: AbiProvider;
signatureProvider: SignatureProvider;
chainId?: string;
textEncoder?: TextEncoder;
textDecoder?: TextDecoder;
});
/** Decodes an abi as Uint8Array into json. */
rawAbiToJson(rawAbi: Uint8Array): Abi;
/** Get abi in both binary and structured forms. Fetch when needed. */
getCachedAbi(accountName: string, reload?: boolean): Promise<CachedAbi>;
/** Get abi in structured form. Fetch when needed. */
getAbi(accountName: string, reload?: boolean): Promise<Abi>;
/** Get abis needed by a transaction */
getTransactionAbis(transaction: any, reload?: boolean): Promise<BinaryAbi[]>;
/** Get data needed to serialize actions in a contract */
getContract(accountName: string, reload?: boolean): Promise<ser.Contract>;
/** Convert `value` to binary form. `type` must be a built-in abi type or in `transaction.abi.json`. */
serialize(buffer: ser.SerialBuffer, type: string, value: any): void;
/** Convert data in `buffer` to structured form. `type` must be a built-in abi type or in `transaction.abi.json`. */
deserialize(buffer: ser.SerialBuffer, type: string): any;
/** Convert a transaction to binary */
serializeTransaction(transaction: any): Uint8Array;
/** Convert a transaction from binary. Leaves actions in hex. */
deserializeTransaction(transaction: Uint8Array): any;
/** Convert actions to hex */
serializeActions(actions: ser.Action[]): Promise<ser.SerializedAction[]>;
/** Convert actions from hex */
deserializeActions(actions: ser.Action[]): Promise<ser.Action[]>;
/** Convert a transaction from binary. Also deserializes actions. */
deserializeTransactionWithActions(transaction: Uint8Array | string): Promise<any>;
/**
* Create and optionally broadcast a transaction.
*
* Named Parameters:
* * `broadcast`: broadcast this transaction?
* * `sign`: sign this transaction?
* * If both `blocksBehind` and `expireSeconds` are present,
* then fetch the block which is `blocksBehind` behind head block,
* use it as a reference for TAPoS, and expire the transaction `expireSeconds` after that block's time.
* @returns node response if `broadcast`, `{signatures, serializedTransaction}` if `!broadcast`
*/
transact(transaction: any, { broadcast, sign, blocksBehind, expireSeconds }?: {
broadcast?: boolean;
sign?: boolean;
blocksBehind?: number;
expireSeconds?: number;
}): Promise<any>;
/** Broadcast a signed transaction */
pushSignedTransaction({ signatures, serializedTransaction }: PushTransactionArgs): Promise<any>;
private hasRequiredTaposFields;
}
-427
View File
@@ -1,427 +0,0 @@
"use strict";
/**
* @module API
*/
// copyright defined in eosjs/LICENSE.txt
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);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
t[p[i]] = s[p[i]];
return t;
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spread = (this && this.__spread) || function () {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
return ar;
};
var __values = (this && this.__values) || function (o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
};
Object.defineProperty(exports, "__esModule", { value: true });
var ser = require("./eosjs-serialize");
var abiAbi = require('./src/abi.abi.json');
var transactionAbi = require('./src/transaction.abi.json');
var Api = /** @class */ (function () {
/**
* @param args
* * `rpc`: Issues RPC calls
* * `authorityProvider`: Get public keys needed to meet authorities in a transaction
* * `abiProvider`: Supplies ABIs in raw form (binary)
* * `signatureProvider`: Signs transactions
* * `chainId`: Identifies chain
* * `textEncoder`: `TextEncoder` instance to use. Pass in `null` if running in a browser
* * `textDecoder`: `TextDecoder` instance to use. Pass in `null` if running in a browser
*/
function Api(args) {
/** Holds information needed to serialize contract actions */
this.contracts = new Map();
/** Fetched abis */
this.cachedAbis = new Map();
this.rpc = args.rpc;
this.authorityProvider = args.authorityProvider || args.rpc;
this.abiProvider = args.abiProvider || args.rpc;
this.signatureProvider = args.signatureProvider;
this.chainId = args.chainId;
this.textEncoder = args.textEncoder;
this.textDecoder = args.textDecoder;
this.abiTypes = ser.getTypesFromAbi(ser.createInitialTypes(), abiAbi);
this.transactionTypes = ser.getTypesFromAbi(ser.createInitialTypes(), transactionAbi);
}
/** Decodes an abi as Uint8Array into json. */
Api.prototype.rawAbiToJson = function (rawAbi) {
var buffer = new ser.SerialBuffer({
textEncoder: this.textEncoder,
textDecoder: this.textDecoder,
array: rawAbi,
});
if (!ser.supportedAbiVersion(buffer.getString())) {
throw new Error('Unsupported abi version');
}
buffer.restartRead();
return this.abiTypes.get('abi_def').deserialize(buffer);
};
/** Get abi in both binary and structured forms. Fetch when needed. */
Api.prototype.getCachedAbi = function (accountName, reload) {
if (reload === void 0) { reload = false; }
return __awaiter(this, void 0, void 0, function () {
var cachedAbi, rawAbi, abi, e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!reload && this.cachedAbis.get(accountName)) {
return [2 /*return*/, this.cachedAbis.get(accountName)];
}
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.abiProvider.getRawAbi(accountName)];
case 2:
rawAbi = (_a.sent()).abi;
abi = this.rawAbiToJson(rawAbi);
cachedAbi = { rawAbi: rawAbi, abi: abi };
return [3 /*break*/, 4];
case 3:
e_1 = _a.sent();
e_1.message = "fetching abi for " + accountName + ": " + e_1.message;
throw e_1;
case 4:
if (!cachedAbi) {
throw new Error("Missing abi for " + accountName);
}
this.cachedAbis.set(accountName, cachedAbi);
return [2 /*return*/, cachedAbi];
}
});
});
};
/** Get abi in structured form. Fetch when needed. */
Api.prototype.getAbi = function (accountName, reload) {
if (reload === void 0) { reload = false; }
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getCachedAbi(accountName, reload)];
case 1: return [2 /*return*/, (_a.sent()).abi];
}
});
});
};
/** Get abis needed by a transaction */
Api.prototype.getTransactionAbis = function (transaction, reload) {
if (reload === void 0) { reload = false; }
return __awaiter(this, void 0, void 0, function () {
var accounts, uniqueAccounts, actionPromises;
var _this = this;
return __generator(this, function (_a) {
accounts = transaction.actions.map(function (action) { return action.account; });
uniqueAccounts = new Set(accounts);
actionPromises = __spread(uniqueAccounts).map(function (account) { return __awaiter(_this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = {
accountName: account
};
return [4 /*yield*/, this.getCachedAbi(account, reload)];
case 1: return [2 /*return*/, (_a.abi = (_b.sent()).rawAbi,
_a)];
}
});
}); });
return [2 /*return*/, Promise.all(actionPromises)];
});
});
};
/** Get data needed to serialize actions in a contract */
Api.prototype.getContract = function (accountName, reload) {
if (reload === void 0) { reload = false; }
return __awaiter(this, void 0, void 0, function () {
var e_2, _a, abi, types, actions, _b, _c, _d, name_1, type, result;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
if (!reload && this.contracts.get(accountName)) {
return [2 /*return*/, this.contracts.get(accountName)];
}
return [4 /*yield*/, this.getAbi(accountName, reload)];
case 1:
abi = _e.sent();
types = ser.getTypesFromAbi(ser.createInitialTypes(), abi);
actions = new Map();
try {
for (_b = __values(abi.actions), _c = _b.next(); !_c.done; _c = _b.next()) {
_d = _c.value, name_1 = _d.name, type = _d.type;
actions.set(name_1, ser.getType(types, type));
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_2) throw e_2.error; }
}
result = { types: types, actions: actions };
this.contracts.set(accountName, result);
return [2 /*return*/, result];
}
});
});
};
/** Convert `value` to binary form. `type` must be a built-in abi type or in `transaction.abi.json`. */
Api.prototype.serialize = function (buffer, type, value) {
this.transactionTypes.get(type).serialize(buffer, value);
};
/** Convert data in `buffer` to structured form. `type` must be a built-in abi type or in `transaction.abi.json`. */
Api.prototype.deserialize = function (buffer, type) {
return this.transactionTypes.get(type).deserialize(buffer);
};
/** Convert a transaction to binary */
Api.prototype.serializeTransaction = function (transaction) {
var buffer = new ser.SerialBuffer({ textEncoder: this.textEncoder, textDecoder: this.textDecoder });
this.serialize(buffer, 'transaction', __assign({ max_net_usage_words: 0, max_cpu_usage_ms: 0, delay_sec: 0, context_free_actions: [], actions: [], transaction_extensions: [] }, transaction));
return buffer.asUint8Array();
};
/** Convert a transaction from binary. Leaves actions in hex. */
Api.prototype.deserializeTransaction = function (transaction) {
var buffer = new ser.SerialBuffer({ textEncoder: this.textEncoder, textDecoder: this.textDecoder });
buffer.pushArray(transaction);
return this.deserialize(buffer, 'transaction');
};
/** Convert actions to hex */
Api.prototype.serializeActions = function (actions) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, Promise.all(actions.map(function (_a) {
var account = _a.account, name = _a.name, authorization = _a.authorization, data = _a.data;
return __awaiter(_this, void 0, void 0, function () {
var contract;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, this.getContract(account)];
case 1:
contract = _b.sent();
return [2 /*return*/, ser.serializeAction(contract, account, name, authorization, data, this.textEncoder, this.textDecoder)];
}
});
});
}))];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/** Convert actions from hex */
Api.prototype.deserializeActions = function (actions) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, Promise.all(actions.map(function (_a) {
var account = _a.account, name = _a.name, authorization = _a.authorization, data = _a.data;
return __awaiter(_this, void 0, void 0, function () {
var contract;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, this.getContract(account)];
case 1:
contract = _b.sent();
return [2 /*return*/, ser.deserializeAction(contract, account, name, authorization, data, this.textEncoder, this.textDecoder)];
}
});
});
}))];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/** Convert a transaction from binary. Also deserializes actions. */
Api.prototype.deserializeTransactionWithActions = function (transaction) {
return __awaiter(this, void 0, void 0, function () {
var deserializedTransaction, deserializedActions;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (typeof transaction === 'string') {
transaction = ser.hexToUint8Array(transaction);
}
deserializedTransaction = this.deserializeTransaction(transaction);
return [4 /*yield*/, this.deserializeActions(deserializedTransaction.actions)];
case 1:
deserializedActions = _a.sent();
return [2 /*return*/, __assign({}, deserializedTransaction, { actions: deserializedActions })];
}
});
});
};
/**
* Create and optionally broadcast a transaction.
*
* Named Parameters:
* * `broadcast`: broadcast this transaction?
* * `sign`: sign this transaction?
* * If both `blocksBehind` and `expireSeconds` are present,
* then fetch the block which is `blocksBehind` behind head block,
* use it as a reference for TAPoS, and expire the transaction `expireSeconds` after that block's time.
* @returns node response if `broadcast`, `{signatures, serializedTransaction}` if `!broadcast`
*/
Api.prototype.transact = function (transaction, _a) {
var _b = _a === void 0 ? {} : _a, _c = _b.broadcast, broadcast = _c === void 0 ? true : _c, _d = _b.sign, sign = _d === void 0 ? true : _d, blocksBehind = _b.blocksBehind, expireSeconds = _b.expireSeconds;
return __awaiter(this, void 0, void 0, function () {
var info, refBlock, abis, _e, _f, serializedTransaction, pushTransactionArgs, availableKeys, requiredKeys;
return __generator(this, function (_g) {
switch (_g.label) {
case 0:
if (!!this.chainId) return [3 /*break*/, 2];
return [4 /*yield*/, this.rpc.get_info()];
case 1:
info = _g.sent();
this.chainId = info.chain_id;
_g.label = 2;
case 2:
if (!(typeof blocksBehind === 'number' && expireSeconds)) return [3 /*break*/, 6];
if (!!info) return [3 /*break*/, 4];
return [4 /*yield*/, this.rpc.get_info()];
case 3:
info = _g.sent();
_g.label = 4;
case 4: return [4 /*yield*/, this.rpc.get_block(info.head_block_num - blocksBehind)];
case 5:
refBlock = _g.sent();
transaction = __assign({}, ser.transactionHeader(refBlock, expireSeconds), transaction);
_g.label = 6;
case 6:
if (!this.hasRequiredTaposFields(transaction)) {
throw new Error('Required configuration or TAPOS fields are not present');
}
return [4 /*yield*/, this.getTransactionAbis(transaction)];
case 7:
abis = _g.sent();
_e = [{}, transaction];
_f = {};
return [4 /*yield*/, this.serializeActions(transaction.actions)];
case 8:
transaction = __assign.apply(void 0, _e.concat([(_f.actions = _g.sent(), _f)]));
serializedTransaction = this.serializeTransaction(transaction);
pushTransactionArgs = { serializedTransaction: serializedTransaction, signatures: [] };
if (!sign) return [3 /*break*/, 12];
return [4 /*yield*/, this.signatureProvider.getAvailableKeys()];
case 9:
availableKeys = _g.sent();
return [4 /*yield*/, this.authorityProvider.getRequiredKeys({ transaction: transaction, availableKeys: availableKeys })];
case 10:
requiredKeys = _g.sent();
return [4 /*yield*/, this.signatureProvider.sign({
chainId: this.chainId,
requiredKeys: requiredKeys,
serializedTransaction: serializedTransaction,
abis: abis,
})];
case 11:
pushTransactionArgs = _g.sent();
_g.label = 12;
case 12:
if (broadcast) {
return [2 /*return*/, this.pushSignedTransaction(pushTransactionArgs)];
}
return [2 /*return*/, pushTransactionArgs];
}
});
});
};
/** Broadcast a signed transaction */
Api.prototype.pushSignedTransaction = function (_a) {
var signatures = _a.signatures, serializedTransaction = _a.serializedTransaction;
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_b) {
return [2 /*return*/, this.rpc.push_transaction({
signatures: signatures,
serializedTransaction: serializedTransaction,
})];
});
});
};
// eventually break out into TransactionValidator class
Api.prototype.hasRequiredTaposFields = function (_a) {
var expiration = _a.expiration, ref_block_num = _a.ref_block_num, ref_block_prefix = _a.ref_block_prefix, transaction = __rest(_a, ["expiration", "ref_block_num", "ref_block_prefix"]);
return !!(expiration && ref_block_num && ref_block_prefix);
};
return Api;
}()); // Api
exports.Api = Api;
//# sourceMappingURL=eosjs-api.js.map
File diff suppressed because one or more lines are too long
-63
View File
@@ -1,63 +0,0 @@
/**
* @module JSON-RPC
*/
import { AbiProvider, AuthorityProvider, AuthorityProviderArgs, BinaryAbi } from './eosjs-api-interfaces';
import { GetAbiResult, GetBlockResult, GetCodeResult, GetInfoResult, GetRawCodeAndAbiResult, PushTransactionArgs } from "./eosjs-rpc-interfaces";
/** Make RPC calls */
export declare class JsonRpc implements AuthorityProvider, AbiProvider {
endpoint: string;
fetchBuiltin: (input?: Request | string, init?: RequestInit) => Promise<Response>;
/**
* @param args
* * `fetch`:
* * browsers: leave `null` or `undefined`
* * node: provide an implementation
*/
constructor(endpoint: string, args?: {
fetch?: (input?: string | Request, init?: RequestInit) => Promise<Response>;
});
/** Post `body` to `endpoint + path`. Throws detailed error information in `RpcError` when available. */
fetch(path: string, body: any): Promise<any>;
/** Raw call to `/v1/chain/get_abi` */
get_abi(accountName: string): Promise<GetAbiResult>;
/** Raw call to `/v1/chain/get_account` */
get_account(accountName: string): Promise<any>;
/** Raw call to `/v1/chain/get_block_header_state` */
get_block_header_state(blockNumOrId: number | string): Promise<any>;
/** Raw call to `/v1/chain/get_block` */
get_block(blockNumOrId: number | string): Promise<GetBlockResult>;
/** Raw call to `/v1/chain/get_code` */
get_code(accountName: string): Promise<GetCodeResult>;
/** Raw call to `/v1/chain/get_currency_balance` */
get_currency_balance(code: string, account: string, symbol?: string): Promise<any>;
/** Raw call to `/v1/chain/get_currency_stats` */
get_currency_stats(code: string, symbol: string): Promise<any>;
/** Raw call to `/v1/chain/get_info` */
get_info(): Promise<GetInfoResult>;
/** Raw call to `/v1/chain/get_producer_schedule` */
get_producer_schedule(): Promise<any>;
/** Raw call to `/v1/chain/get_producers` */
get_producers(json?: boolean, lowerBound?: string, limit?: number): Promise<any>;
/** Raw call to `/v1/chain/get_raw_code_and_abi` */
get_raw_code_and_abi(accountName: string): Promise<GetRawCodeAndAbiResult>;
/** calls `/v1/chain/get_raw_code_and_abi` and pulls out unneeded raw wasm code */
getRawAbi(accountName: string): Promise<BinaryAbi>;
/** Raw call to `/v1/chain/get_table_rows` */
get_table_rows({ json, code, scope, table, table_key, lower_bound, upper_bound, index_position, key_type, limit, reverse, show_payer, }: any): Promise<any>;
/** Raw call to `/v1/chain/get_table_by_scope` */
get_table_by_scope({ code, table, lower_bound, upper_bound, limit, }: any): Promise<any>;
/** Get subset of `availableKeys` needed to meet authorities in `transaction`. Implements `AuthorityProvider` */
getRequiredKeys(args: AuthorityProviderArgs): Promise<string[]>;
/** Push a serialized transaction */
push_transaction({ signatures, serializedTransaction }: PushTransactionArgs): Promise<any>;
/** Raw call to `/v1/db_size/get` */
db_size_get(): Promise<any>;
/** Raw call to `/v1/history/get_actions` */
history_get_actions(accountName: string, pos?: number, offset?: number): Promise<any>;
/** Raw call to `/v1/history/get_transaction` */
history_get_transaction(id: string, blockNumHint?: number): Promise<any>;
/** Raw call to `/v1/history/get_key_accounts` */
history_get_key_accounts(publicKey: string): Promise<any>;
/** Raw call to `/v1/history/get_controlled_accounts` */
history_get_controlled_accounts(controllingAccount: string): Promise<any>;
}
-402
View File
@@ -1,402 +0,0 @@
"use strict";
/**
* @module JSON-RPC
*/
// copyright defined in eosjs/LICENSE.txt
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __values = (this && this.__values) || function (o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
};
Object.defineProperty(exports, "__esModule", { value: true });
var eosjs_numeric_1 = require("./eosjs-numeric");
var eosjs_rpcerror_1 = require("./eosjs-rpcerror");
function arrayToHex(data) {
var e_1, _a;
var result = '';
try {
for (var data_1 = __values(data), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) {
var x = data_1_1.value;
result += ('00' + x.toString(16)).slice(-2);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (data_1_1 && !data_1_1.done && (_a = data_1.return)) _a.call(data_1);
}
finally { if (e_1) throw e_1.error; }
}
return result;
}
/** Make RPC calls */
var JsonRpc = /** @class */ (function () {
/**
* @param args
* * `fetch`:
* * browsers: leave `null` or `undefined`
* * node: provide an implementation
*/
function JsonRpc(endpoint, args) {
if (args === void 0) { args = {}; }
this.endpoint = endpoint;
if (args.fetch) {
this.fetchBuiltin = args.fetch;
}
else {
this.fetchBuiltin = global.fetch;
}
}
/** Post `body` to `endpoint + path`. Throws detailed error information in `RpcError` when available. */
JsonRpc.prototype.fetch = function (path, body) {
return __awaiter(this, void 0, void 0, function () {
var response, json, f, e_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 3, , 4]);
f = this.fetchBuiltin;
return [4 /*yield*/, f(this.endpoint + path, {
body: JSON.stringify(body),
method: 'POST',
})];
case 1:
response = _a.sent();
return [4 /*yield*/, response.json()];
case 2:
json = _a.sent();
if (json.processed && json.processed.except) {
throw new eosjs_rpcerror_1.RpcError(json);
}
return [3 /*break*/, 4];
case 3:
e_2 = _a.sent();
e_2.isFetchError = true;
throw e_2;
case 4:
if (!response.ok) {
throw new eosjs_rpcerror_1.RpcError(json);
}
return [2 /*return*/, json];
}
});
});
};
/** Raw call to `/v1/chain/get_abi` */
JsonRpc.prototype.get_abi = function (accountName) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.fetch('/v1/chain/get_abi', { account_name: accountName })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/** Raw call to `/v1/chain/get_account` */
JsonRpc.prototype.get_account = function (accountName) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.fetch('/v1/chain/get_account', { account_name: accountName })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/** Raw call to `/v1/chain/get_block_header_state` */
JsonRpc.prototype.get_block_header_state = function (blockNumOrId) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.fetch('/v1/chain/get_block_header_state', { block_num_or_id: blockNumOrId })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/** Raw call to `/v1/chain/get_block` */
JsonRpc.prototype.get_block = function (blockNumOrId) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.fetch('/v1/chain/get_block', { block_num_or_id: blockNumOrId })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/** Raw call to `/v1/chain/get_code` */
JsonRpc.prototype.get_code = function (accountName) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.fetch('/v1/chain/get_code', { account_name: accountName })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/** Raw call to `/v1/chain/get_currency_balance` */
JsonRpc.prototype.get_currency_balance = function (code, account, symbol) {
if (symbol === void 0) { symbol = null; }
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.fetch('/v1/chain/get_currency_balance', { code: code, account: account, symbol: symbol })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/** Raw call to `/v1/chain/get_currency_stats` */
JsonRpc.prototype.get_currency_stats = function (code, symbol) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.fetch('/v1/chain/get_currency_stats', { code: code, symbol: symbol })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/** Raw call to `/v1/chain/get_info` */
JsonRpc.prototype.get_info = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.fetch('/v1/chain/get_info', {})];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/** Raw call to `/v1/chain/get_producer_schedule` */
JsonRpc.prototype.get_producer_schedule = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.fetch('/v1/chain/get_producer_schedule', {})];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/** Raw call to `/v1/chain/get_producers` */
JsonRpc.prototype.get_producers = function (json, lowerBound, limit) {
if (json === void 0) { json = true; }
if (lowerBound === void 0) { lowerBound = ''; }
if (limit === void 0) { limit = 50; }
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.fetch('/v1/chain/get_producers', { json: json, lower_bound: lowerBound, limit: limit })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/** Raw call to `/v1/chain/get_raw_code_and_abi` */
JsonRpc.prototype.get_raw_code_and_abi = function (accountName) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.fetch('/v1/chain/get_raw_code_and_abi', { account_name: accountName })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/** calls `/v1/chain/get_raw_code_and_abi` and pulls out unneeded raw wasm code */
// TODO: use `/v1/chain/get_raw_abi` directly when it becomes available
JsonRpc.prototype.getRawAbi = function (accountName) {
return __awaiter(this, void 0, void 0, function () {
var rawCodeAndAbi, abi;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.get_raw_code_and_abi(accountName)];
case 1:
rawCodeAndAbi = _a.sent();
abi = eosjs_numeric_1.base64ToBinary(rawCodeAndAbi.abi);
return [2 /*return*/, { accountName: rawCodeAndAbi.account_name, abi: abi }];
}
});
});
};
/** Raw call to `/v1/chain/get_table_rows` */
JsonRpc.prototype.get_table_rows = function (_a) {
var _b = _a.json, json = _b === void 0 ? true : _b, code = _a.code, scope = _a.scope, table = _a.table, _c = _a.table_key, table_key = _c === void 0 ? '' : _c, _d = _a.lower_bound, lower_bound = _d === void 0 ? '' : _d, _e = _a.upper_bound, upper_bound = _e === void 0 ? '' : _e, _f = _a.index_position, index_position = _f === void 0 ? 1 : _f, _g = _a.key_type, key_type = _g === void 0 ? '' : _g, _h = _a.limit, limit = _h === void 0 ? 10 : _h, _j = _a.reverse, reverse = _j === void 0 ? false : _j, _k = _a.show_payer, show_payer = _k === void 0 ? false : _k;
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_l) {
switch (_l.label) {
case 0: return [4 /*yield*/, this.fetch('/v1/chain/get_table_rows', {
json: json,
code: code,
scope: scope,
table: table,
table_key: table_key,
lower_bound: lower_bound,
upper_bound: upper_bound,
index_position: index_position,
key_type: key_type,
limit: limit,
reverse: reverse,
show_payer: show_payer,
})];
case 1: return [2 /*return*/, _l.sent()];
}
});
});
};
/** Raw call to `/v1/chain/get_table_by_scope` */
JsonRpc.prototype.get_table_by_scope = function (_a) {
var code = _a.code, table = _a.table, _b = _a.lower_bound, lower_bound = _b === void 0 ? '' : _b, _c = _a.upper_bound, upper_bound = _c === void 0 ? '' : _c, _d = _a.limit, limit = _d === void 0 ? 10 : _d;
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_e) {
switch (_e.label) {
case 0: return [4 /*yield*/, this.fetch('/v1/chain/get_table_by_scope', {
code: code,
table: table,
lower_bound: lower_bound,
upper_bound: upper_bound,
limit: limit,
})];
case 1: return [2 /*return*/, _e.sent()];
}
});
});
};
/** Get subset of `availableKeys` needed to meet authorities in `transaction`. Implements `AuthorityProvider` */
JsonRpc.prototype.getRequiredKeys = function (args) {
return __awaiter(this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = eosjs_numeric_1.convertLegacyPublicKeys;
return [4 /*yield*/, this.fetch('/v1/chain/get_required_keys', {
transaction: args.transaction,
available_keys: args.availableKeys,
})];
case 1: return [2 /*return*/, _a.apply(void 0, [(_b.sent()).required_keys])];
}
});
});
};
/** Push a serialized transaction */
JsonRpc.prototype.push_transaction = function (_a) {
var signatures = _a.signatures, serializedTransaction = _a.serializedTransaction;
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, this.fetch('/v1/chain/push_transaction', {
signatures: signatures,
compression: 0,
packed_context_free_data: '',
packed_trx: arrayToHex(serializedTransaction),
})];
case 1: return [2 /*return*/, _b.sent()];
}
});
});
};
/** Raw call to `/v1/db_size/get` */
JsonRpc.prototype.db_size_get = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.fetch('/v1/db_size/get', {})];
case 1: return [2 /*return*/, _a.sent()];
}
}); });
};
/** Raw call to `/v1/history/get_actions` */
JsonRpc.prototype.history_get_actions = function (accountName, pos, offset) {
if (pos === void 0) { pos = null; }
if (offset === void 0) { offset = null; }
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.fetch('/v1/history/get_actions', { account_name: accountName, pos: pos, offset: offset })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/** Raw call to `/v1/history/get_transaction` */
JsonRpc.prototype.history_get_transaction = function (id, blockNumHint) {
if (blockNumHint === void 0) { blockNumHint = null; }
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.fetch('/v1/history/get_transaction', { id: id, block_num_hint: blockNumHint })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/** Raw call to `/v1/history/get_key_accounts` */
JsonRpc.prototype.history_get_key_accounts = function (publicKey) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.fetch('/v1/history/get_key_accounts', { public_key: publicKey })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/** Raw call to `/v1/history/get_controlled_accounts` */
JsonRpc.prototype.history_get_controlled_accounts = function (controllingAccount) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.fetch('/v1/history/get_controlled_accounts', { controlling_account: controllingAccount })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
return JsonRpc;
}()); // JsonRpc
exports.JsonRpc = JsonRpc;
//# sourceMappingURL=eosjs-jsonrpc.js.map
File diff suppressed because one or more lines are too long
-20
View File
@@ -1,20 +0,0 @@
/**
* @module JS-Sig
*/
import { SignatureProvider, SignatureProviderArgs } from './eosjs-api-interfaces';
/** Signs transactions using in-process private keys */
export declare class JsSignatureProvider implements SignatureProvider {
/** map public to private keys */
keys: Map<string, string>;
/** public keys */
availableKeys: string[];
/** @param privateKeys private keys to sign with */
constructor(privateKeys: string[]);
/** Public keys associated with the private keys that the `SignatureProvider` holds */
getAvailableKeys(): Promise<string[]>;
/** Sign a transaction */
sign({ chainId, requiredKeys, serializedTransaction }: SignatureProviderArgs): Promise<{
signatures: any[];
serializedTransaction: Uint8Array;
}>;
}
-105
View File
@@ -1,105 +0,0 @@
"use strict";
/**
* @module JS-Sig
*/
// copyright defined in eosjs/LICENSE.txt
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __values = (this && this.__values) || function (o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
};
Object.defineProperty(exports, "__esModule", { value: true });
var ecc = require("eosjs-ecc");
var eosjs_numeric_1 = require("./eosjs-numeric");
/** Signs transactions using in-process private keys */
var JsSignatureProvider = /** @class */ (function () {
/** @param privateKeys private keys to sign with */
function JsSignatureProvider(privateKeys) {
var e_1, _a;
/** map public to private keys */
this.keys = new Map();
/** public keys */
this.availableKeys = [];
try {
for (var privateKeys_1 = __values(privateKeys), privateKeys_1_1 = privateKeys_1.next(); !privateKeys_1_1.done; privateKeys_1_1 = privateKeys_1.next()) {
var k = privateKeys_1_1.value;
var pub = eosjs_numeric_1.convertLegacyPublicKey(ecc.PrivateKey.fromString(k).toPublic().toString());
this.keys.set(pub, k);
this.availableKeys.push(pub);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (privateKeys_1_1 && !privateKeys_1_1.done && (_a = privateKeys_1.return)) _a.call(privateKeys_1);
}
finally { if (e_1) throw e_1.error; }
}
}
/** Public keys associated with the private keys that the `SignatureProvider` holds */
JsSignatureProvider.prototype.getAvailableKeys = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.availableKeys];
});
});
};
/** Sign a transaction */
JsSignatureProvider.prototype.sign = function (_a) {
var chainId = _a.chainId, requiredKeys = _a.requiredKeys, serializedTransaction = _a.serializedTransaction;
return __awaiter(this, void 0, void 0, function () {
var signBuf, signatures;
var _this = this;
return __generator(this, function (_b) {
signBuf = Buffer.concat([
new Buffer(chainId, 'hex'), new Buffer(serializedTransaction), new Buffer(new Uint8Array(32)),
]);
signatures = requiredKeys.map(function (pub) { return ecc.Signature.sign(signBuf, _this.keys.get(eosjs_numeric_1.convertLegacyPublicKey(pub))).toString(); });
return [2 /*return*/, { signatures: signatures, serializedTransaction: serializedTransaction }];
});
});
};
return JsSignatureProvider;
}());
exports.JsSignatureProvider = JsSignatureProvider;
//# sourceMappingURL=eosjs-jssig.js.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"eosjs-jssig.js","sourceRoot":"","sources":["../src/eosjs-jssig.ts"],"names":[],"mappings":";AAAA;;GAEG;AACH,yCAAyC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEzC,+BAAiC;AAEjC,iDAAyD;AAEzD,uDAAuD;AACvD;IAOI,mDAAmD;IACnD,6BAAY,WAAqB;;QAPjC,iCAAiC;QAC1B,SAAI,GAAG,IAAI,GAAG,EAAkB,CAAC;QAExC,kBAAkB;QACX,kBAAa,GAAG,EAAc,CAAC;;YAIlC,KAAgB,IAAA,gBAAA,SAAA,WAAW,CAAA,wCAAA,iEAAE;gBAAxB,IAAM,CAAC,wBAAA;gBACR,IAAM,GAAG,GAAG,sCAAsB,CAAC,GAAG,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAC;gBACvF,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;gBACtB,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;aAChC;;;;;;;;;IACL,CAAC;IAED,sFAAsF;IACzE,8CAAgB,GAA7B;;;gBACI,sBAAO,IAAI,CAAC,aAAa,EAAC;;;KAC7B;IAED,yBAAyB;IACZ,kCAAI,GAAjB,UAAkB,EAAuE;YAArE,oBAAO,EAAE,8BAAY,EAAE,gDAAqB;;;;;gBACtD,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC;oBAC1B,IAAI,MAAM,CAAC,OAAO,EAAE,KAAK,CAAC,EAAE,IAAI,MAAM,CAAC,qBAAqB,CAAC,EAAE,IAAI,MAAM,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;iBAChG,CAAC,CAAC;gBACG,UAAU,GAAG,YAAY,CAAC,GAAG,CAC/B,UAAC,GAAG,IAAK,OAAA,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,EAAE,KAAI,CAAC,IAAI,CAAC,GAAG,CAAC,sCAAsB,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,EAAlF,CAAkF,CAC9F,CAAC;gBACF,sBAAO,EAAE,UAAU,YAAA,EAAE,qBAAqB,uBAAA,EAAE,EAAC;;;KAChD;IACL,0BAAC;AAAD,CAAC,AA/BD,IA+BC;AA/BY,kDAAmB"}
-75
View File
@@ -1,75 +0,0 @@
/**
* @module Numeric
*/
/** Is `bignum` a negative number? */
export declare function isNegative(bignum: Uint8Array): boolean;
/** Negate `bignum` */
export declare function negate(bignum: Uint8Array): void;
/**
* Convert an unsigned decimal number in `s` to a bignum
* @param size bignum size (bytes)
*/
export declare function decimalToBinary(size: number, s: string): Uint8Array;
/**
* Convert a signed decimal number in `s` to a bignum
* @param size bignum size (bytes)
*/
export declare function signedDecimalToBinary(size: number, s: string): Uint8Array;
/**
* Convert `bignum` to an unsigned decimal number
* @param minDigits 0-pad result to this many digits
*/
export declare function binaryToDecimal(bignum: Uint8Array, minDigits?: number): string;
/**
* Convert `bignum` to a signed decimal number
* @param minDigits 0-pad result to this many digits
*/
export declare function signedBinaryToDecimal(bignum: Uint8Array, minDigits?: number): string;
/**
* Convert an unsigned base-58 number in `s` to a bignum
* @param size bignum size (bytes)
*/
export declare function base58ToBinary(size: number, s: string): Uint8Array;
/**
* Convert `bignum` to a base-58 number
* @param minDigits 0-pad result to this many digits
*/
export declare function binaryToBase58(bignum: Uint8Array, minDigits?: number): string;
/** Convert an unsigned base-64 number in `s` to a bignum */
export declare function base64ToBinary(s: string): Uint8Array;
/** Key types this library supports */
export declare enum KeyType {
k1 = 0,
r1 = 1
}
/** Public key data size, excluding type field */
export declare const publicKeyDataSize = 33;
/** Private key data size, excluding type field */
export declare const privateKeyDataSize = 32;
/** Signature data size, excluding type field */
export declare const signatureDataSize = 65;
/** Public key, private key, or signature in binary form */
export interface Key {
type: KeyType;
data: Uint8Array;
}
/** Convert key in `s` to binary form */
export declare function stringToPublicKey(s: string): Key;
/** Convert `key` to string (base-58) form */
export declare function publicKeyToString(key: Key): string;
/** If a key is in the legacy format (`EOS` prefix), then convert it to the new format (`PUB_K1_`).
* Leaves other formats untouched
*/
export declare function convertLegacyPublicKey(s: string): string;
/** If a key is in the legacy format (`EOS` prefix), then convert it to the new format (`PUB_K1_`).
* Leaves other formats untouched
*/
export declare function convertLegacyPublicKeys(keys: string[]): string[];
/** Convert key in `s` to binary form */
export declare function stringToPrivateKey(s: string): Key;
/** Convert `key` to string (base-58) form */
export declare function privateKeyToString(key: Key): string;
/** Convert key in `s` to binary form */
export declare function stringToSignature(s: string): Key;
/** Convert `signature` to string (base-58) form */
export declare function signatureToString(signature: Key): string;
-468
View File
@@ -1,468 +0,0 @@
"use strict";
/**
* @module Numeric
*/
// copyright defined in eosjs/LICENSE.txt
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
} catch (error) {
e = {error: error};
} finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
} finally {
if (e) throw e.error;
}
}
return ar;
};
var __spread = (this && this.__spread) || function () {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
return ar;
};
var __values = (this && this.__values) || function (o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return {value: o && o[i++], done: !o};
}
};
};
Object.defineProperty(exports, "__esModule", {value: true});
// const ripemd160 = require('./ripemd').RIPEMD160.hash as (a: Uint8Array) => ArrayBuffer;
var crypto = require('crypto');
function ripemd160(data) {
var hash = crypto.createHash('ripemd160');
hash.update(data);
return hash.digest('hex');
}
var base58Chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
var base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var bs58 = require('base-x')(base58Chars);
function create_base58_map() {
var base58M = Array(256).fill(-1);
for (var i = 0; i < base58Chars.length; ++i) {
base58M[base58Chars.charCodeAt(i)] = i;
}
return base58M;
}
var base58Map = create_base58_map();
function create_base64_map() {
var base64M = Array(256).fill(-1);
for (var i = 0; i < base64Chars.length; ++i) {
base64M[base64Chars.charCodeAt(i)] = i;
}
base64M['='.charCodeAt(0)] = 0;
return base64M;
}
var base64Map = create_base64_map();
/** Is `bignum` a negative number? */
function isNegative(bignum) {
return (bignum[bignum.length - 1] & 0x80) !== 0;
}
exports.isNegative = isNegative;
/** Negate `bignum` */
function negate(bignum) {
var carry = 1;
for (var i = 0; i < bignum.length; ++i) {
var x = (~bignum[i] & 0xff) + carry;
bignum[i] = x;
carry = x >> 8;
}
}
exports.negate = negate;
/**
* Convert an unsigned decimal number in `s` to a bignum
* @param size bignum size (bytes)
*/
function decimalToBinary(size, s) {
var result = new Uint8Array(size);
for (var i = 0; i < s.length; ++i) {
var srcDigit = s.charCodeAt(i);
if (srcDigit < '0'.charCodeAt(0) || srcDigit > '9'.charCodeAt(0)) {
throw new Error('invalid number');
}
var carry = srcDigit - '0'.charCodeAt(0);
for (var j = 0; j < size; ++j) {
var x = result[j] * 10 + carry;
result[j] = x;
carry = x >> 8;
}
if (carry) {
throw new Error('number is out of range');
}
}
return result;
}
exports.decimalToBinary = decimalToBinary;
/**
* Convert a signed decimal number in `s` to a bignum
* @param size bignum size (bytes)
*/
function signedDecimalToBinary(size, s) {
var negative = s[0] === '-';
if (negative) {
s = s.substr(1);
}
var result = decimalToBinary(size, s);
if (negative) {
negate(result);
if (!isNegative(result)) {
throw new Error('number is out of range');
}
} else if (isNegative(result)) {
throw new Error('number is out of range');
}
return result;
}
exports.signedDecimalToBinary = signedDecimalToBinary;
/**
* Convert `bignum` to an unsigned decimal number
* @param minDigits 0-pad result to this many digits
*/
function binaryToDecimal(bignum, minDigits) {
if (minDigits === void 0) {
minDigits = 1;
}
var result = Array(minDigits).fill('0'.charCodeAt(0));
for (var i = bignum.length - 1; i >= 0; --i) {
var carry = bignum[i];
for (var j = 0; j < result.length; ++j) {
var x = ((result[j] - '0'.charCodeAt(0)) << 8) + carry;
result[j] = '0'.charCodeAt(0) + x % 10;
carry = (x / 10) | 0;
}
while (carry) {
result.push('0'.charCodeAt(0) + carry % 10);
carry = (carry / 10) | 0;
}
}
result.reverse();
return String.fromCharCode.apply(String, __spread(result));
}
exports.binaryToDecimal = binaryToDecimal;
/**
* Convert `bignum` to a signed decimal number
* @param minDigits 0-pad result to this many digits
*/
function signedBinaryToDecimal(bignum, minDigits) {
if (minDigits === void 0) {
minDigits = 1;
}
if (isNegative(bignum)) {
var x = bignum.slice();
negate(x);
return '-' + binaryToDecimal(x, minDigits);
}
return binaryToDecimal(bignum, minDigits);
}
exports.signedBinaryToDecimal = signedBinaryToDecimal;
/**
* Convert an unsigned base-58 number in `s` to a bignum
* @param size bignum size (bytes)
*/
function base58ToBinary(size, s) {
var result = new Uint8Array(size);
for (var i = 0; i < s.length; ++i) {
var carry = base58Map[s.charCodeAt(i)];
if (carry < 0) {
throw new Error('invalid base-58 value');
}
for (var j = 0; j < size; ++j) {
var x = result[j] * 58 + carry;
result[j] = x;
carry = x >> 8;
}
if (carry) {
throw new Error('base-58 value is out of range');
}
}
result.reverse();
return result;
}
exports.base58ToBinary = base58ToBinary;
/**
* Convert `bignum` to a base-58 number
* @param minDigits 0-pad result to this many digits
*/
function binaryToBase58(bignum, minDigits) {
return bs58.encode(Buffer.from(bignum));
// if (minDigits === void 0) {
// minDigits = 1;
// }
// var e_1, _a, e_2, _b;
// var result = [];
// try {
// for (var bignum_1 = __values(bignum), bignum_1_1 = bignum_1.next(); !bignum_1_1.done; bignum_1_1 = bignum_1.next()) {
// var byte = bignum_1_1.value;
// var carry = byte;
// for (var j = 0; j < result.length; ++j) {
// var x = (base58Map[result[j]] << 8) + carry;
// result[j] = base58Chars.charCodeAt(x % 58);
// carry = (x / 58) | 0;
// }
// while (carry) {
// result.push(base58Chars.charCodeAt(carry % 58));
// carry = (carry / 58) | 0;
// }
// }
// } catch (e_1_1) {
// e_1 = {error: e_1_1};
// } finally {
// try {
// if (bignum_1_1 && !bignum_1_1.done && (_a = bignum_1.return)) _a.call(bignum_1);
// } finally {
// if (e_1) throw e_1.error;
// }
// }
// try {
// for (var bignum_2 = __values(bignum), bignum_2_1 = bignum_2.next(); !bignum_2_1.done; bignum_2_1 = bignum_2.next()) {
// var byte = bignum_2_1.value;
// if (byte) {
// break;
// } else {
// result.push('1'.charCodeAt(0));
// }
// }
// } catch (e_2_1) {
// e_2 = {error: e_2_1};
// } finally {
// try {
// if (bignum_2_1 && !bignum_2_1.done && (_b = bignum_2.return)) _b.call(bignum_2);
// } finally {
// if (e_2) throw e_2.error;
// }
// }
// result.reverse();
// return String.fromCharCode.apply(String, __spread(result));
}
exports.binaryToBase58 = binaryToBase58;
/** Convert an unsigned base-64 number in `s` to a bignum */
function base64ToBinary(s) {
var len = s.length;
if ((len & 3) === 1 && s[len - 1] === '=') {
len -= 1;
} // fc appends an extra '='
if ((len & 3) !== 0) {
throw new Error('base-64 value is not padded correctly');
}
var groups = len >> 2;
var bytes = groups * 3;
if (len > 0 && s[len - 1] === '=') {
if (s[len - 2] === '=') {
bytes -= 2;
} else {
bytes -= 1;
}
}
var result = new Uint8Array(bytes);
for (var group = 0; group < groups; ++group) {
var digit0 = base64Map[s.charCodeAt(group * 4 + 0)];
var digit1 = base64Map[s.charCodeAt(group * 4 + 1)];
var digit2 = base64Map[s.charCodeAt(group * 4 + 2)];
var digit3 = base64Map[s.charCodeAt(group * 4 + 3)];
result[group * 3 + 0] = (digit0 << 2) | (digit1 >> 4);
if (group * 3 + 1 < bytes) {
result[group * 3 + 1] = ((digit1 & 15) << 4) | (digit2 >> 2);
}
if (group * 3 + 2 < bytes) {
result[group * 3 + 2] = ((digit2 & 3) << 6) | digit3;
}
}
return result;
}
exports.base64ToBinary = base64ToBinary;
/** Key types this library supports */
var KeyType;
(function (KeyType) {
KeyType[KeyType["k1"] = 0] = "k1";
KeyType[KeyType["r1"] = 1] = "r1";
})(KeyType = exports.KeyType || (exports.KeyType = {}));
/** Public key data size, excluding type field */
exports.publicKeyDataSize = 33;
/** Private key data size, excluding type field */
exports.privateKeyDataSize = 32;
/** Signature data size, excluding type field */
exports.signatureDataSize = 65;
function digestSuffixRipemd160(data, suffix) {
var d = new Uint8Array(data.length + suffix.length);
for (var i = 0; i < data.length; ++i) {
d[i] = data[i];
}
for (var i = 0; i < suffix.length; ++i) {
d[data.length + i] = suffix.charCodeAt(i);
}
return ripemd160(d);
}
function stringToKey(s, type, size, suffix) {
var whole = base58ToBinary(size + 4, s);
var result = {type: type, data: new Uint8Array(whole.buffer, 0, size)};
var digest = new Uint8Array(digestSuffixRipemd160(result.data, suffix));
if (digest[0] !== whole[size + 0] || digest[1] !== whole[size + 1]
|| digest[2] !== whole[size + 2] || digest[3] !== whole[size + 3]) {
throw new Error('checksum doesn\'t match');
}
return result;
}
function keyToString(key, suffix, prefix) {
var digest = new Uint8Array(digestSuffixRipemd160(key.data, suffix));
var whole = new Uint8Array(key.data.length + 4);
for (var i = 0; i < key.data.length; ++i) {
whole[i] = key.data[i];
}
for (var i = 0; i < 4; ++i) {
whole[i + key.data.length] = digest[i];
}
return prefix + binaryToBase58(whole);
}
/** Convert key in `s` to binary form */
function stringToPublicKey(s) {
if (typeof s !== 'string') {
throw new Error('expected string containing public key');
}
if (s.substr(0, 3) === 'EOS') {
var whole = base58ToBinary(exports.publicKeyDataSize + 4, s.substr(3));
var key = {type: KeyType.k1, data: new Uint8Array(exports.publicKeyDataSize)};
for (var i = 0; i < exports.publicKeyDataSize; ++i) {
key.data[i] = whole[i];
}
var digest = new Uint8Array(ripemd160(key.data));
if (digest[0] !== whole[exports.publicKeyDataSize] || digest[1] !== whole[34]
|| digest[2] !== whole[35] || digest[3] !== whole[36]) {
throw new Error('checksum doesn\'t match');
}
return key;
} else if (s.substr(0, 7) === 'PUB_K1_') {
return stringToKey(s.substr(7), KeyType.k1, exports.publicKeyDataSize, 'K1');
} else if (s.substr(0, 7) === 'PUB_R1_') {
return stringToKey(s.substr(7), KeyType.r1, exports.publicKeyDataSize, 'R1');
} else {
throw new Error('unrecognized public key format');
}
}
exports.stringToPublicKey = stringToPublicKey;
/** Convert `key` to string (base-58) form */
function publicKeyToString(key) {
if (key.type === KeyType.k1 && key.data.length === exports.publicKeyDataSize) {
return keyToString(key, 'K1', 'PUB_K1_');
} else if (key.type === KeyType.r1 && key.data.length === exports.publicKeyDataSize) {
return keyToString(key, 'R1', 'PUB_R1_');
} else {
throw new Error('unrecognized public key format');
}
}
exports.publicKeyToString = publicKeyToString;
/** If a key is in the legacy format (`EOS` prefix), then convert it to the new format (`PUB_K1_`).
* Leaves other formats untouched
*/
function convertLegacyPublicKey(s) {
if (s.substr(0, 3) === 'EOS') {
return publicKeyToString(stringToPublicKey(s));
}
return s;
}
exports.convertLegacyPublicKey = convertLegacyPublicKey;
/** If a key is in the legacy format (`EOS` prefix), then convert it to the new format (`PUB_K1_`).
* Leaves other formats untouched
*/
function convertLegacyPublicKeys(keys) {
return keys.map(convertLegacyPublicKey);
}
exports.convertLegacyPublicKeys = convertLegacyPublicKeys;
/** Convert key in `s` to binary form */
function stringToPrivateKey(s) {
if (typeof s !== 'string') {
throw new Error('expected string containing private key');
}
if (s.substr(0, 7) === 'PVT_R1_') {
return stringToKey(s.substr(7), KeyType.r1, exports.privateKeyDataSize, 'R1');
} else {
throw new Error('unrecognized private key format');
}
}
exports.stringToPrivateKey = stringToPrivateKey;
/** Convert `key` to string (base-58) form */
function privateKeyToString(key) {
if (key.type === KeyType.r1) {
return keyToString(key, 'R1', 'PVT_R1_');
} else {
throw new Error('unrecognized private key format');
}
}
exports.privateKeyToString = privateKeyToString;
/** Convert key in `s` to binary form */
function stringToSignature(s) {
if (typeof s !== 'string') {
throw new Error('expected string containing signature');
}
if (s.substr(0, 7) === 'SIG_K1_') {
return stringToKey(s.substr(7), KeyType.k1, exports.signatureDataSize, 'K1');
} else if (s.substr(0, 7) === 'SIG_R1_') {
return stringToKey(s.substr(7), KeyType.r1, exports.signatureDataSize, 'R1');
} else {
throw new Error('unrecognized signature format');
}
}
exports.stringToSignature = stringToSignature;
/** Convert `signature` to string (base-58) form */
function signatureToString(signature) {
if (signature.type === KeyType.k1) {
return keyToString(signature, 'K1', 'SIG_K1_');
} else if (signature.type === KeyType.r1) {
return keyToString(signature, 'R1', 'SIG_R1_');
} else {
throw new Error('unrecognized signature format');
}
}
exports.signatureToString = signatureToString;
//# sourceMappingURL=eosjs-numeric.js.map
File diff suppressed because one or more lines are too long
-103
View File
@@ -1,103 +0,0 @@
/** Structured format for abis */
export interface Abi {
version: string;
types: Array<{
new_type_name: string;
type: string;
}>;
structs: Array<{
name: string;
base: string;
fields: Array<{
name: string;
type: string;
}>;
}>;
actions: Array<{
name: string;
type: string;
ricardian_contract: string;
}>;
tables: Array<{
name: string;
type: string;
index_type: string;
key_names: string[];
key_types: string[];
}>;
ricardian_clauses: Array<{
id: string;
body: string;
}>;
error_messages: Array<{
error_code: string;
error_msg: string;
}>;
abi_extensions: Array<{
tag: number;
value: string;
}>;
variants?: Array<{
name: string;
types: string[];
}>;
}
/** Return value of `/v1/chain/get_abi` */
export interface GetAbiResult {
account_name: string;
abi: Abi;
}
/** Subset of `GetBlockResult` needed to calculate TAPoS fields in transactions */
export interface BlockTaposInfo {
timestamp: string;
block_num: number;
ref_block_prefix: number;
}
/** Return value of `/v1/chain/get_block` */
export interface GetBlockResult {
timestamp: string;
producer: string;
confirmed: number;
previous: string;
transaction_mroot: string;
action_mroot: string;
schedule_version: number;
producer_signature: string;
id: string;
block_num: number;
ref_block_prefix: number;
}
/** Return value of `/v1/chain/get_code` */
export interface GetCodeResult {
account_name: string;
code_hash: string;
wast: string;
wasm: string;
abi: Abi;
}
/** Return value of `/v1/chain/get_info` */
export interface GetInfoResult {
server_version: string;
chain_id: string;
head_block_num: number;
last_irreversible_block_num: number;
last_irreversible_block_id: string;
head_block_id: string;
head_block_time: string;
head_block_producer: string;
virtual_block_cpu_limit: number;
virtual_block_net_limit: number;
block_cpu_limit: number;
block_net_limit: number;
}
/** Return value of `/v1/chain/get_raw_code_and_abi` */
export interface GetRawCodeAndAbiResult {
account_name: string;
wasm: string;
abi: string;
}
/** Arguments for `push_transaction` */
export interface PushTransactionArgs {
signatures: string[];
serializedTransaction: Uint8Array;
}
@@ -1,4 +0,0 @@
"use strict";
// copyright defined in eosjs/LICENSE.txt
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=eosjs-rpc-interfaces.js.map
@@ -1 +0,0 @@
{"version":3,"file":"eosjs-rpc-interfaces.js","sourceRoot":"","sources":["../src/eosjs-rpc-interfaces.ts"],"names":[],"mappings":";AAAA,yCAAyC"}
-9
View File
@@ -1,9 +0,0 @@
/**
* @module RPC-Error
*/
/** Holds detailed error information */
export declare class RpcError extends Error {
/** Detailed error information */
json: any;
constructor(json: any);
}
-41
View File
@@ -1,41 +0,0 @@
"use strict";
/**
* @module RPC-Error
*/
// copyright defined in eosjs/LICENSE.txt
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
/** Holds detailed error information */
var RpcError = /** @class */ (function (_super) {
__extends(RpcError, _super);
function RpcError(json) {
var _this = this;
if (json.error && json.error.details && json.error.details.length && json.error.details[0].message) {
_this = _super.call(this, json.error.details[0].message) || this;
}
else if (json.processed && json.processed.except && json.processed.except.message) {
_this = _super.call(this, json.processed.except.message) || this;
}
else {
_this = _super.call(this, json.message) || this;
}
Object.setPrototypeOf(_this, RpcError.prototype);
_this.json = json;
return _this;
}
return RpcError;
}(Error));
exports.RpcError = RpcError;
//# sourceMappingURL=eosjs-rpcerror.js.map
@@ -1 +0,0 @@
{"version":3,"file":"eosjs-rpcerror.js","sourceRoot":"","sources":["../src/eosjs-rpcerror.ts"],"names":[],"mappings":";AAAA;;GAEG;AACH,yCAAyC;;;;;;;;;;;;;;;AAEzC,uCAAuC;AACvC;IAA8B,4BAAK;IAI/B,kBAAY,IAAS;QAArB,iBAUC;QATG,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE;YAChG,QAAA,kBAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,SAAC;SACxC;aAAM,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,SAAS,CAAC,MAAM,IAAI,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,OAAO,EAAE;YACjF,QAAA,kBAAM,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,OAAO,CAAC,SAAC;SACxC;aAAM;YACH,QAAA,kBAAM,IAAI,CAAC,OAAO,CAAC,SAAC;SACvB;QACD,MAAM,CAAC,cAAc,CAAC,KAAI,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC;QAChD,KAAI,CAAC,IAAI,GAAG,IAAI,CAAC;;IACrB,CAAC;IACL,eAAC;AAAD,CAAC,AAfD,CAA8B,KAAK,GAelC;AAfY,4BAAQ"}
-241
View File
@@ -1,241 +0,0 @@
/**
* @module Serialize
*/
import { Abi, BlockTaposInfo } from './eosjs-rpc-interfaces';
/** A field in an abi */
export interface Field {
/** Field name */
name: string;
/** Type name in string form */
typeName: string;
/** Type of the field */
type: Type;
}
/** Options for serialize() and deserialize() */
export interface SerializerOptions {
bytesAsUint8Array?: boolean;
}
/** State for serialize() and deserialize() */
export declare class SerializerState {
options: SerializerOptions;
/** Have any binary extensions been skipped? */
skippedBinaryExtension: boolean;
constructor(options?: SerializerOptions);
}
/** A type in an abi */
export interface Type {
/** Type name */
name: string;
/** Type name this is an alias of, if any */
aliasOfName: string;
/** Type this is an array of, if any */
arrayOf: Type;
/** Type this is an optional of, if any */
optionalOf: Type;
/** Marks binary extension fields */
extensionOf?: Type;
/** Base name of this type, if this is a struct */
baseName: string;
/** Base of this type, if this is a struct */
base: Type;
/** Contained fields, if this is a struct */
fields: Field[];
/** Convert `data` to binary form and store in `buffer` */
serialize: (buffer: SerialBuffer, data: any, state?: SerializerState, allowExtensions?: boolean) => void;
/** Convert data in `buffer` from binary form */
deserialize: (buffer: SerialBuffer, state?: SerializerState, allowExtensions?: boolean) => any;
}
/** Structural representation of a symbol */
export interface Symbol {
/** Name of the symbol, not including precision */
name: string;
/** Number of digits after the decimal point */
precision: number;
}
export interface Contract {
actions: Map<string, Type>;
types: Map<string, Type>;
}
export interface Authorization {
actor: string;
permission: string;
}
/** Action with data in structured form */
export interface Action {
account: string;
name: string;
authorization: Authorization[];
data: any;
}
/** Action with data in serialized hex form */
export interface SerializedAction {
account: string;
name: string;
authorization: Authorization[];
data: string;
}
/** Serialize and deserialize data */
export declare class SerialBuffer {
/** Amount of valid data in `array` */
length: number;
/** Data in serialized (binary) form */
array: Uint8Array;
/** Current position while reading (deserializing) */
readPos: number;
textEncoder: TextEncoder;
textDecoder: TextDecoder;
/**
* @param __namedParameters
* * `array`: `null` if serializing, or binary data to deserialize
* * `textEncoder`: `TextEncoder` instance to use. Pass in `null` if running in a browser
* * `textDecoder`: `TextDecider` instance to use. Pass in `null` if running in a browser
*/
constructor({ textEncoder, textDecoder, array }?: {
textEncoder?: TextEncoder;
textDecoder?: TextDecoder;
array?: Uint8Array;
});
/** Resize `array` if needed to have at least `size` bytes free */
reserve(size: number): void;
/** Is there data available to read? */
haveReadData(): boolean;
/** Restart reading from the beginning */
restartRead(): void;
/** Return data with excess storage trimmed away */
asUint8Array(): Uint8Array;
/** Append bytes */
pushArray(v: number[] | Uint8Array): void;
/** Append bytes */
push(...v: number[]): void;
/** Get a single byte */
get(): number;
/** Append bytes in `v`. Throws if `len` doesn't match `v.length` */
pushUint8ArrayChecked(v: Uint8Array, len: number): void;
/** Get `len` bytes */
getUint8Array(len: number): Uint8Array;
/** Append a `uint16` */
pushUint16(v: number): void;
/** Get a `uint16` */
getUint16(): number;
/** Append a `uint32` */
pushUint32(v: number): void;
/** Get a `uint32` */
getUint32(): number;
/** Append a `uint64`. *Caution*: `number` only has 53 bits of precision */
pushNumberAsUint64(v: number): void;
/**
* Get a `uint64` as a `number`. *Caution*: `number` only has 53 bits of precision; some values will change.
* `numeric.binaryToDecimal(serialBuffer.getUint8Array(8))` recommended instead
*/
getUint64AsNumber(): number;
/** Append a `varuint32` */
pushVaruint32(v: number): void;
/** Get a `varuint32` */
getVaruint32(): number;
/** Append a `varint32` */
pushVarint32(v: number): void;
/** Get a `varint32` */
getVarint32(): number;
/** Append a `float32` */
pushFloat32(v: number): void;
/** Get a `float32` */
getFloat32(): number;
/** Append a `float64` */
pushFloat64(v: number): void;
/** Get a `float64` */
getFloat64(): number;
/** Append a `name` */
pushName(s: string): void;
/** Get a `name` */
getName(): string;
/** Append length-prefixed binary data */
pushBytes(v: number[] | Uint8Array): void;
/** Get length-prefixed binary data */
getBytes(): Uint8Array;
/** Append a string */
pushString(v: string): void;
/** Get a string */
getString(): string;
/** Append a `symbol_code`. Unlike `symbol`, `symbol_code` doesn't include a precision. */
pushSymbolCode(name: string): void;
/** Get a `symbol_code`. Unlike `symbol`, `symbol_code` doesn't include a precision. */
getSymbolCode(): string;
/** Append a `symbol` */
pushSymbol({ name, precision }: {
name: string;
precision: number;
}): void;
/** Get a `symbol` */
getSymbol(): {
name: string;
precision: number;
};
/** Append an asset */
pushAsset(s: string): void;
/** Get an asset */
getAsset(): string;
/** Append a public key */
pushPublicKey(s: string): void;
/** Get a public key */
getPublicKey(): string;
/** Append a private key */
pushPrivateKey(s: string): void;
/** Get a private key */
getPrivateKey(): string;
/** Append a signature */
pushSignature(s: string): void;
/** Get a signature */
getSignature(): string;
}
/** Is this a supported ABI version? */
export declare function supportedAbiVersion(version: string): boolean;
/** Convert date in ISO format to `time_point` (miliseconds since epoch) */
export declare function dateToTimePoint(date: string): number;
/** Convert `time_point` (miliseconds since epoch) to date in ISO format */
export declare function timePointToDate(us: number): string;
/** Convert date in ISO format to `time_point_sec` (seconds since epoch) */
export declare function dateToTimePointSec(date: string): number;
/** Convert `time_point_sec` (seconds since epoch) to to date in ISO format */
export declare function timePointSecToDate(sec: number): string;
/** Convert date in ISO format to `block_timestamp_type` (half-seconds since a different epoch) */
export declare function dateToBlockTimestamp(date: string): number;
/** Convert `block_timestamp_type` (half-seconds since a different epoch) to to date in ISO format */
export declare function blockTimestampToDate(slot: number): string;
/** Convert `string` to `Symbol`. format: `precision,NAME`. */
export declare function stringToSymbol(s: string): {
name: string;
precision: number;
};
/** Convert `Symbol` to `string`. format: `precision,NAME`. */
export declare function symbolToString({ name, precision }: {
name: string;
precision: number;
}): string;
/** Convert binary data to hex */
export declare function arrayToHex(data: Uint8Array): string;
/** Convert hex to binary data */
export declare function hexToUint8Array(hex: string): Uint8Array;
/** Create the set of types built-in to the abi format */
export declare function createInitialTypes(): Map<string, Type>;
/** Get type from `types` */
export declare function getType(types: Map<string, Type>, name: string): Type;
/**
* Get types from abi
* @param initialTypes Set of types to build on.
* In most cases, it's best to fill this from a fresh call to `getTypesFromAbi()`.
*/
export declare function getTypesFromAbi(initialTypes: Map<string, Type>, abi: Abi): Map<string, Type>;
/** TAPoS: Return transaction fields which reference `refBlock` and expire `expireSeconds` after `refBlock.timestamp` */
export declare function transactionHeader(refBlock: BlockTaposInfo, expireSeconds: number): {
expiration: string;
ref_block_num: number;
ref_block_prefix: number;
};
/** Convert action data to serialized form (hex) */
export declare function serializeActionData(contract: Contract, account: string, name: string, data: any, textEncoder: TextEncoder, textDecoder: TextDecoder): string;
/** Return action in serialized form */
export declare function serializeAction(contract: Contract, account: string, name: string, authorization: Authorization[], data: any, textEncoder: TextEncoder, textDecoder: TextDecoder): SerializedAction;
/** Deserialize action data. If `data` is a `string`, then it's assumed to be in hex. */
export declare function deserializeActionData(contract: Contract, account: string, name: string, data: string | Uint8Array | number[], textEncoder: TextEncoder, textDecoder: TextDecoder): any;
/** Deserialize action. If `data` is a `string`, then it's assumed to be in hex. */
export declare function deserializeAction(contract: Contract, account: string, name: string, authorization: Authorization[], data: string | Uint8Array | number[], textEncoder: TextEncoder, textDecoder: TextDecoder): Action;
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
-8
View File
@@ -1,8 +0,0 @@
import { Api } from './eosjs-api';
import * as ApiInterfaces from './eosjs-api-interfaces';
import { JsonRpc } from './eosjs-jsonrpc';
import * as Numeric from './eosjs-numeric';
import * as RpcInterfaces from './eosjs-rpc-interfaces';
import { RpcError } from './eosjs-rpcerror';
import * as Serialize from './eosjs-serialize';
export { Api, ApiInterfaces, JsonRpc, Numeric, RpcInterfaces, RpcError, Serialize };
-17
View File
@@ -1,17 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var eosjs_api_1 = require("./eosjs-api");
exports.Api = eosjs_api_1.Api;
var ApiInterfaces = require("./eosjs-api-interfaces");
exports.ApiInterfaces = ApiInterfaces;
var eosjs_jsonrpc_1 = require("./eosjs-jsonrpc");
exports.JsonRpc = eosjs_jsonrpc_1.JsonRpc;
var Numeric = require("./eosjs-numeric");
exports.Numeric = Numeric;
var RpcInterfaces = require("./eosjs-rpc-interfaces");
exports.RpcInterfaces = RpcInterfaces;
var eosjs_rpcerror_1 = require("./eosjs-rpcerror");
exports.RpcError = eosjs_rpcerror_1.RpcError;
var Serialize = require("./eosjs-serialize");
exports.Serialize = Serialize;
//# sourceMappingURL=index.js.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;AAAA,yCAAkC;AAQzB,cARA,eAAG,CAQA;AAPZ,sDAAwD;AAO1C,sCAAa;AAN3B,iDAA0C;AAMb,kBANpB,uBAAO,CAMoB;AALpC,yCAA2C;AAKL,0BAAO;AAJ7C,sDAAwD;AAIT,sCAAa;AAH5D,mDAA4C;AAGkB,mBAHrD,yBAAQ,CAGqD;AAFtE,6CAA+C;AAEyB,8BAAS"}
-401
View File
@@ -1,401 +0,0 @@
// https://gist.githubusercontent.com/wlzla000/bac83df6d3c51916c4dd0bc947e46947/raw/7ee3462b095ab22580ddaf191f44a590da6fe33b/RIPEMD-160.js
/*
RIPEMD-160.js
developed
by K. (https://github.com/wlzla000)
on December 27-29, 2017,
licensed under
the MIT license
Copyright (c) 2017 K.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
"use strict";
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var RIPEMD160 = function () {
function RIPEMD160() {
// https://webcache.googleusercontent.com/search?q=cache:CnLOgolTHYEJ:https://www.cosic.esat.kuleuven.be/publications/article-317.pdf
// http://shodhganga.inflibnet.ac.in/bitstream/10603/22978/13/13_appendix.pdf
_classCallCheck(this, RIPEMD160);
}
_createClass(RIPEMD160, null, [{
key: "get_n_pad_bytes",
value: function get_n_pad_bytes(message_size /* in bytes, 1 byte is 8 bits. */) {
// Obtain the number of bytes needed to pad the message.
// It does not contain the size of the message size information.
/*
https://webcache.googleusercontent.com/search?q=cache:CnLOgolTHYEJ:https://www.cosic.esat.kuleuven.be/publications/article-317.pdf
The Cryptographic Hash Function RIPEMD-160
written by
Bart Preneel,
Hans Dobbertin,
Antoon Bosselaers
in
1997.
--------------------------------------------------
§5 Description of RIPEMD-160
......
In order to guarantee that the total input size is a
multiple of 512 bits, the input is padded in the same
way as for all the members of the MD4-family: one
appends a single 1 followed by a string of 0s (the
number of 0s lies between 0 and 511); the last 64 bits
of the extended input contain the binary representation
of the input size in bits, least significant byte first.
*/
/*
https://tools.ietf.org/rfc/rfc1186.txt
RFC 1186: MD4 Message Digest Algorithm.
written by
Ronald Linn Rivest
in
October 1990.
--------------------------------------------------
§3 MD4 Algorithm Description
......
Step 1. Append padding bits
The message is "padded" (extended) so that its length
(in bits) is congruent to 448, modulo 512. That is, the
message is extended so that it is just 64 bits shy of
being a multiple of 512 bits long. Padding is always
performed, even if the length of the message is already
congruent to 448, modulo 512 (in which case 512 bits of
padding are added).
Padding is performed as follows: a single "1" bit is
appended to the message, and then enough zero bits are
appended so that the length in bits of the padded
message becomes congruent to 448, modulo 512.
Step 2. Append length
A 64-bit representation of b (the length of the message
before the padding bits were added) is appended to the
result of the previous step. In the unlikely event that
b is greater than 2^64, then only the low-order 64 bits
of b are used. (These bits are appended as two 32-bit
words and appended low-order word first in accordance
with the previous conventions.)
At this point the resulting message (after padding with
bits and with b) has a length that is an exact multiple
of 512 bits. Equivalently, this message has a length
that is an exact multiple of 16 (32-bit) words. Let
M[0 ... N-1] denote the words of the resulting message,
where N is a multiple of 16.
*/
// https://crypto.stackexchange.com/a/32407/54568
/*
Example case # 1
[0 bit: message.]
[1 bit: 1.]
[447 bits: 0.]
[64 bits: message size information.]
Example case # 2
[512-bits: message]
[1 bit: 1.]
[447 bits: 0.]
[64 bits: message size information.]
Example case # 3
[(512 - 64 = 448) bits: message.]
[1 bit: 1.]
[511 bits: 0.]
[64 bits: message size information.]
Example case # 4
[(512 - 65 = 447) bits: message.]
[1 bit: 1.]
[0 bit: 0.]
[64 bits: message size information.]
*/
// The number of padding zero bits:
// 511 - [{(message size in bits) + 64} (mod 512)]
return 64 - (message_size + 8 & 63 /* 63 */);
}
}, {
key: "pad",
value: function pad(message /* An ArrayBuffer. */) {
var message_size = message.byteLength;
var n_pad = RIPEMD160.get_n_pad_bytes(message_size);
// `Number.MAX_SAFE_INTEGER` is ((2 ** 53) - 1) and
// bitwise operation in Javascript is done on 32-bits operands.
var divmod = function divmod(dividend, divisor) {
return [Math.floor(dividend / divisor), dividend % divisor];
};
/*
To shift
00000000 000????? ???????? ???????? ???????? ???????? ???????? ????????
t o
00000000 ???????? ???????? ???????? ???????? ???????? ???????? ?????000
--------------------------------------------------------------------------------
Method #1
00000000 000????? ???????? ???????? ???????? ???????? ???????? ????????
[00000000 000AAAAA AAAAAAAA AAAAAAAA] (<A> captured)
[00000000 AAAAAAAA AAAAAAAA AAAAA000] (<A> shifted)
(<B> captured) [BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB]
(<B> shifted) [BBB][BBBBBBBB BBBBBBBB BBBBBBBB BBBBB000]
[00000000 AAAAAAAA AAAAAAAA AAAAABBB] (<A> & <B_2> merged)
[00000000 AAAAAAAA AAAAAAAA AAAAABBB][BBBBBBBB BBBBBBBB BBBBBBBB BBBBB000]
00000000 ???????? ???????? ???????? ???????? ???????? ???????? ?????000
const uint32_max_plus_1 = 0x100000000; // (2 ** 32)
const [
msg_byte_size_most, // Value range [0, (2 ** 21) - 1].
msg_byte_size_least // Value range [0, (2 ** 32) - 1].
] = divmod(message_size, uint32_max_plus_1);
const [
carry, // Value range [0, 7].
msg_bit_size_least // Value range [0, (2 ** 32) - 8].
] = divmod(message_byte_size_least * 8, uint32_max_plus_1);
const message_bit_size_most = message_byte_size_most * 8
+ carry; // Value range [0, (2 ** 24) - 1].
--------------------------------------------------------------------------------
Method #2
00000000 000????? ???????? ???????? ???????? ???????? ???????? ????????
[00000 000AAAAA AAAAAAAA AAAAAAAA AAA] (<A> captured)
(<B> captured) [000BBBBB BBBBBBBB BBBBBBBB BBBBBBBB]
(<B> shifted) [BBBBBBBB BBBBBBBB BBBBBBBB BBBBB000]
[00000000 AAAAAAAA AAAAAAAA AAAAAAAA][BBBBBBBB BBBBBBBB BBBBBBBB BBBBB000]
00000000 ???????? ???????? ???????? ???????? ???????? ???????? ?????000
*/
var _divmod$map = divmod(message_size, 536870912 /* (2 ** 29) */).map(function (x, index) {
return index ? x * 8 : x;
}),
_divmod$map2 = _slicedToArray(_divmod$map, 2),
msg_bit_size_most = _divmod$map2[0],
msg_bit_size_least = _divmod$map2[1];
// `ArrayBuffer.transfer()` is not supported.
var padded = new Uint8Array(message_size + n_pad + 8);
padded.set(new Uint8Array(message), 0);
var data_view = new DataView(padded.buffer);
data_view.setUint8(message_size, 128);
data_view.setUint32(message_size + n_pad, msg_bit_size_least, true // Little-endian
);
data_view.setUint32(message_size + n_pad + 4, msg_bit_size_most, true // Little-endian
);
return padded.buffer;
}
}, {
key: "f",
value: function f(j, x, y, z) {
if (0 <= j && j <= 15) {
// Exclusive-OR
return x ^ y ^ z;
}
if (16 <= j && j <= 31) {
// Multiplexing (muxing)
return x & y | ~x & z;
}
if (32 <= j && j <= 47) {
return (x | ~y) ^ z;
}
if (48 <= j && j <= 63) {
// Multiplexing (muxing)
return x & z | y & ~z;
}
if (64 <= j && j <= 79) {
return x ^ (y | ~z);
}
}
}, {
key: "K",
value: function K(j) {
if (0 <= j && j <= 15) {
return 0x00000000;
}
if (16 <= j && j <= 31) {
// Math.floor((2 ** 30) * Math.SQRT2)
return 0x5A827999;
}
if (32 <= j && j <= 47) {
// Math.floor((2 ** 30) * Math.sqrt(3))
return 0x6ED9EBA1;
}
if (48 <= j && j <= 63) {
// Math.floor((2 ** 30) * Math.sqrt(5))
return 0x8F1BBCDC;
}
if (64 <= j && j <= 79) {
// Math.floor((2 ** 30) * Math.sqrt(7))
return 0xA953FD4E;
}
}
}, {
key: "KP",
value: function KP(j) // K'
{
if (0 <= j && j <= 15) {
// Math.floor((2 ** 30) * Math.cbrt(2))
return 0x50A28BE6;
}
if (16 <= j && j <= 31) {
// Math.floor((2 ** 30) * Math.cbrt(3))
return 0x5C4DD124;
}
if (32 <= j && j <= 47) {
// Math.floor((2 ** 30) * Math.cbrt(5))
return 0x6D703EF3;
}
if (48 <= j && j <= 63) {
// Math.floor((2 ** 30) * Math.cbrt(7))
return 0x7A6D76E9;
}
if (64 <= j && j <= 79) {
return 0x00000000;
}
}
}, {
key: "add_modulo32",
value: function add_modulo32() /* ...... */{
// 1. Modulo addition (addition modulo) is associative.
// https://proofwiki.org/wiki/Modulo_Addition_is_Associative
// 2. Bitwise operation in Javascript
// is done on 32-bits operands
// and results in a 32-bits value.
return Array.from(arguments).reduce(function (a, b) {
return a + b;
}, 0) | 0;
}
}, {
key: "rol32",
value: function rol32(value, count) {
// Cyclic left shift (rotate) on 32-bits value.
return value << count | value >>> 32 - count;
}
}, {
key: "hash",
value: function hash(message /* An ArrayBuffer. */) {
////////// Padding //////////
// The padded message.
var padded = RIPEMD160.pad(message);
////////// Compression //////////
// Message word selectors.
var r = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13];
var rP = [// r'
5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11];
// Amounts for 'rotate left' operation.
var s = [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6];
var sP = [// s'
8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11];
// The size, in bytes, of a word.
var word_size = 4;
// The size, in bytes, of a 16-words block.
var block_size = 64;
// The number of the 16-words blocks.
var t = padded.byteLength / block_size;
// The message after padding consists of t 16-word blocks that
// are denoted with X_i[j], with 0≤i≤(t 1) and 0≤j≤15.
var X = new Array(t).fill(undefined).map(function (_, i) {
return function (j) {
return new DataView(padded, i * block_size, block_size).getUint32(j * word_size, true // Little-endian
);
};
});
// The result of RIPEMD-160 is contained in five 32-bit words,
// which form the internal state of the algorithm. The final
// content of these five 32-bit words is converted to a 160-bit
// string, again using the little-endian convention.
var h = [0x67452301, // h_0
0xEFCDAB89, // h_1
0x98BADCFE, // h_2
0x10325476, // h_3
0xC3D2E1F0 // h_4
];
for (var i = 0; i < t; ++i) {
var A = h[0],
B = h[1],
C = h[2],
D = h[3],
E = h[4];
var AP = A,
BP = B,
CP = C,
DP = D,
EP = E;
for (var j = 0; j < 80; ++j) {
// Left rounds
var _T = RIPEMD160.add_modulo32(RIPEMD160.rol32(RIPEMD160.add_modulo32(A, RIPEMD160.f(j, B, C, D), X[i](r[j]), RIPEMD160.K(j)), s[j]), E);
A = E;
E = D;
D = RIPEMD160.rol32(C, 10);
C = B;
B = _T;
// Right rounds
_T = RIPEMD160.add_modulo32(RIPEMD160.rol32(RIPEMD160.add_modulo32(AP, RIPEMD160.f(79 - j, BP, CP, DP), X[i](rP[j]), RIPEMD160.KP(j)), sP[j]), EP);
AP = EP;
EP = DP;
DP = RIPEMD160.rol32(CP, 10);
CP = BP;
BP = _T;
}
var T = RIPEMD160.add_modulo32(h[1], C, DP);
h[1] = RIPEMD160.add_modulo32(h[2], D, EP);
h[2] = RIPEMD160.add_modulo32(h[3], E, AP);
h[3] = RIPEMD160.add_modulo32(h[4], A, BP);
h[4] = RIPEMD160.add_modulo32(h[0], B, CP);
h[0] = T;
}
// The final output string then consists of the concatenatation
// of h_0, h_1, h_2, h_3, and h_4 after converting each h_i to a
// 4-byte string using the little-endian convention.
var result = new ArrayBuffer(20);
var data_view = new DataView(result);
h.forEach(function (h_i, i) {
return data_view.setUint32(i * 4, h_i, true);
});
return result;
}
}]);
return RIPEMD160;
}();
module.exports = {
RIPEMD160: RIPEMD160
};
-3
View File
@@ -1,3 +0,0 @@
import { JsonRpc } from './eosjs-jsonrpc';
import { RpcError } from './eosjs-rpcerror';
export { JsonRpc, RpcError };
-7
View File
@@ -1,7 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var eosjs_jsonrpc_1 = require("./eosjs-jsonrpc");
exports.JsonRpc = eosjs_jsonrpc_1.JsonRpc;
var eosjs_rpcerror_1 = require("./eosjs-rpcerror");
exports.RpcError = eosjs_rpcerror_1.RpcError;
//# sourceMappingURL=rpc-web.js.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"rpc-web.js","sourceRoot":"","sources":["../src/rpc-web.ts"],"names":[],"mappings":";;AAAA,iDAA0C;AAGjC,kBAHA,uBAAO,CAGA;AAFhB,mDAA4C;AAE1B,mBAFT,yBAAQ,CAES"}
-193
View File
@@ -1,193 +0,0 @@
{
"version": "eosio::abi/1.1",
"structs": [
{
"name": "extensions_entry",
"base": "",
"fields": [
{
"name": "tag",
"type": "uint16"
},
{
"name": "value",
"type": "bytes"
}
]
},
{
"name": "type_def",
"base": "",
"fields": [
{
"name": "new_type_name",
"type": "string"
},
{
"name": "type",
"type": "string"
}
]
},
{
"name": "field_def",
"base": "",
"fields": [
{
"name": "name",
"type": "string"
},
{
"name": "type",
"type": "string"
}
]
},
{
"name": "struct_def",
"base": "",
"fields": [
{
"name": "name",
"type": "string"
},
{
"name": "base",
"type": "string"
},
{
"name": "fields",
"type": "field_def[]"
}
]
},
{
"name": "action_def",
"base": "",
"fields": [
{
"name": "name",
"type": "name"
},
{
"name": "type",
"type": "string"
},
{
"name": "ricardian_contract",
"type": "string"
}
]
},
{
"name": "table_def",
"base": "",
"fields": [
{
"name": "name",
"type": "name"
},
{
"name": "index_type",
"type": "string"
},
{
"name": "key_names",
"type": "string[]"
},
{
"name": "key_types",
"type": "string[]"
},
{
"name": "type",
"type": "string"
}
]
},
{
"name": "clause_pair",
"base": "",
"fields": [
{
"name": "id",
"type": "string"
},
{
"name": "body",
"type": "string"
}
]
},
{
"name": "error_message",
"base": "",
"fields": [
{
"name": "error_code",
"type": "uint64"
},
{
"name": "error_msg",
"type": "string"
}
]
},
{
"name": "variant_def",
"base": "",
"fields": [
{
"name": "name",
"type": "string"
},
{
"name": "types",
"type": "string[]"
}
]
},
{
"name": "abi_def",
"base": "",
"fields": [
{
"name": "version",
"type": "string"
},
{
"name": "types",
"type": "type_def[]"
},
{
"name": "structs",
"type": "struct_def[]"
},
{
"name": "actions",
"type": "action_def[]"
},
{
"name": "tables",
"type": "table_def[]"
},
{
"name": "ricardian_clauses",
"type": "clause_pair[]"
},
{
"name": "error_messages",
"type": "error_message[]"
},
{
"name": "abi_extensions",
"type": "extensions_entry[]"
},
{
"name": "variants",
"type": "variant_def[]$"
}
]
}
]
}
@@ -1,117 +0,0 @@
{
"version": "eosio::abi/1.0",
"types": [
{
"new_type_name": "account_name",
"type": "name"
},
{
"new_type_name": "action_name",
"type": "name"
},
{
"new_type_name": "permission_name",
"type": "name"
}
],
"structs": [
{
"name": "permission_level",
"base": "",
"fields": [
{
"name": "actor",
"type": "account_name"
},
{
"name": "permission",
"type": "permission_name"
}
]
},
{
"name": "action",
"base": "",
"fields": [
{
"name": "account",
"type": "account_name"
},
{
"name": "name",
"type": "action_name"
},
{
"name": "authorization",
"type": "permission_level[]"
},
{
"name": "data",
"type": "bytes"
}
]
},
{
"name": "extension",
"base": "",
"fields": [
{
"name": "type",
"type": "uint16"
},
{
"name": "data",
"type": "bytes"
}
]
},
{
"name": "transaction_header",
"base": "",
"fields": [
{
"name": "expiration",
"type": "time_point_sec"
},
{
"name": "ref_block_num",
"type": "uint16"
},
{
"name": "ref_block_prefix",
"type": "uint32"
},
{
"name": "max_net_usage_words",
"type": "varuint32"
},
{
"name": "max_cpu_usage_ms",
"type": "uint8"
},
{
"name": "delay_sec",
"type": "varuint32"
}
]
},
{
"name": "transaction",
"base": "transaction_header",
"fields": [
{
"name": "context_free_actions",
"type": "action[]"
},
{
"name": "actions",
"type": "action[]"
},
{
"name": "transaction_extensions",
"type": "extension[]"
}
]
}
]
}
-1
View File
@@ -1 +0,0 @@
export {};
-259
View File
@@ -1,259 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var _this = this;
Object.defineProperty(exports, "__esModule", { value: true });
var text_encoding_1 = require("text-encoding");
var eosjs_api_1 = require("../eosjs-api");
var eosjs_jsonrpc_1 = require("../eosjs-jsonrpc");
var eosjs_jssig_1 = require("../eosjs-jssig");
var transaction = {
expiration: '2018-09-04T18:42:49',
ref_block_num: 38096,
ref_block_prefix: 505360011,
max_net_usage_words: 0,
max_cpu_usage_ms: 0,
delay_sec: 0,
context_free_actions: [],
actions: [
{
account: 'testeostoken',
name: 'transfer',
authorization: [
{
actor: 'thegazelle',
permission: 'active',
},
],
data: {
from: 'thegazelle',
to: 'remasteryoda',
quantity: '1.0000 EOS',
memo: 'For a secure future.',
},
hex_data: "00808a517dc354cb6012f557656ca4ba102700000000000004454f530000000014466f722\n 06120736563757265206675747572652e",
},
{
account: 'testeostoken',
name: 'transfer',
authorization: [
{
actor: 'thegazelle',
permission: 'active',
},
],
data: {
from: 'thegazelle',
to: 'remasteryoda',
quantity: '2.0000 EOS',
memo: 'For a second secure future (multiverse?)',
},
hex_data: "00808a517dc354cb6012f557656ca4ba204e00000000000004454f530000000028466f722061207365636f6e642073656\n 37572652066757475726520286d756c746976657273653f29",
},
],
transaction_extensions: [],
};
var serializedTx = [
41, 210, 142, 91, 208, 148, 139, 46, 31, 30, 0, 0, 0, 0, 2, 48, 21, 164,
25, 83, 149, 177, 202, 0, 0, 0, 87, 45, 60, 205, 205, 1, 0, 128, 138, 81,
125, 195, 84, 203, 0, 0, 0, 0, 168, 237, 50, 50, 0, 48, 21, 164, 25, 83,
149, 177, 202, 0, 0, 0, 87, 45, 60, 205, 205, 1, 0, 128, 138, 81, 125,
195, 84, 203, 0, 0, 0, 0, 168, 237, 50, 50, 0, 0,
];
var deserializedTx = {
actions: [
{
account: 'testeostoken',
authorization: [{ actor: 'thegazelle', permission: 'active' }],
data: '',
name: 'transfer',
},
{
account: 'testeostoken',
authorization: [{ actor: 'thegazelle', permission: 'active' }],
data: '',
name: 'transfer',
},
],
context_free_actions: [],
delay_sec: 0,
expiration: '2018-09-04T18:42:49.000',
max_cpu_usage_ms: 0,
max_net_usage_words: 0,
ref_block_num: 38096,
ref_block_prefix: 505360011,
transaction_extensions: [],
};
var serializedActions = [
{
account: 'testeostoken',
authorization: [{ actor: 'thegazelle', permission: 'active' }],
data: "00808A517DC354CB6012F557656CA4BA102700000000000004454F530000000014466F72206120736563757265206675747572652E",
name: 'transfer',
},
{
account: 'testeostoken',
authorization: [{ actor: 'thegazelle', permission: 'active' }],
data: "00808A517DC354CB6012F557656CA4BA204E00000000000004454F530000000028466F722061207365636F6E64207365637572652066757475726520286D756C746976657273653F29",
name: 'transfer',
},
];
var deserializedActions = [
{
account: 'testeostoken',
authorization: [{ actor: 'thegazelle', permission: 'active' }],
data: {
from: 'thegazelle',
memo: 'For a secure future.',
quantity: '1.0000 EOS',
to: 'remasteryoda',
},
name: 'transfer',
},
{
account: 'testeostoken',
authorization: [{ actor: 'thegazelle', permission: 'active' }],
data: {
from: 'thegazelle',
memo: 'For a second secure future (multiverse?)',
quantity: '2.0000 EOS',
to: 'remasteryoda',
},
name: 'transfer',
},
];
describe('eosjs-api', function () {
var api;
var fetch = function (input, init) { return __awaiter(_this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
return [2 /*return*/, ({
ok: true,
json: function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
if (input === '/v1/chain/get_raw_code_and_abi') {
return [2 /*return*/, {
account_name: 'testeostoken',
abi: "DmVvc2lvOjphYmkvMS4wAQxhY2NvdW50X25hbWUEbmFtZQUIdHJhbnNmZXIABARmcm9tDGFjY291bnRfbmFtZQJ0bwxhY2NvdW50X25hbWUIcXVhbnRpdHkFYXNzZXQEbWVtbwZzdHJpbmcGY3JlYXRlAAIGaXNzdWVyDGFjY291bnRfbmFtZQ5tYXhpbXVtX3N1cHBseQVhc3NldAVpc3N1ZQADAnRvDGFjY291bnRfbmFtZQhxdWFudGl0eQVhc3NldARtZW1vBnN0cmluZwdhY2NvdW50AAEHYmFsYW5jZQVhc3NldA5jdXJyZW5jeV9zdGF0cwADBnN1cHBseQVhc3NldAptYXhfc3VwcGx5BWFzc2V0Bmlzc3VlcgxhY2NvdW50X25hbWUDAAAAVy08zc0IdHJhbnNmZXLnBSMjIFRyYW5zZmVyIFRlcm1zICYgQ29uZGl0aW9ucwoKSSwge3tmcm9tfX0sIGNlcnRpZnkgdGhlIGZvbGxvd2luZyB0byBiZSB0cnVlIHRvIHRoZSBiZXN0IG9mIG15IGtub3dsZWRnZToKCjEuIEkgY2VydGlmeSB0aGF0IHt7cXVhbnRpdHl9fSBpcyBub3QgdGhlIHByb2NlZWRzIG9mIGZyYXVkdWxlbnQgb3IgdmlvbGVudCBhY3Rpdml0aWVzLgoyLiBJIGNlcnRpZnkgdGhhdCwgdG8gdGhlIGJlc3Qgb2YgbXkga25vd2xlZGdlLCB7e3RvfX0gaXMgbm90IHN1cHBvcnRpbmcgaW5pdGlhdGlvbiBvZiB2aW9sZW5jZSBhZ2FpbnN0IG90aGVycy4KMy4gSSBoYXZlIGRpc2Nsb3NlZCBhbnkgY29udHJhY3R1YWwgdGVybXMgJiBjb25kaXRpb25zIHdpdGggcmVzcGVjdCB0byB7e3F1YW50aXR5fX0gdG8ge3t0b319LgoKSSB1bmRlcnN0YW5kIHRoYXQgZnVuZHMgdHJhbnNmZXJzIGFyZSBub3QgcmV2ZXJzaWJsZSBhZnRlciB0aGUge3t0cmFuc2FjdGlvbi5kZWxheX19IHNlY29uZHMgb3Igb3RoZXIgZGVsYXkgYXMgY29uZmlndXJlZCBieSB7e2Zyb219fSdzIHBlcm1pc3Npb25zLgoKSWYgdGhpcyBhY3Rpb24gZmFpbHMgdG8gYmUgaXJyZXZlcnNpYmx5IGNvbmZpcm1lZCBhZnRlciByZWNlaXZpbmcgZ29vZHMgb3Igc2VydmljZXMgZnJvbSAne3t0b319JywgSSBhZ3JlZSB0byBlaXRoZXIgcmV0dXJuIHRoZSBnb29kcyBvciBzZXJ2aWNlcyBvciByZXNlbmQge3txdWFudGl0eX19IGluIGEgdGltZWx5IG1hbm5lci4KAAAAAAClMXYFaXNzdWUAAAAAAKhs1EUGY3JlYXRlAAIAAAA4T00RMgNpNjQBCGN1cnJlbmN5AQZ1aW50NjQHYWNjb3VudAAAAAAAkE3GA2k2NAEIY3VycmVuY3kBBnVpbnQ2NA5jdXJyZW5jeV9zdGF0cwAAAA===",
}];
}
return [2 /*return*/, transaction];
});
}); },
})];
});
}); };
beforeEach(function () {
var rpc = new eosjs_jsonrpc_1.JsonRpc('', { fetch: fetch });
var signatureProvider = new eosjs_jssig_1.JsSignatureProvider(['5JtUScZK2XEp3g9gh7F8bwtPTRAkASmNrrftmx4AxDKD5K4zDnr']);
var chainId = '038f4b0fc8ff18a4f0842a8f0564611f6e96e8535901dd45e43ac8691a1c4dca';
api = new eosjs_api_1.Api({
rpc: rpc, signatureProvider: signatureProvider, chainId: chainId, textDecoder: new text_encoding_1.TextDecoder(), textEncoder: new text_encoding_1.TextEncoder(),
});
});
it('Doesnt crash', function () {
expect(api).toBeTruthy();
});
it('getAbi returns an abi', function () { return __awaiter(_this, void 0, void 0, function () {
var response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, api.getAbi('testeostoken')];
case 1:
response = _a.sent();
expect(response).toBeTruthy();
return [2 /*return*/];
}
});
}); });
it('getTransactionAbis returns abis by transactions', function () { return __awaiter(_this, void 0, void 0, function () {
var response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, api.getTransactionAbis(transaction)];
case 1:
response = _a.sent();
expect(response[0].abi.length).toBeGreaterThan(0);
return [2 /*return*/];
}
});
}); });
it('getContract returns a contract', function () { return __awaiter(_this, void 0, void 0, function () {
var response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, api.getContract('testeostoken')];
case 1:
response = _a.sent();
expect(response.actions).toBeTruthy();
return [2 /*return*/];
}
});
}); });
it('deserializeTransaction converts tx from binary', function () {
var tx = api.deserializeTransaction(serializedTx);
expect(tx).toEqual(deserializedTx);
});
it('serializeActions converts actions to hex', function () { return __awaiter(_this, void 0, void 0, function () {
var response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, api.serializeActions(transaction.actions)];
case 1:
response = _a.sent();
expect(response).toEqual(serializedActions);
return [2 /*return*/];
}
});
}); });
it('deserializeActions converts actions from hex', function () { return __awaiter(_this, void 0, void 0, function () {
var response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, api.deserializeActions(serializedActions)];
case 1:
response = _a.sent();
expect(response).toEqual(deserializedActions);
return [2 /*return*/];
}
});
}); });
it('hasRequiredTaposFields returns true, if required fields are present', function () {
var response = api.hasRequiredTaposFields(transaction);
expect(response).toEqual(true);
});
});
//# sourceMappingURL=eosjs-api.test.js.map
File diff suppressed because one or more lines are too long
-1
View File
@@ -1 +0,0 @@
export {};
@@ -1,880 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var _this = this;
Object.defineProperty(exports, "__esModule", { value: true });
var eosjs_jsonrpc_1 = require("../eosjs-jsonrpc");
var eosjs_rpcerror_1 = require("../eosjs-rpcerror");
describe('JSON RPC', function () {
var endpoint = 'http://localhost';
var fetchMock = fetch;
var jsonRpc;
beforeEach(function () {
fetchMock.resetMocks();
jsonRpc = new eosjs_jsonrpc_1.JsonRpc(endpoint);
});
it('throws error bad status', function () { return __awaiter(_this, void 0, void 0, function () {
var actMessage, expMessage, accountName, expReturn, e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
actMessage = '';
expMessage = 'Not Found';
accountName = 'myaccountaaa';
expReturn = { data: '12345', message: expMessage };
fetchMock.once(JSON.stringify(expReturn), { status: 404 });
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, jsonRpc.get_abi(accountName)];
case 2:
_a.sent();
return [3 /*break*/, 4];
case 3:
e_1 = _a.sent();
expect(e_1).toBeInstanceOf(eosjs_rpcerror_1.RpcError);
actMessage = e_1.message;
return [3 /*break*/, 4];
case 4:
expect(actMessage).toEqual(expMessage);
return [2 /*return*/];
}
});
}); });
it('throws error unprocessed', function () { return __awaiter(_this, void 0, void 0, function () {
var actMessage, expMessage, accountName, expReturn, e_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
actMessage = '';
expMessage = 'Not Processed';
accountName = 'myaccountaaa';
expReturn = {
data: '12345',
processed: {
except: {
message: expMessage,
},
},
};
fetchMock.once(JSON.stringify(expReturn));
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, jsonRpc.get_abi(accountName)];
case 2:
_a.sent();
return [3 /*break*/, 4];
case 3:
e_2 = _a.sent();
expect(e_2).toBeInstanceOf(eosjs_rpcerror_1.RpcError);
actMessage = e_2.message;
return [3 /*break*/, 4];
case 4:
expect(actMessage).toEqual(expMessage);
return [2 /*return*/];
}
});
}); });
it('calls provided fetch instead of default', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, accountName, expReturn, expParams, mockResp, myFetch;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/chain/get_abi';
accountName = 'myaccountaaa';
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({
account_name: accountName,
}),
method: 'POST',
};
mockResp = {
json: function () {
return expReturn;
},
ok: true,
};
myFetch = jest.fn();
myFetch.mockReturnValue(mockResp);
jsonRpc = new eosjs_jsonrpc_1.JsonRpc(endpoint, { fetch: myFetch });
return [4 /*yield*/, jsonRpc.get_abi(accountName)];
case 1:
_a.sent();
expect(myFetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls get_abi', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, accountName, expReturn, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/chain/get_abi';
accountName = 'myaccountaaa';
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({
account_name: accountName,
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.get_abi(accountName)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls get_account', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, accountName, expReturn, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/chain/get_account';
accountName = 'myaccountaaa';
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({
account_name: accountName,
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.get_account(accountName)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls get_block_header_state', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, blockNumOrId, expReturn, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/chain/get_block_header_state';
blockNumOrId = 1234;
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({
block_num_or_id: blockNumOrId,
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.get_block_header_state(blockNumOrId)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls get_block', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, blockNumOrId, expReturn, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/chain/get_block';
blockNumOrId = 1234;
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({
block_num_or_id: blockNumOrId,
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.get_block(blockNumOrId)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls get_code', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, accountName, expReturn, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/chain/get_code';
accountName = 'myaccountaaa';
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({
account_name: accountName,
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.get_code(accountName)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls get_currency_balance with all params', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, code, account, symbol, expReturn, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/chain/get_currency_balance';
code = 'morse';
account = 'myaccountaaa';
symbol = 'EOS';
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({
code: code,
account: account,
symbol: symbol,
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.get_currency_balance(code, account, symbol)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls get_currency_balance with default params', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, code, account, symbol, expReturn, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/chain/get_currency_balance';
code = 'morse';
account = 'myaccountaaa';
symbol = null;
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({
code: code,
account: account,
symbol: symbol,
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.get_currency_balance(code, account)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls get_currency_stats with all params', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, code, symbol, expReturn, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/chain/get_currency_stats';
code = 'morse';
symbol = 'EOS';
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({
code: code,
symbol: symbol,
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.get_currency_stats(code, symbol)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls get_info', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, expReturn, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/chain/get_info';
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.get_info()];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls get_producer_schedule', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, expReturn, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/chain/get_producer_schedule';
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.get_producer_schedule()];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls get_producers with all params', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, json, lowerBound, limit, expReturn, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/chain/get_producers';
json = false;
lowerBound = 'zero';
limit = 10;
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({
json: json,
lower_bound: lowerBound,
limit: limit,
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.get_producers(json, lowerBound, limit)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls get_producers with default params', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, json, lowerBound, limit, expReturn, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/chain/get_producers';
json = true;
lowerBound = '';
limit = 50;
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({
json: json,
lower_bound: lowerBound,
limit: limit,
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.get_producers()];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls get_raw_code_and_abi', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, accountName, expReturn, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/chain/get_raw_code_and_abi';
accountName = 'myaccountaaa';
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({
account_name: accountName,
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.get_raw_code_and_abi(accountName)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls get_table_rows with all params', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, json, code, scope, table, tableKey, lowerBound, upperBound, limit, indexPosition, keyType, expReturn, reverse, showPayer, callParams, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/chain/get_table_rows';
json = false;
code = 'morse';
scope = 'minty';
table = 'coffee';
tableKey = 'front_door';
lowerBound = 'zero';
upperBound = 'five';
limit = 20;
indexPosition = 1;
keyType = 'str';
expReturn = { data: '12345' };
reverse = false;
showPayer = false;
callParams = {
json: json,
code: code,
scope: scope,
table: table,
table_key: tableKey,
lower_bound: lowerBound,
upper_bound: upperBound,
index_position: indexPosition,
key_type: keyType,
limit: limit,
reverse: reverse,
show_payer: showPayer,
};
expParams = {
body: JSON.stringify(callParams),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.get_table_rows(callParams)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls get_table_rows with default params', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, json, code, scope, table, tableKey, lowerBound, upperBound, limit, indexPosition, keyType, reverse, showPayer, expReturn, callParams, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/chain/get_table_rows';
json = true;
code = 'morse';
scope = 'minty';
table = 'coffee';
tableKey = '';
lowerBound = '';
upperBound = '';
limit = 10;
indexPosition = 1;
keyType = '';
reverse = false;
showPayer = false;
expReturn = { data: '12345' };
callParams = {
code: code,
scope: scope,
table: table,
};
expParams = {
body: JSON.stringify({
json: json,
code: code,
scope: scope,
table: table,
table_key: tableKey,
lower_bound: lowerBound,
upper_bound: upperBound,
index_position: indexPosition,
key_type: keyType,
limit: limit,
reverse: reverse,
show_payer: showPayer,
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.get_table_rows(callParams)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls get_table_by_scope with all params', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, code, table, lowerBound, upperBound, limit, expReturn, callParams, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/chain/get_table_by_scope';
code = 'morse';
table = 'coffee';
lowerBound = 'minty';
upperBound = 'minty';
limit = 20;
expReturn = { data: '12345' };
callParams = {
code: code,
table: table,
lower_bound: lowerBound,
upper_bound: upperBound,
limit: limit,
};
expParams = {
body: JSON.stringify(callParams),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.get_table_by_scope(callParams)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls get_table_by_scope with default params', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, code, table, lowerBound, upperBound, limit, expReturn, callParams, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/chain/get_table_by_scope';
code = 'morse';
table = 'coffee';
lowerBound = '';
upperBound = '';
limit = 10;
expReturn = { data: '12345' };
callParams = {
code: code,
table: table,
};
expParams = {
body: JSON.stringify({
code: code,
table: table,
lower_bound: lowerBound,
upper_bound: upperBound,
limit: limit,
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.get_table_by_scope(callParams)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls getRequiredKeys', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, keys, expReturn, callParams, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/chain/get_required_keys';
keys = ['key1', 'key2', 'key3'];
expReturn = { required_keys: keys };
callParams = {
transaction: 'mytxn',
availableKeys: keys,
};
expParams = {
body: JSON.stringify({
transaction: callParams.transaction,
available_keys: callParams.availableKeys,
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.getRequiredKeys(callParams)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn.required_keys);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls push_transaction', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, signatures, serializedTransaction, limit, expReturn, callParams, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/chain/push_transaction';
signatures = [
'George Washington',
'John Hancock',
'Abraham Lincoln',
];
serializedTransaction = new Uint8Array([
0, 16, 32, 128, 255,
]);
limit = 50;
expReturn = { data: '12345' };
callParams = {
signatures: signatures,
serializedTransaction: serializedTransaction,
};
expParams = {
body: JSON.stringify({
signatures: signatures,
compression: 0,
packed_context_free_data: '',
packed_trx: '00102080ff',
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.push_transaction(callParams)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls db_size_get', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, expReturn, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/db_size/get';
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.db_size_get()];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls history_get_actions with all params', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, accountName, pos, offset, expReturn, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/history/get_actions';
accountName = 'myaccountaaa';
pos = 5;
offset = 10;
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({
account_name: accountName,
pos: pos,
offset: offset,
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.history_get_actions(accountName, pos, offset)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls history_get_actions with default params', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, accountName, pos, offset, expReturn, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/history/get_actions';
accountName = 'myaccountaaa';
pos = null;
offset = null;
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({
account_name: accountName,
pos: pos,
offset: offset,
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.history_get_actions(accountName)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls history_get_transaction with all params', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, id, blockNumHint, expReturn, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/history/get_transaction';
id = 'myaccountaaa';
blockNumHint = 20;
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({
id: id,
block_num_hint: blockNumHint,
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.history_get_transaction(id, blockNumHint)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls history_get_transaction with default params', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, id, blockNumHint, expReturn, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/history/get_transaction';
id = 'myaccountaaa';
blockNumHint = null;
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({
id: id,
block_num_hint: blockNumHint,
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.history_get_transaction(id)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls history_get_key_accounts', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, publicKey, expReturn, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/history/get_key_accounts';
publicKey = 'key12345';
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({
public_key: publicKey,
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.history_get_key_accounts(publicKey)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
it('calls history_get_controlled_accounts', function () { return __awaiter(_this, void 0, void 0, function () {
var expPath, controllingAccount, expReturn, expParams, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
expPath = '/v1/history/get_controlled_accounts';
controllingAccount = 'key12345';
expReturn = { data: '12345' };
expParams = {
body: JSON.stringify({
controlling_account: controllingAccount,
}),
method: 'POST',
};
fetchMock.once(JSON.stringify(expReturn));
return [4 /*yield*/, jsonRpc.history_get_controlled_accounts(controllingAccount)];
case 1:
response = _a.sent();
expect(response).toEqual(expReturn);
expect(fetch).toBeCalledWith(endpoint + expPath, expParams);
return [2 /*return*/];
}
});
}); });
});
//# sourceMappingURL=eosjs-jsonrpc.test.js.map
File diff suppressed because one or more lines are too long
-1
View File
@@ -1 +0,0 @@
export {};
@@ -1,92 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var _this = this;
Object.defineProperty(exports, "__esModule", { value: true });
var ecc = require("eosjs-ecc");
var eosjs_jssig_1 = require("../eosjs-jssig");
describe('JsSignatureProvider', function () {
var privateKeys = ['key1', 'key2', 'key3'];
var publicKeys = [
'PUB_K1_8iD9ABKFH5b9JyFgb5PE51BdCV74qGN9UMfg9V3TwaExCQWxJm',
'PUB_K1_8f2o2LLQ3phteqyazxirQZnQzQFpnjLnXiUFEJcsSYhnjWNvSX',
'PUB_K1_5imfbmmHC83VRxLRTcvovviAc6LPpyszcDuKtkwka9e9Jg37Hp',
];
it('builds public keys from private when constructed', function () { return __awaiter(_this, void 0, void 0, function () {
var eccPkFromString, provider, actualPublicKeys;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
eccPkFromString = jest.spyOn(ecc.PrivateKey, 'fromString');
eccPkFromString.mockImplementation(function (k) { return ecc.PrivateKey.fromHex(ecc.sha256(k)); });
provider = new eosjs_jssig_1.JsSignatureProvider(privateKeys);
return [4 /*yield*/, provider.getAvailableKeys()];
case 1:
actualPublicKeys = _a.sent();
expect(eccPkFromString).toHaveBeenCalledTimes(privateKeys.length);
expect(actualPublicKeys).toEqual(publicKeys);
return [2 /*return*/];
}
});
}); });
it('signs a transaction', function () { return __awaiter(_this, void 0, void 0, function () {
var eccSignatureSign, provider, chainId, requiredKeys, serializedTransaction, abis, signOutput;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
eccSignatureSign = jest.spyOn(ecc.Signature, 'sign');
eccSignatureSign.mockImplementation(function (buffer, signKey) { return signKey; });
provider = new eosjs_jssig_1.JsSignatureProvider(privateKeys);
chainId = '12345';
requiredKeys = [
publicKeys[0],
publicKeys[2],
];
serializedTransaction = new Uint8Array([
0, 16, 32, 128, 255,
]);
abis = [];
return [4 /*yield*/, provider.sign({ chainId: chainId, requiredKeys: requiredKeys, serializedTransaction: serializedTransaction, abis: abis })];
case 1:
signOutput = _a.sent();
expect(eccSignatureSign).toHaveBeenCalledTimes(2);
expect(signOutput).toEqual({ signatures: [privateKeys[0], privateKeys[2]], serializedTransaction: serializedTransaction });
return [2 /*return*/];
}
});
}); });
});
//# sourceMappingURL=eosjs-jssig.test.js.map
@@ -1 +0,0 @@
{"version":3,"file":"eosjs-jssig.test.js","sourceRoot":"","sources":["../../src/tests/eosjs-jssig.test.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iBA0CA;;AA1CA,+BAAiC;AACjC,8CAAqD;AAErD,QAAQ,CAAC,qBAAqB,EAAE;IAC5B,IAAM,WAAW,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7C,IAAM,UAAU,GAAG;QACf,2DAA2D;QAC3D,2DAA2D;QAC3D,2DAA2D;KAC9D,CAAC;IAEF,EAAE,CAAC,kDAAkD,EAAE;;;;;oBAC7C,eAAe,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC;oBACjE,eAAe,CAAC,kBAAkB,CAAC,UAAC,CAAC,IAAK,OAAA,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAArC,CAAqC,CAAC,CAAC;oBAC3E,QAAQ,GAAG,IAAI,iCAAmB,CAAC,WAAW,CAAC,CAAC;oBAC7B,qBAAM,QAAQ,CAAC,gBAAgB,EAAE,EAAA;;oBAApD,gBAAgB,GAAG,SAAiC;oBAE1D,MAAM,CAAC,eAAe,CAAC,CAAC,qBAAqB,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;oBAClE,MAAM,CAAC,gBAAgB,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;;;;SAChD,CAAC,CAAC;IAEH,EAAE,CAAC,qBAAqB,EAAE;;;;;oBAChB,gBAAgB,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;oBAC3D,gBAAgB,CAAC,kBAAkB,CAAC,UAAC,MAAM,EAAE,OAAO,IAAK,OAAA,OAAO,EAAP,CAAO,CAAC,CAAC;oBAE5D,QAAQ,GAAG,IAAI,iCAAmB,CAAC,WAAW,CAAC,CAAC;oBAChD,OAAO,GAAG,OAAO,CAAC;oBAClB,YAAY,GAAG;wBACjB,UAAU,CAAC,CAAC,CAAC;wBACb,UAAU,CAAC,CAAC,CAAC;qBAChB,CAAC;oBACI,qBAAqB,GAAG,IAAI,UAAU,CAAC;wBACzC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,EAAE,GAAG;qBACtB,CAAC,CAAC;oBACG,IAAI,GAAU,EAAE,CAAC;oBAEJ,qBAAM,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,SAAA,EAAE,YAAY,cAAA,EAAE,qBAAqB,uBAAA,EAAE,IAAI,MAAA,EAAE,CAAC,EAAA;;oBAAxF,UAAU,GAAG,SAA2E;oBAE9F,MAAM,CAAC,gBAAgB,CAAC,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC;oBAClD,MAAM,CAAC,UAAU,CAAC,CAAC,OAAO,CAAC,EAAE,UAAU,EAAE,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,EAAE,qBAAqB,uBAAA,EAAE,CAAC,CAAC;;;;SACvG,CAAC,CAAC;AACP,CAAC,CAAC,CAAC"}
-1
View File
@@ -1 +0,0 @@
declare const tests: any;
-140
View File
@@ -1,140 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var _this = this;
var tests = require('./node');
describe('Node JS environment', function () {
var transactionResponse;
var transactionSignatures;
var failedAsPlanned;
it('transacts with configuration object', function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, tests.transactWithConfig()];
case 1:
transactionResponse = _a.sent();
expect(Object.keys(transactionResponse)).toContain('transaction_id');
return [2 /*return*/];
}
});
}); });
it('transacts with manually configured TAPOS fields', function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, tests.transactWithoutConfig()];
case 1:
transactionResponse = _a.sent();
expect(Object.keys(transactionResponse)).toContain('transaction_id');
return [2 /*return*/];
}
});
}); }, 10000);
it('transacts without broadcasting, returning signatures and packed transaction', function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, tests.transactWithoutBroadcast()];
case 1:
transactionSignatures = _a.sent();
expect(Object.keys(transactionSignatures)).toContain('signatures');
expect(Object.keys(transactionSignatures)).toContain('serializedTransaction');
return [2 /*return*/];
}
});
}); });
it('broadcasts packed transaction, given valid signatures', function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, tests.transactWithoutBroadcast()];
case 1:
transactionSignatures = _a.sent();
return [4 /*yield*/, tests.broadcastResult(transactionSignatures)];
case 2:
transactionResponse = _a.sent();
expect(Object.keys(transactionResponse)).toContain('transaction_id');
return [2 /*return*/];
}
});
}); });
it('throws appropriate error message without configuration object or TAPOS in place', function () { return __awaiter(_this, void 0, void 0, function () {
var e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
failedAsPlanned = true;
return [4 /*yield*/, tests.transactShouldFail()];
case 1:
_a.sent();
failedAsPlanned = false;
return [3 /*break*/, 3];
case 2:
e_1 = _a.sent();
if (e_1.message !== 'Required configuration or TAPOS fields are not present') {
failedAsPlanned = false;
}
return [3 /*break*/, 3];
case 3:
expect(failedAsPlanned).toEqual(true);
return [2 /*return*/];
}
});
}); });
it('throws an an error with RpcError structure for invalid RPC calls', function () { return __awaiter(_this, void 0, void 0, function () {
var e_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
failedAsPlanned = true;
return [4 /*yield*/, tests.rpcShouldFail()];
case 1:
_a.sent();
failedAsPlanned = false;
return [3 /*break*/, 3];
case 2:
e_2 = _a.sent();
if (!e_2.json || !e_2.json.error || !(e_2.json.error.hasOwnProperty('details'))) {
failedAsPlanned = false;
}
return [3 /*break*/, 3];
case 3:
expect(failedAsPlanned).toEqual(true);
return [2 /*return*/];
}
});
}); });
});
//# sourceMappingURL=node.test.js.map
@@ -1 +0,0 @@
{"version":3,"file":"node.test.js","sourceRoot":"","sources":["../../src/tests/node.test.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iBAuDA;AAvDA,IAAM,KAAK,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;AAEhC,QAAQ,CAAC,qBAAqB,EAAE;IAC5B,IAAI,mBAAwB,CAAC;IAC7B,IAAI,qBAA0B,CAAC;IAC/B,IAAI,eAAwB,CAAC;IAE7B,EAAE,CAAC,qCAAqC,EAAE;;;wBAChB,qBAAM,KAAK,CAAC,kBAAkB,EAAE,EAAA;;oBAAtD,mBAAmB,GAAG,SAAgC,CAAC;oBACvD,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC,CAAC,SAAS,CAAC,gBAAgB,CAAC,CAAC;;;;SACxE,CAAC,CAAC;IAEH,EAAE,CAAC,iDAAiD,EAAE;;;wBAC5B,qBAAM,KAAK,CAAC,qBAAqB,EAAE,EAAA;;oBAAzD,mBAAmB,GAAG,SAAmC,CAAC;oBAC1D,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC,CAAC,SAAS,CAAC,gBAAgB,CAAC,CAAC;;;;SACxE,EAAE,KAAK,CAAC,CAAC;IAEV,EAAE,CAAC,6EAA6E,EAAE;;;wBACtD,qBAAM,KAAK,CAAC,wBAAwB,EAAE,EAAA;;oBAA9D,qBAAqB,GAAG,SAAsC,CAAC;oBAC/D,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;oBACnE,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC,CAAC,SAAS,CAAC,uBAAuB,CAAC,CAAC;;;;SACjF,CAAC,CAAC;IAEH,EAAE,CAAC,uDAAuD,EAAE;;;wBAChC,qBAAM,KAAK,CAAC,wBAAwB,EAAE,EAAA;;oBAA9D,qBAAqB,GAAG,SAAsC,CAAC;oBACzC,qBAAM,KAAK,CAAC,eAAe,CAAC,qBAAqB,CAAC,EAAA;;oBAAxE,mBAAmB,GAAG,SAAkD,CAAC;oBACzE,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC,CAAC,SAAS,CAAC,gBAAgB,CAAC,CAAC;;;;SACxE,CAAC,CAAC;IAEH,EAAE,CAAC,iFAAiF,EAAE;;;;;;oBAE9E,eAAe,GAAG,IAAI,CAAC;oBACvB,qBAAM,KAAK,CAAC,kBAAkB,EAAE,EAAA;;oBAAhC,SAAgC,CAAC;oBACjC,eAAe,GAAG,KAAK,CAAC;;;;oBAExB,IAAI,GAAC,CAAC,OAAO,KAAK,wDAAwD,EAAE;wBACxE,eAAe,GAAG,KAAK,CAAC;qBAC3B;;;oBAEL,MAAM,CAAC,eAAe,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;;;;SACzC,CAAC,CAAC;IAEH,EAAE,CAAC,kEAAkE,EAAE;;;;;;oBAE/D,eAAe,GAAG,IAAI,CAAC;oBACvB,qBAAM,KAAK,CAAC,aAAa,EAAE,EAAA;;oBAA3B,SAA2B,CAAC;oBAC5B,eAAe,GAAG,KAAK,CAAC;;;;oBAExB,IAAI,CAAC,GAAC,CAAC,IAAI,IAAI,CAAC,GAAC,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,CAAC,GAAC,CAAC,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC,EAAE;wBACvE,eAAe,GAAG,KAAK,CAAC;qBAC3B;;;oBAEL,MAAM,CAAC,eAAe,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;;;;SACzC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC"}
-439
View File
@@ -1,439 +0,0 @@
import {createHash} from "crypto";
import * as _ from "lodash";
import {FastifyInstance, FastifyReply, FastifyRequest, FastifySchema, HTTPMethods} from "fastify";
import got from "got";
export function extendResponseSchema(responseProps: any) {
const props = {
query_time_ms: {type: "number"},
cached: {type: "boolean"},
hot_only: {type: "boolean"},
lib: {type: "number"},
total: {
type: "object",
properties: {
value: {type: "number"},
relation: {type: "string"}
}
}
};
for (const p in responseProps) {
if (responseProps.hasOwnProperty(p)) {
props[p] = responseProps[p];
}
}
return {
200: {
type: 'object',
properties: props
}
};
}
export function extendQueryStringSchema(queryParams: any, required?: string[]) {
const params = {
limit: {
description: 'limit of [n] results per page',
type: 'integer',
minimum: 1
},
skip: {
description: 'skip [n] results',
type: 'integer',
minimum: 0
}
};
for (const p in queryParams) {
if (queryParams.hasOwnProperty(p)) {
params[p] = queryParams[p];
}
}
const schema = {
type: 'object',
properties: params
}
if (required && required.length > 0) {
schema["required"] = required;
}
return schema;
}
export async function getCacheByHash(redis, key, chain) {
const hash = createHash('sha256');
const query_hash = hash.update(chain + "-" + key).digest('hex');
return [await redis.get(query_hash), query_hash];
}
export function mergeActionMeta(action) {
const name = action.act.name;
if (action['@' + name]) {
action['act']['data'] = _.merge(action['@' + name], action['act']['data']);
delete action['@' + name];
}
action['timestamp'] = action['@timestamp'];
// delete action['@timestamp'];
}
export function mergeDeltaMeta(delta: any) {
const name = delta.table;
if (delta["@" + name]) {
delta['data'] = _.merge(delta['@' + name], delta['data']);
delete delta['@' + name];
}
delta['timestamp'] = delta['@timestamp'];
delete delta['@timestamp'];
return delta;
}
export function setCacheByHash(fastify, hash, response, expiration?: number) {
if (fastify.manager.config.api.enable_caching) {
let exp;
if (expiration) {
exp = expiration;
} else {
exp = fastify.manager.config.api.cache_life;
}
fastify.redis.set(hash, JSON.stringify(response), 'EX', exp).catch(console.log);
}
}
export function getRouteName(filename: string) {
const arr = filename.split("/");
return arr[arr.length - 2];
}
export function addApiRoute(
fastifyInstance: FastifyInstance,
method: HTTPMethods | HTTPMethods[],
routeName: string,
routeBuilder: (fastify: FastifyInstance, route: string) => (request: FastifyRequest, reply: FastifyReply) => Promise<void>,
schema: FastifySchema
) {
fastifyInstance.route({
url: '/' + routeName,
method,
handler: routeBuilder(fastifyInstance, routeName),
schema
});
}
export async function getCachedResponse(server: FastifyInstance, route: string, key: any) {
const chain = server.manager.chain;
let resp, hash;
if (server.manager.config.api.enable_caching) {
[resp, hash] = await getCacheByHash(server.redis, route + JSON.stringify(key), chain);
if (resp) {
resp = JSON.parse(resp);
resp['cached'] = true;
return [resp, hash];
} else {
return [null, hash];
}
} else {
return [null, null];
}
}
export function getTrackTotalHits(query) {
let trackTotalHits: number | boolean = 10000;
if (query?.track) {
if (query.track === 'true') {
trackTotalHits = true;
} else if (query.track === 'false') {
trackTotalHits = false;
} else {
const parsed = parseInt(query.track, 10);
if (parsed > 0) {
trackTotalHits = parsed;
} else {
throw new Error('failed to parse track param');
}
}
}
return trackTotalHits;
}
function bigint2Milliseconds(input: bigint) {
return parseFloat((parseInt(input.toString()) / 1000000).toFixed(3));
}
const defaultRouteCacheMap = {
get_resource_usage: 3600,
get_creator: 3600 * 24
}
export async function timedQuery(
queryFunction: (fastify: FastifyInstance, request: FastifyRequest) => Promise<any>,
fastify: FastifyInstance, request: FastifyRequest, route: string): Promise<any> {
// get reference time in nanoseconds
const t0 = process.hrtime.bigint();
// check for cached data, return the response hash if caching is enabled
const [cachedResponse, hash] = await getCachedResponse(
fastify,
route,
request.method === 'POST' ? request.body : request.query
);
if (cachedResponse && !request.query["ignoreCache"]) {
// add cached query time
cachedResponse['query_time_ms'] = bigint2Milliseconds(process.hrtime.bigint() - t0);
return cachedResponse;
}
// call query function
const response = await queryFunction(fastify, request);
// save response to cash
if (hash) {
let EX = null;
if (defaultRouteCacheMap[route]) {
EX = defaultRouteCacheMap[route];
}
setCacheByHash(fastify, hash, response, EX);
}
// add normal query time
if (response) {
response['query_time_ms'] = bigint2Milliseconds(process.hrtime.bigint() - t0);
return response;
} else {
return {};
}
}
export function chainApiHandler(fastify: FastifyInstance) {
return async (request: FastifyRequest, reply: FastifyReply) => {
await handleChainApiRedirect(request, reply, fastify);
}
}
export async function handleChainApiRedirect(
request: FastifyRequest,
reply: FastifyReply,
fastify: FastifyInstance
) {
const urlParts = request.url.split("?");
let reqUrl = fastify.chain_api + urlParts[0];
if (urlParts[0] === '/v1/chain/push_transaction' && fastify.push_api && fastify.push_api !== "") {
reqUrl = fastify.push_api + urlParts[0];
}
const opts = {};
if (request.method === 'POST') {
if (request.body) {
if (typeof request.body === 'string') {
opts['body'] = request.body;
} else if (typeof request.body === 'object') {
opts['body'] = JSON.stringify(request.body);
}
} else {
opts['body'] = "";
}
} else if (request.method === 'GET') {
opts['json'] = request.query;
}
try {
const apiResponse = await got.post(reqUrl, opts);
reply.headers({"Content-Type": "application/json"});
if (request.method === 'HEAD') {
reply.headers({"Content-Length": apiResponse.body.length});
reply.send("");
} else {
reply.send(apiResponse.body);
}
} catch (error) {
if (error.response) {
reply.status(error.response.statusCode).send(error.response.body);
} else {
console.log(error);
reply.status(500).send();
}
if (fastify.manager.config.api.chain_api_error_log) {
try {
if (error.response) {
const error_msg = JSON.parse(error.response.body).error.details[0].message;
console.log(`endpoint: ${request.raw.url} | status: ${error.response.statusCode} | error: ${error_msg}`);
} else {
console.log(error);
}
// if (request.req.url === '/v1/chain/push_transaction') {
// const packedTrx = JSON.parse(opts['body']).packed_trx;
// const trxBuffer = Buffer.from(packedTrx, 'hex');
// const trxData = await fastify.eosjs.api.deserializeTransactionWithActions(trxBuffer);
// console.log(trxData);
// }
} catch (e) {
console.log(e);
}
}
}
}
export function addChainApiRoute(fastify: FastifyInstance, routeName, description, props?, required?) {
const baseSchema = {
description: description,
summary: description,
tags: ['chain']
};
addApiRoute(
fastify,
['GET', 'HEAD'],
routeName,
chainApiHandler,
{
...baseSchema,
querystring: props ? {
type: 'object',
properties: props,
required: required
} : undefined
}
);
addApiRoute(
fastify,
'POST',
routeName,
chainApiHandler,
{
...baseSchema,
body: props ? {
type: ['object', 'string'],
properties: props,
required: required
} : undefined
}
);
}
export function addSharedSchemas(fastify: FastifyInstance) {
fastify.addSchema({
$id: "WholeNumber",
title: "Integer",
description: "Integer or String",
anyOf: [
{
type: "string",
pattern: "^\\d+$"
},
{
type: "integer"
}
],
});
fastify.addSchema({
$id: "Symbol",
type: "string",
description: "A symbol composed of capital letters between 1-7.",
pattern: "^([A-Z]{1,7})$",
title: "Symbol"
});
fastify.addSchema({
$id: "Signature",
type: "string",
description: "String representation of an EOSIO compatible cryptographic signature",
pattern: "^SIG_([RK]1|WA)_[1-9A-HJ-NP-Za-km-z]+$",
title: "Signature"
})
fastify.addSchema({
$id: "AccountName",
description: "String representation of an EOSIO compatible account name",
"anyOf": [
{
"type": "string",
"description": "String representation of privileged EOSIO name type",
"pattern": "^(eosio[\\.][a-z1-5]{1,6})([a-j]{1})?$",
"title": "NamePrivileged"
},
{
"type": "string",
"description": "String representation of basic EOSIO name type, must be 12 characters and contain only a-z and 0-5",
"pattern": "^([a-z]{1}[a-z1-5]{11})([a-j]{1})?$",
"title": "NameBasic"
},
{
"type": "string",
"description": "String representation of EOSIO bid name type, 1-12 characters and only a-z and 0-5 are allowed",
"pattern": "^([a-z1-5]{1,12})([a-j]{1})?$",
"title": "NameBid"
},
{
"type": "string",
"description": "String representation of EOSIO name type",
"pattern": "^([a-z1-5]{1}[a-z1-5\\.]{0,10}[a-z1-5]{1})([a-j]{1})?$",
"title": "NameCatchAll"
}
],
"title": "Name"
});
fastify.addSchema({
$id: "Expiration",
"description": "Time that transaction must be confirmed by.",
"type": "string",
"pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}$",
"title": "DateTime"
});
fastify.addSchema({
$id: "BlockExtensions",
"type": "array",
"items": {
"anyOf": [
{"type": "integer"},
{"type": "string"}
]
},
"title": "Extension"
})
fastify.addSchema({
$id: "ActionItems",
"type": "object",
"additionalProperties": false,
"minProperties": 5,
"required": [
"account",
"name",
"authorization",
"data",
"hex_data"
],
"properties": {
"account": {$ref: 'AccountName#'},
"name": {$ref: 'AccountName#'},
"authorization": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"minProperties": 2,
"required": [
"actor",
"permission"
],
"properties": {
"actor": {$ref: 'AccountName#'},
"permission": {$ref: 'AccountName#'}
},
"title": "Authority"
}
},
"data": {
"type": "object",
"additionalProperties": true
},
"hex_data": {
"type": "string"
}
},
"title": "Action"
});
}
-23
View File
@@ -1,23 +0,0 @@
import * as Fastify from "fastify";
import {IncomingMessage, Server, ServerResponse} from "http";
// fastify plugins
import * as fastifyElasticsearch from 'fastify-elasticsearch';
import fastifySwagger from 'fastify-swagger';
import fastifyCors from 'fastify-cors';
import fastifyFormbody from 'fastify-formbody';
import fastifyRedis from 'fastify-redis';
import fastifyRateLimit from 'fastify-rate-limit';
// custom plugins
import fastify_eosjs from "./plugins/fastify-eosjs";
export function registerPlugins(server: Fastify.FastifyInstance<Server, IncomingMessage, ServerResponse>, params: any) {
server.register(fastifyElasticsearch, params.fastify_elasticsearch);
server.register(fastifySwagger, params.fastify_swagger);
server.register(fastifyCors);
server.register(fastifyFormbody);
server.register(fastifyRedis, params.fastify_redis);
server.register(fastifyRateLimit, params.fastify_rate_limit);
server.register(fastify_eosjs, params.fastify_eosjs);
}
-19
View File
@@ -1,19 +0,0 @@
import {FastifyInstance, FastifyPluginOptions} from "fastify";
import {Api} from "eosjs/dist";
import fp from "fastify-plugin";
export default fp(async (fastify: FastifyInstance, options: FastifyPluginOptions): Promise<void> => {
const rpc = fastify.manager.nodeosJsonRPC;
const chain_data = await rpc.get_info();
const api = new Api({
rpc,
signatureProvider: null,
chainId: chain_data.chain_id,
textDecoder: new TextDecoder(),
textEncoder: new TextEncoder(),
});
fastify.decorate('eosjs', {api, rpc});
}, {
fastify: '>=2.0.0',
name: 'fastify-eosjs'
});
-80
View File
@@ -1,80 +0,0 @@
import {join} from "path";
import {FastifyError, FastifyInstance, FastifyReply, FastifyRequest} from "fastify";
import {createReadStream} from "fs";
import {addSharedSchemas, handleChainApiRedirect} from "./helpers/functions";
import autoLoad from 'fastify-autoload';
function addRedirect(server: FastifyInstance, url: string, redirectTo: string) {
server.route({
url,
method: 'GET',
schema: {
hide: true
},
handler: async (request: FastifyRequest, reply: FastifyReply) => {
reply.redirect(redirectTo);
}
});
}
function addRoute(server: FastifyInstance, handlersPath: string, prefix: string) {
server.register(autoLoad, {
dir: join(__dirname, 'routes', handlersPath),
ignorePattern: /.*(handler|schema).js/,
dirNameRoutePrefix: false,
options: {prefix}
});
}
export function registerRoutes(server: FastifyInstance) {
// Register fastify api routes
addRoute(server, 'v2', '/v2');
addRoute(server, 'v2-history', '/v2/history');
addRoute(server, 'v2-state', '/v2/state');
addRoute(server, 'v2-stats', '/v2/stats');
// legacy routes
addRoute(server, 'v1-history', '/v1/history');
addRoute(server, 'v1-trace', '/v1/trace_api');
addSharedSchemas(server);
// chain api redirects
addRoute(server, 'v1-chain', '/v1/chain');
server.route({
url: '/v1/chain/*',
method: ["GET", "POST"],
schema: {
summary: "Wildcard chain api handler",
tags: ["chain"]
},
handler: async (request: FastifyRequest, reply: FastifyReply) => {
await handleChainApiRedirect(request, reply, server);
}
});
server.addHook('onError', (request: FastifyRequest, reply: FastifyReply, error: FastifyError, done) => {
console.log(`[${request.headers['x-real-ip']}] ${request.method} ${request.url} failed with error: ${error.message}`);
done();
});
if (server.manager.config.features.streaming) {
// steam client lib
server.get(
'/stream-client.js',
{schema: {tags: ['internal']}},
(request: FastifyRequest, reply: FastifyReply) => {
const stream = createReadStream('./hyperion-stream-client.js');
reply.type('application/javascript').send(stream);
});
}
// Redirect routes to documentation
addRedirect(server, '/v2', '/v2/docs');
addRedirect(server, '/v2/history', '/v2/docs/index.html#/history');
addRedirect(server, '/v2/state', '/v2/docs/index.html#/state');
addRedirect(server, '/v1/chain', '/v2/docs/index.html#/chain');
addRedirect(server, '/explorer', '/v2/explore');
addRedirect(server, '/explore', '/v2/explore');
}
@@ -1,39 +0,0 @@
import {FastifyInstance} from "fastify";
import {addApiRoute, chainApiHandler, getRouteName} from "../../../helpers/functions";
export default function (fastify: FastifyInstance, opts: any, next) {
addApiRoute(
fastify,
'POST',
getRouteName(__filename),
chainApiHandler,
{
description: "This method expects a transaction in JSON format and will attempt to apply it to the blockchain.",
summary: "This method expects a transaction in JSON format and will attempt to apply it to the blockchain.",
tags: ['chain'],
body: {
type: ['object', 'string'],
properties: {
signatures: {
"type": "array",
"description": "array of signatures required to authorize transaction",
"items": {$ref: 'Signature#'}
},
compression: {
"type": "boolean",
"description": "Compression used, usually false"
},
packed_context_free_data: {
"type": "string",
"description": "json to hex"
},
packed_trx: {
"type": "string",
"description": "Transaction object json to hex"
}
}
}
}
);
next();
}
@@ -1,55 +0,0 @@
import {FastifyInstance} from "fastify";
import {addApiRoute, chainApiHandler, getRouteName} from "../../../helpers/functions";
export default function (fastify: FastifyInstance, opts: any, next) {
addApiRoute(
fastify,
'POST',
getRouteName(__filename),
chainApiHandler,
{
description: "This method expects a transaction in JSON format and will attempt to apply it to the blockchain.",
summary: "This method expects a transaction in JSON format and will attempt to apply it to the blockchain.",
tags: ['chain'],
body: {
type: ['array', 'object', 'string'],
items: {
type: ['object', 'string'],
additionalProperties: false,
minProperties: 8,
required: [
"expiration",
"ref_block_num",
"ref_block_prefix",
"max_net_usage_words",
"max_cpu_usage_ms",
"delay_sec",
"context_free_actions",
"actions"
],
properties: {
"expiration": {$ref: 'Expiration#'},
"ref_block_num": {"type": "integer"},
"ref_block_prefix": {"type": "integer"},
"max_net_usage_words": {$ref: 'WholeNumber#'},
"max_cpu_usage_ms": {$ref: 'WholeNumber#'},
"delay_sec": {"type": "integer"},
"context_free_actions": {
"type": "array",
"items": {$ref: 'ActionItems#'}
},
"actions": {
"type": "array",
"items": {$ref: 'ActionItems#'}
},
"transaction_extensions": {
"type": "array",
"items": {$ref: 'BlockExtensions#'}
}
},
}
}
}
);
next();
}
@@ -1,39 +0,0 @@
import {FastifyInstance} from "fastify";
import {addApiRoute, chainApiHandler, getRouteName} from "../../../helpers/functions";
export default function (fastify: FastifyInstance, opts: any, next) {
addApiRoute(
fastify,
'POST',
getRouteName(__filename),
chainApiHandler,
{
description: "This method expects a transaction in JSON format and will attempt to apply it to the blockchain.",
summary: "This method expects a transaction in JSON format and will attempt to apply it to the blockchain.",
tags: ['chain'],
body: {
type: ['object', 'string'],
properties: {
signatures: {
"type": "array",
"description": "array of signatures required to authorize transaction",
"items": {$ref: 'Signature#'}
},
compression: {
"type": "boolean",
"description": "Compression used, usually false"
},
packed_context_free_data: {
"type": "string",
"description": "json to hex"
},
packed_trx: {
"type": "string",
"description": "Transaction object json to hex"
}
}
}
}
);
next();
}
@@ -1,72 +0,0 @@
import {FastifyInstance, FastifyReply, FastifyRequest} from "fastify";
import {timedQuery} from "../../../helpers/functions";
import {ApiResponse} from "@elastic/elasticsearch";
async function getControlledAccounts(fastify: FastifyInstance, request: FastifyRequest) {
if (typeof request.body === 'string') {
request.body = JSON.parse(request.body)
}
let controlling_account = request.body["controlling_account"];
const results: ApiResponse = await fastify.elastic.search({
index: fastify.manager.chain + '-action-*',
size: 100,
body: {
query: {
bool: {
should: [
{
term: {"@updateauth.auth.accounts.permission.actor": controlling_account}
},
{
bool: {
must: [
{term: {"act.account": "eosio"}},
{term: {"act.name": "newaccount"}},
{term: {"act.authorization.actor": controlling_account}}
]
}
}
],
minimum_should_match: 1
}
},
sort: [
{"global_sequence": {"order": "desc"}}
]
}
});
const response = {
controlled_accounts: []
};
const hits = results.body.hits.hits;
if (hits.length > 0) {
response.controlled_accounts = hits.map((v) => {
if (v._source.act.name === 'newaccount') {
if (v._source['@newaccount'].newact) {
return v._source['@newaccount'].newact;
} else if (v._source.act.data.newact) {
return v._source.act.data.newact;
} else {
return null;
}
} else if (v._source.act.name === 'updateauth') {
return v._source.act.data.account;
} else {
return null;
}
});
}
if (response.controlled_accounts.length > 0) {
response.controlled_accounts = [...(new Set(response.controlled_accounts))];
}
return response;
}
export function getControlledAccountsHandler(fastify: FastifyInstance, route: string) {
return async (request: FastifyRequest, reply: FastifyReply) => {
reply.send(await timedQuery(getControlledAccounts, fastify, request, route));
}
}
@@ -1,195 +0,0 @@
import {FastifyInstance, FastifyReply, FastifyRequest} from "fastify";
import {mergeActionMeta, timedQuery} from "../../../helpers/functions";
import {createHash} from "crypto";
import * as flatstr from 'flatstr';
async function getTransaction(fastify: FastifyInstance, request: FastifyRequest) {
if (typeof request.body === 'string') {
request.body = JSON.parse(request.body)
}
const body: any = request.body;
const pResults = await Promise.all([fastify.eosjs.rpc.get_info(), fastify.elastic['search']({
"index": fastify.manager.chain + '-action-*',
"body": {
"query": {
"bool": {
must: [
{term: {"trx_id": body.id.toLowerCase()}}
]
}
},
"sort": {
"global_sequence": "asc"
}
}
})]);
const results = pResults[1];
const response: any = {
"id": body.id,
"trx": {
"receipt": {
"status": "executed",
"cpu_usage_us": 0,
"net_usage_words": 0,
"trx": [1, {
"signatures": "",
"compression": "none",
"packed_context_free_data": "",
"packed_trx": ""
}]
},
"trx": {}
},
"block_num": 0,
"block_time": "",
"last_irreversible_block": pResults[0].last_irreversible_block_num,
"traces": []
};
const hits = results['body']['hits']['hits'];
if (hits.length > 0) {
const actions = hits;
response.trx.trx = {
"expiration": "",
"ref_block_num": 0,
"ref_block_prefix": 0,
"max_net_usage_words": 0,
"max_cpu_usage_ms": 0,
"delay_sec": 0,
"context_free_actions": [],
"actions": [],
"transaction_extensions": [],
"signatures": [],
"context_free_data": []
};
let traces = {};
let seqNum = 0;
for (let action of actions) {
action = action._source;
mergeActionMeta(action);
action.act['hex_data'] = Buffer.from(flatstr(JSON.stringify(action.act.data))).toString('hex');
if (action.parent === 0) {
response.trx.trx.actions.push(action.act);
}
response.block_num = action.block_num;
response.block_time = action['@timestamp'];
seqNum += 1;
let trace = {
receipt: {
receiver: action.act.account,
global_sequence: String(action.global_sequence),
auth_sequence: [
action.act.authorization[0].actor,
seqNum
],
act_digest: '',
recv_sequence: seqNum,
code_sequence: 1,
abi_sequence: 1
},
act: action.act,
account_ram_deltas: action.account_ram_deltas || [],
context_free: false,
block_num: action.block_num,
block_time: action['@timestamp'],
console: "",
elapsed: 0,
except: null,
inline_traces: [],
producer_block_id: "",
trx_id: body.id,
notified: action.notified
};
let hash = createHash('sha256');
hash.update(JSON.stringify(action.act));
trace.receipt.act_digest = hash.digest('hex');
traces[action.global_sequence] = trace;
}
actions.forEach(action => {
action = action._source;
for (let i = 0; i < traces[action.global_sequence].notified.length; i++) {
if (traces[action.global_sequence].notified[i] === action.act.account) {
traces[action.global_sequence].notified.splice(i, 1);
break;
}
}
if (action.parent !== 0 && action.parent) {
if (traces[action.parent]) {
for (let i = 0; i < traces[action.parent].notified.length; i++) {
if (traces[action.parent].notified[i] === action.act.account) {
traces[action.parent].notified.splice(i, 1);
break;
}
}
traces[action.parent].inline_traces.push(traces[action.global_sequence]);
}
}
});
actions.forEach(action => {
action = action._source;
response.traces.push(traces[action.global_sequence]);
if (traces[action.global_sequence] && traces[action.global_sequence].notified) {
traces[action.global_sequence].notified.forEach((note, index) => {
seqNum += 1;
let trace = {
receipt: {
receiver: note,
global_sequence: String(action.global_sequence + index + 1),
auth_sequence: [
action.act.authorization[0].actor,
seqNum
],
act_digest: traces[action.global_sequence].receipt.act_digest,
recv_sequence: seqNum,
code_sequence: 1,
abi_sequence: 1
},
account_ram_deltas: action.account_ram_deltas || [],
act: action.act,
block_num: action.block_num,
block_time: action['@timestamp'],
console: "",
context_free: false,
elapsed: 0,
except: null,
inline_traces: [],
producer_block_id: "",
trx_id: body.id,
};
traces[action.global_sequence].inline_traces.unshift(trace);
response.traces.push(trace);
});
delete traces[action.global_sequence].notified;
}
});
} else {
const errmsg = "Transaction " + body.id.toLowerCase() + " not found in history and no block hint was given";
return {
code: 500,
message: "Internal Service Error",
error: {
code: 3040011,
name: "tx_not_found",
what: "The transaction can not be found",
details: [
{
message: errmsg,
file: "",
line_number: 1,
method: "get_transaction"
}
]
}
}
}
return response;
}
export function getTransactionHandler(fastify: FastifyInstance, route: string) {
return async (request: FastifyRequest, reply: FastifyReply) => {
reply.send(await timedQuery(getTransaction, fastify, request, route));
}
}
@@ -1,17 +0,0 @@
import {FastifyInstance} from "fastify";
import {addApiRoute, getRouteName} from "../../../helpers/functions";
import {getTransactionHandler} from "./get_transaction";
export default function (fastify: FastifyInstance, opts: any, next) {
addApiRoute(fastify, 'POST', getRouteName(__filename), getTransactionHandler, {
description: 'get all actions belonging to the same transaction',
summary: 'get transaction by id',
tags: ['history'],
body: {
type: ['object', 'string'],
properties: {id: {description: 'transaction id', type: 'string'}},
required: ["id"]
}
});
next();
}
@@ -1,51 +0,0 @@
import {FastifyInstance, FastifyReply, FastifyRequest} from "fastify";
import {timedQuery} from "../../../helpers/functions";
async function getAbiSnapshot(fastify: FastifyInstance, request: FastifyRequest) {
const response = {
block_num: null
};
const query: any = request.query;
const code = query.contract;
const block = query.block;
const should_fetch = query.fetch;
const mustArray = [];
mustArray.push({"term": {"account": code}});
if (block) {
mustArray.push({"range": {"block": {"lte": parseInt(block)}}});
}
const results = await fastify.elastic.search({
index: fastify.manager.chain + '-abi',
size: 1,
body: {
query: {bool: {must: mustArray}},
sort: [{block: {order: "desc"}}]
}
});
if (results['body']['hits']['hits'].length > 0) {
if (should_fetch) {
response['abi'] = JSON.parse(results['body']['hits']['hits'][0]['_source']['abi']);
} else {
response['present'] = true;
}
response.block_num = results['body']['hits']['hits'][0]['_source']['block'];
} else {
response['present'] = false;
response['error'] = 'abi not found for ' + code + ' until block ' + block;
}
return response;
}
export function getAbiSnapshotHandler(fastify: FastifyInstance, route: string) {
return async (request: FastifyRequest, reply: FastifyReply) => {
reply.send(await timedQuery(getAbiSnapshot, fastify, request, route));
}
}
@@ -1,215 +0,0 @@
import {primaryTerms, terms} from "./definitions";
export function addSortedBy(query, queryBody, sort_direction) {
if (query['sortedBy']) {
const opts = query['sortedBy'].split(":");
const sortedByObj = {};
sortedByObj[opts[0]] = opts[1];
queryBody['sort'] = sortedByObj;
} else {
queryBody['sort'] = {
"global_sequence": sort_direction
};
}
}
export function processMultiVars(queryStruct, parts, field) {
const must = [];
const mustNot = [];
parts.forEach(part => {
if (part.startsWith("!")) {
mustNot.push(part.replace("!", ""));
} else {
must.push(part);
}
});
if (must.length > 1) {
queryStruct.bool.must.push({
bool: {
should: must.map(elem => {
const _q = {};
_q[field] = elem;
return {term: _q}
})
}
});
} else if (must.length === 1) {
const mustQuery = {};
mustQuery[field] = must[0];
queryStruct.bool.must.push({term: mustQuery});
}
if (mustNot.length > 1) {
queryStruct.bool.must_not.push({
bool: {
should: mustNot.map(elem => {
const _q = {};
_q[field] = elem;
return {term: _q}
})
}
});
} else if (mustNot.length === 1) {
const mustNotQuery = {};
mustNotQuery[field] = mustNot[0].replace("!", "");
queryStruct.bool.must_not.push({term: mustNotQuery});
}
}
function addRangeQuery(queryStruct, prop, pkey, query) {
const _termQuery = {};
const parts = query[prop].split("-");
_termQuery[pkey] = {
"gte": parts[0],
"lte": parts[1]
};
queryStruct.bool.must.push({range: _termQuery});
}
export function applyTimeFilter(query, queryStruct) {
if (query['after'] || query['before']) {
let _lte = "now";
let _gte = "0";
if (query['before']) {
_lte = query['before'];
if (!_lte.endsWith("Z")) {
_lte += "Z";
}
}
if (query['after']) {
_gte = query['after'];
if (!_gte.endsWith("Z")) {
_gte += "Z";
}
}
if (!queryStruct.bool['filter']) {
queryStruct.bool['filter'] = [];
}
queryStruct.bool['filter'].push({
range: {
"@timestamp": {
"gte": _gte,
"lte": _lte
}
}
});
}
}
export function applyGenericFilters(query, queryStruct, allowedExtraParams: Set<string>) {
for (const prop in query) {
if (Object.prototype.hasOwnProperty.call(query, prop)) {
const pair = prop.split(".");
if (pair.length > 1 || primaryTerms.includes(pair[0])) {
let pkey;
if (pair.length > 1 && allowedExtraParams) {
pkey = allowedExtraParams.has(pair[0]) ? "@" + prop : prop;
} else {
pkey = prop;
}
if (query[prop].indexOf("-") !== -1) {
addRangeQuery(queryStruct, prop, pkey, query);
} else {
const _termQuery = {};
const parts = query[prop].split(",");
if (parts.length > 1) {
processMultiVars(queryStruct, parts, prop);
} else if (parts.length === 1) {
const andParts = parts[0].split(" ");
if (andParts.length > 1) {
andParts.forEach(value => {
const _q = {};
console.log(value);
_q[pkey] = value;
queryStruct.bool.must.push({term: _q});
});
} else {
if (parts[0].startsWith("!")) {
_termQuery[pkey] = parts[0].replace("!", "");
queryStruct.bool.must_not.push({term: _termQuery});
} else {
_termQuery[pkey] = parts[0];
queryStruct.bool.must.push({term: _termQuery});
}
}
}
}
}
}
}
}
export function makeShouldArray(query) {
const should_array = [];
for (const entry of terms) {
const tObj = {term: {}};
tObj.term[entry] = query.account;
should_array.push(tObj);
}
return should_array;
}
export function applyCodeActionFilters(query, queryStruct) {
let filterObj = [];
if (query.filter) {
for (const filter of query.filter.split(',')) {
if (filter !== '*:*') {
const _arr = [];
const parts = filter.split(':');
if (parts.length === 2) {
const [code, method] = parts;
if (code && code !== "*") {
_arr.push({'term': {'act.account': code}});
}
if (method && method !== "*") {
_arr.push({'term': {'act.name': method}});
}
}
if (_arr.length > 0) {
filterObj.push({bool: {must: _arr}});
}
}
}
if (filterObj.length > 0) {
queryStruct.bool['should'] = filterObj;
queryStruct.bool['minimum_should_match'] = 1;
}
}
}
export function getSkipLimit(query, max?: number) {
let skip, limit;
skip = parseInt(query.skip, 10);
if (skip < 0) {
throw new Error('invalid skip parameter');
}
limit = parseInt(query.limit, 10);
if (limit < 1) {
throw new Error('invalid limit parameter');
} else if (limit > max) {
throw new Error(`limit too big, maximum: ${max}`);
}
return {skip, limit};
}
export function getSortDir(query) {
let sort_direction = 'desc';
if (query.sort) {
if (query.sort === 'asc' || query.sort === '1') {
sort_direction = 'asc';
} else if (query.sort === 'desc' || query.sort === '-1') {
sort_direction = 'desc'
} else {
throw new Error('invalid sort direction');
}
}
return sort_direction;
}
export function applyAccountFilters(query, queryStruct) {
if (query.account) {
queryStruct.bool.must.push({"bool": {should: makeShouldArray(query)}});
}
}
@@ -1,118 +0,0 @@
import {FastifyInstance, FastifyReply, FastifyRequest} from "fastify";
import {getTrackTotalHits, mergeActionMeta, timedQuery} from "../../../helpers/functions";
import {
addSortedBy,
applyAccountFilters,
applyCodeActionFilters,
applyGenericFilters,
applyTimeFilter,
getSkipLimit,
getSortDir
} from "./functions";
async function getActions(fastify: FastifyInstance, request: FastifyRequest) {
const query: any = request.query;
const maxActions = fastify.manager.config.api.limits.get_actions;
const queryStruct = {
"bool": {
must: [],
must_not: [],
boost: 1.0
}
};
const {skip, limit} = getSkipLimit(query, maxActions);
const sort_direction = getSortDir(query);
applyAccountFilters(query, queryStruct);
applyGenericFilters(query, queryStruct, fastify.allowedActionQueryParamSet);
applyTimeFilter(query, queryStruct);
applyCodeActionFilters(query, queryStruct);
// allow precise counting of total hits
const trackTotalHits = getTrackTotalHits(query);
// Prepare query body
const query_body = {
"track_total_hits": trackTotalHits,
"query": queryStruct
};
// Include sorting
addSortedBy(query, query_body, sort_direction);
// Perform search
let indexPattern = fastify.manager.chain + '-action-*';
if (query.hot_only) {
indexPattern = fastify.manager.chain + '-action';
}
const esResults = await fastify.elastic.search({
"index": indexPattern,
"from": skip || 0,
"size": (limit > maxActions ? maxActions : limit) || 10,
"body": query_body
});
const results = esResults['body']['hits'];
const response: any = {
cached: false,
lib: 0,
total: results['total']
};
if (query.hot_only) {
response.hot_only = true;
}
if (query.checkLib) {
response.lib = (await fastify.eosjs.rpc.get_info()).last_irreversible_block_num;
}
if (query.simple) {
response['simple_actions'] = [];
} else {
response['actions'] = [];
}
if (results['hits'].length > 0) {
const actions = results['hits'];
for (let action of actions) {
action = action._source;
mergeActionMeta(action);
if (query.noBinary === true) {
for (const key in action['act']['data']) {
if (action['act']['data'].hasOwnProperty(key)) {
if (typeof action['act']['data'][key] === 'string' && action['act']['data'][key].length > 256) {
action['act']['data'][key] = action['act']['data'][key].slice(0, 32) + "...";
}
}
}
}
if (query.simple) {
response.simple_actions.push({
block: action['block_num'],
irreversible: response.lib !== 0 ? action['block_num'] < response.lib : undefined,
timestamp: action['@timestamp'],
transaction_id: action['trx_id'],
actors: action['act']['authorization'].map(a => `${a.actor}@${a.permission}`).join(","),
notified: action['notified'].join(','),
contract: action['act']['account'],
action: action['act']['name'],
data: action['act']['data']
});
} else {
response.actions.push(action);
}
}
}
return response;
}
export function getActionsHandler(fastify: FastifyInstance, route: string) {
return async (request: FastifyRequest, reply: FastifyReply) => {
reply.send(await timedQuery(getActions, fastify, request, route));
}
}
@@ -1,58 +0,0 @@
import {FastifyInstance, FastifyReply, FastifyRequest} from "fastify";
import {timedQuery} from "../../../helpers/functions";
import {getSkipLimit} from "../get_actions/functions";
async function getCreatedAccounts(fastify: FastifyInstance, request: FastifyRequest) {
const query: any = request.query;
const {skip, limit} = getSkipLimit(query);
const maxActions = fastify.manager.config.api.limits.get_created_accounts;
const results = await fastify.elastic.search({
"index": fastify.manager.chain + '-action-*',
"from": skip || 0,
"size": (limit > maxActions ? maxActions : limit) || 100,
"body": {
"query": {
"bool": {
must: [
{term: {"act.authorization.actor": query.account.toLowerCase()}},
{term: {"act.name": "newaccount"}},
{term: {"act.account": "eosio"}}
]
}
},
sort: {
"global_sequence": "desc"
}
}
});
const response = {accounts: []};
if (results['body']['hits']['hits'].length > 0) {
const actions = results['body']['hits']['hits'];
for (let action of actions) {
action = action._source;
const _tmp = {};
if (action['act']['data']['newact']) {
_tmp['name'] = action['act']['data']['newact'];
} else if (action['@newaccount']['newact']) {
_tmp['name'] = action['@newaccount']['newact'];
} else {
console.log(action);
}
_tmp['trx_id'] = action['trx_id'];
_tmp['timestamp'] = action['@timestamp'];
response.accounts.push(_tmp);
}
}
return response;
}
export function getCreatedAccountsHandler(fastify: FastifyInstance, route: string) {
return async (request: FastifyRequest, reply: FastifyReply) => {
reply.send(await timedQuery(getCreatedAccounts, fastify, request, route));
}
}
@@ -1,100 +0,0 @@
import {FastifyInstance, FastifyReply, FastifyRequest} from "fastify";
import {timedQuery} from "../../../helpers/functions";
async function getCreator(fastify: FastifyInstance, request: FastifyRequest) {
const query: any = request.query;
const response = {
account: query.account,
creator: '',
timestamp: '',
block_num: 0,
trx_id: '',
};
if (query.account === fastify.manager.config.settings.eosio_alias) {
const genesisBlock = await fastify.eosjs.rpc.get_block(1);
if (genesisBlock) {
response.creator = '__self__';
response.timestamp = genesisBlock.timestamp;
response.block_num = 1;
response.trx_id = "";
return response;
} else {
throw new Error("genesis block not found");
}
}
const results = await fastify.elastic.search({
"index": fastify.manager.chain + '-action-*',
"body": {
size: 1,
query: {
bool: {
must: [{term: {"@newaccount.newact": query.account}}]
}
}
}
});
if (results['body']['hits']['hits'].length === 1) {
const result = results['body']['hits']['hits'][0]._source;
response.trx_id = result.trx_id;
response.block_num = result.block_num;
response.creator = result.act.data.creator;
response.timestamp = result['@timestamp'];
return response;
} else {
let accountInfo;
try {
accountInfo = await fastify.eosjs.rpc.get_account(query.account);
} catch (e) {
throw new Error("account not found");
}
if (accountInfo) {
try {
response.timestamp = accountInfo.created;
const blockHeader = await fastify.elastic.search({
"index": fastify.manager.chain + '-block-*',
"body": {
size: 1,
query: {
bool: {
must: [{term: {"@timestamp": response.timestamp}}]
}
}
}
});
const blockId = blockHeader['body']['hits']['hits'][0]._source.block_id;
const blockData = await fastify.eosjs.rpc.get_block(blockId);
response.block_num = blockData.block_num;
for (const transaction of blockData["transactions"]) {
if (typeof transaction.trx !== 'string') {
const actions = transaction.trx.transaction.actions;
for (const act of actions) {
if (act.name === 'newaccount') {
if (act.data.name === query.account) {
response.creator = act.data.creator;
response.trx_id = transaction.id;
return response;
}
}
}
}
}
return response;
} catch (e) {
throw new Error("account creation not found");
}
} else {
throw new Error("account creation not found");
}
}
}
export function getCreatorHandler(fastify: FastifyInstance, route: string) {
return async (request: FastifyRequest, reply: FastifyReply) => {
reply.send(await timedQuery(getCreator, fastify, request, route));
}
}
@@ -1,91 +0,0 @@
import {FastifyInstance, FastifyReply, FastifyRequest} from "fastify";
import {mergeDeltaMeta, timedQuery} from "../../../helpers/functions";
import {applyTimeFilter} from "../get_actions/functions";
async function getDeltas(fastify: FastifyInstance, request: FastifyRequest) {
let skip, limit;
let sort_direction = 'desc';
const mustArray = [];
const query: any = request.query;
for (const param in query) {
if (Object.prototype.hasOwnProperty.call(query, param)) {
const value = query[param];
switch (param) {
case 'limit': {
limit = parseInt(value, 10);
if (limit < 1) {
return 'invalid limit parameter';
}
break;
}
case 'skip': {
skip = parseInt(value, 10);
if (skip < 0) {
return 'invalid skip parameter';
}
break;
}
case 'sort': {
if (value === 'asc' || value === '1') {
sort_direction = 'asc';
} else if (value === 'desc' || value === '-1') {
sort_direction = 'desc'
} else {
return 'invalid sort direction';
}
break;
}
case 'before': {
break;
}
case 'after': {
break;
}
default: {
const values = query[param].split(",");
if (values.length > 1) {
const terms = {};
terms[param] = values;
mustArray.push({terms: terms});
} else {
const term = {};
term[param] = values[0];
mustArray.push({term: term});
}
break;
}
}
}
}
const maxDeltas = fastify.manager.config.api.limits.get_deltas ?? 1000;
const queryStruct = {bool: {must: mustArray}};
applyTimeFilter(query, queryStruct);
const results = await fastify.elastic.search({
"index": fastify.manager.chain + '-delta-*',
"from": skip || 0,
"size": (limit > maxDeltas ? maxDeltas : limit) || 10,
"body": {
query: queryStruct,
sort: {
"block_num": sort_direction
}
}
});
const deltas = results['body']['hits']['hits'].map((d) => {
return mergeDeltaMeta(d._source);
});
return {
query_time: null,
total: results['body']['hits']['total'],
deltas
};
}
export function getDeltasHandler(fastify: FastifyInstance, route: string) {
return async (request: FastifyRequest, reply: FastifyReply) => {
reply.send(await timedQuery(getDeltas, fastify, request, route));
}
}
-70
View File
@@ -1,70 +0,0 @@
import {FastifyInstance, FastifySchema} from "fastify";
import {getDeltasHandler} from "./get_deltas";
import {addApiRoute, extendQueryStringSchema, extendResponseSchema, getRouteName} from "../../../helpers/functions";
export default function (fastify: FastifyInstance, opts: any, next) {
const schema: FastifySchema = {
description: 'get state deltas',
summary: 'get state deltas',
tags: ['history'],
querystring: extendQueryStringSchema({
"code": {
description: 'contract account',
type: 'string'
},
"scope": {
description: 'table scope',
type: 'string'
},
"table": {
description: 'table name',
type: 'string'
},
"payer": {
description: 'payer account',
type: 'string'
},
"after": {
description: 'filter after specified date (ISO8601)',
type: 'string'
},
"before": {
description: 'filter before specified date (ISO8601)',
type: 'string'
}
}),
response: extendResponseSchema({
"deltas": {
type: "array",
items: {
type: 'object',
properties: {
"timestamp": {type: 'string'},
"code": {type: 'string'},
"scope": {type: 'string'},
"table": {type: 'string'},
"primary_key": {type: 'string'},
"payer": {type: 'string'},
"present": {type: 'number'},
"block_num": {type: 'number'},
"block_id": {type: 'string'},
"data": {
type: 'object',
additionalProperties: true
}
},
additionalProperties: true
}
}
})
};
addApiRoute(
fastify,
'GET',
getRouteName(__filename),
getDeltasHandler,
schema
);
next();
}
@@ -1,73 +0,0 @@
import {FastifyInstance, FastifyReply, FastifyRequest} from "fastify";
import {timedQuery} from "../../../helpers/functions";
import {createHash} from "crypto";
import {base58ToBinary, binaryToBase58} from "eosjs/dist/eosjs-numeric";
import {Search} from "@elastic/elasticsearch/api/requestParams";
function convertToLegacyKey(block_signing_key: string) {
if (block_signing_key.startsWith("PUB_K1_")) {
const buf = base58ToBinary(37, block_signing_key.substr(7));
const data = buf.slice(0, buf.length - 4);
const merged = Buffer.concat([
data,
createHash('ripemd160')
.update(data)
.digest()
.slice(0, 4)
]);
return "EOS" + binaryToBase58(merged);
} else {
return block_signing_key;
}
}
async function getSchedule(fastify: FastifyInstance, request: FastifyRequest) {
const query: any = request.query;
const response: any = {
producers: []
};
const searchParams: Search<any> = {
track_total_hits: true,
index: fastify.manager.chain + "-block-*",
size: 1,
body: {
query: {
bool: {
must: []
}
},
sort: {block_num: "desc"}
}
};
if (query.version) {
searchParams.body.query.bool.must.push({"term": {"new_producers.version": {"value": query.version}}});
} else {
searchParams.body.query.bool.must.push({
"exists": {
"field": "new_producers.version"
}
});
}
const apiResponse = await fastify.elastic.search(searchParams);
const results = apiResponse.body.hits.hits;
if (results) {
response.timestamp = results[0]._source["@timestamp"];
response.block_num = results[0]._source.block_num;
response.version = results[0]._source.new_producers.version;
response.producers = results[0]._source.new_producers.producers.map(prod => {
return {
...prod,
legacy_key: convertToLegacyKey(prod.block_signing_key)
}
});
}
return response;
}
export function getScheduleHandler(fastify: FastifyInstance, route: string) {
return async (request: FastifyRequest, reply: FastifyReply) => {
reply.send(await timedQuery(getSchedule, fastify, request, route));
}
}
@@ -1,88 +0,0 @@
import {FastifyInstance, FastifyReply, FastifyRequest} from "fastify";
import {mergeDeltaMeta, timedQuery} from "../../../helpers/functions";
async function getTableState(fastify: FastifyInstance, request: FastifyRequest) {
const query: any = request.query;
const response = {
...query,
results: [],
next_key: null
};
const mustArray: any[] = [
{"term": {"code": query.code}},
{"term": {"table": query.table}}
];
if (query.block_num) {
mustArray.push({"range": {"block_num": {"lte": query.block_num}}});
}
let after_key = "";
if (query.after_key) {
after_key = query.after_key;
}
const results = await fastify.elastic.search({
index: fastify.manager.chain + '-delta-*',
body: {
"query": {
"bool": {
"must": mustArray
}
},
"size": 0,
"sort": [
{"block_num": "desc"},
{"primary_key": "desc"}
],
"aggs": {
"scope_buckets": {
"composite": {
"size": 25,
"after": {
"scope_pk": after_key
},
"sources": [
{
"scope_pk": {
"terms": {
"script": {
"source": "return doc['scope'].value + '-' + doc['primary_key'].value",
"lang": "painless"
}
}
}
}
]
},
"aggs": {
"last_doc": {
"top_hits": {
"size": 1,
"sort": [{"block_num": "desc"}],
"_source": {
"excludes": ["code"]
}
}
}
}
}
}
}
});
const scope_buckets = results.body.aggregations.scope_buckets;
if (scope_buckets && scope_buckets.buckets.length > 0) {
if (scope_buckets.after_key) {
response.next_key = scope_buckets.after_key.scope_pk;
}
response.results = scope_buckets.buckets.map(bucket => {
const row = mergeDeltaMeta(bucket.last_doc.hits.hits[0]._source);
delete row.table;
return row;
});
}
return response;
}
export function getTableStateHandler(fastify: FastifyInstance, route: string) {
return async (request: FastifyRequest, reply: FastifyReply) => {
reply.send(await timedQuery(getTableState, fastify, request, route));
}
}
@@ -1,130 +0,0 @@
import {FastifyInstance, FastifyReply, FastifyRequest} from "fastify";
import {mergeActionMeta, timedQuery} from "../../../helpers/functions";
async function getTransaction(fastify: FastifyInstance, request: FastifyRequest) {
const query: any = request.query;
const _size = fastify.manager.config.api.limits.get_trx_actions || 100;
let indexPattern = fastify.manager.chain + '-action-*';
if (query.hot_only) {
indexPattern = fastify.manager.chain + '-action';
}
const pResults = await Promise.all([
fastify.eosjs.rpc.get_info(),
fastify.elastic.search({
index: indexPattern,
size: _size,
body: {
query: {
bool: {
must: [
{term: {trx_id: query.id.toLowerCase()}}
]
}
},
sort: {
global_sequence: "asc"
}
}
}),
fastify.elastic.search({
index: fastify.manager.chain + '-gentrx-*',
size: _size,
body: {
query: {
bool: {
must: [
{term: {trx_id: query.id.toLowerCase()}}
]
}
}
}
})
]);
const results = pResults[1];
const genTrxRes = pResults[2];
const response = {
"executed": false,
"hot_only": false,
"trx_id": query.id,
"lib": pResults[0].last_irreversible_block_num,
"actions": [],
"generated": undefined
};
if (query.hot_only) {
response.hot_only = true;
}
const hits = results['body']['hits']['hits'];
if (hits.length > 0) {
// const producers = {};
// for (let hit of hits) {
// if (hit._source.producer) {
// if (producers[hit._source.producer]) {
// producers[hit._source.producer]++;
// } else {
// producers[hit._source.producer] = 1;
// }
// }
// }
// let useBlocknumber;
// if (Object.keys(producers).length > 1) {
// // multiple producers of the same tx id, forked actions are present, attempt to cleanup
// let trueProd = '';
// let highestActCount = 0;
// for (const prod in producers) {
// if (producers.hasOwnProperty(prod)) {
// if(producers[prod] === highestActCount) {
// useBlocknumber = true;
// } else if (producers[prod] > highestActCount) {
// highestActCount = producers[prod];
// trueProd = prod;
// }
// }
// }
// }
let highestBlockNum = 0;
for (let action of hits) {
action = action._source;
if (action.block_num > highestBlockNum) {
highestBlockNum = action.block_num;
}
}
for (let action of hits) {
if (action.block_num === highestBlockNum) {
mergeActionMeta(action);
response.actions.push(action);
}
}
response.executed = true;
}
const hits2 = genTrxRes['body']['hits']['hits'];
if (hits2 && hits2.length > 0) {
if (hits2[0]._source['@timestamp']) {
hits2[0]._source['timestamp'] = hits2[0]._source['@timestamp'];
delete hits2[0]._source['@timestamp'];
}
response.generated = hits2[0]._source;
}
return response;
}
export function getTransactionHandler(fastify: FastifyInstance, route: string) {
return async (request: FastifyRequest, reply: FastifyReply) => {
reply.send(await timedQuery(getTransaction, fastify, request, route));
}
}
@@ -1,139 +0,0 @@
import {FastifyInstance, FastifyReply, FastifyRequest} from "fastify";
import {timedQuery} from "../../../helpers/functions";
import {Numeric} from "eosjs/dist";
import {getSkipLimit} from "../../v2-history/get_actions/functions";
function invalidKey() {
const err: any = new Error();
err.statusCode = 400;
err.message = 'invalid public key';
throw err;
}
async function getKeyAccounts(fastify: FastifyInstance, request: FastifyRequest) {
let publicKey;
if (typeof request.body === 'string' && request.method === 'POST') {
request.body = JSON.parse(request.body);
}
const body: any = request.body;
const query: any = request.query;
const {skip, limit} = getSkipLimit(request.query);
const maxDocs = fastify.manager.config.api.limits.get_key_accounts ?? 1000;
const public_Key = request.method === 'POST' ? body.public_key : query.public_key;
if (public_Key.startsWith("PUB_")) {
publicKey = public_Key;
} else if (public_Key.startsWith("EOS")) {
try {
publicKey = Numeric.convertLegacyPublicKey(public_Key);
} catch (e) {
console.log(e.message);
invalidKey();
}
} else {
invalidKey();
}
const response = {
account_names: []
} as any;
if (request.method === 'GET' && query.details) {
response.permissions = [];
}
try {
const permTableResults = await fastify.elastic.search({
index: fastify.manager.chain + '-perm-*',
size: (limit > maxDocs ? maxDocs : limit) || 100,
from: skip || 0,
body: {
query: {
bool: {
must: [
{
term: {
"auth.keys.key.keyword": publicKey
}
}
],
}
}
}
});
if (permTableResults.body.hits.hits.length > 0) {
for (const perm of permTableResults.body.hits.hits) {
response.account_names.push(perm._source.owner);
if (request.method === 'GET' && query.details) {
response.permissions.push(perm._source);
}
}
}
} catch (e) {
console.log(e);
}
if (response.account_names.length > 0) {
response.account_names = [...(new Set(response.account_names))];
return response;
}
// Fallback to action search
const _body = {
query: {
bool: {
should: [
{term: {"@updateauth.auth.keys.key.keyword": publicKey}},
{term: {"@newaccount.active.keys.key.keyword": publicKey}},
{term: {"@newaccount.owner.keys.key.keyword": publicKey}}
],
minimum_should_match: 1
}
},
sort: [{"global_sequence": {"order": "desc"}}]
};
const results = await fastify.elastic.search({
index: fastify.manager.chain + '-action-*',
size: (limit > maxDocs ? maxDocs : limit) || 100,
from: skip || 0,
body: _body
});
if (results['body']['hits']['hits'].length > 0) {
response.account_names = results['body']['hits']['hits'].map((v) => {
if (v._source.act.name === 'newaccount') {
if (v._source['@newaccount'].newact) {
return v._source['@newaccount'].newact;
} else if (v._source.act.data.newact) {
return v._source.act.data.newact;
} else {
return null;
}
} else if (v._source.act.name === 'updateauth') {
return v._source.act.data.account;
} else {
return null;
}
});
}
if (response.account_names.length > 0) {
response.account_names = [...(new Set(response.account_names))];
}
return response;
}
export function getKeyAccountsHandler(fastify: FastifyInstance, route: string) {
return async (request: FastifyRequest, reply: FastifyReply) => {
reply.send(await timedQuery(getKeyAccounts, fastify, request, route));
}
}
@@ -1,73 +0,0 @@
import {timedQuery} from "../../../helpers/functions";
import {FastifyInstance, FastifyReply, FastifyRequest} from "fastify";
import {getSkipLimit} from "../../v2-history/get_actions/functions";
async function getTokens(fastify: FastifyInstance, request: FastifyRequest) {
const query: any = request.query;
const response = {'account': query.account, 'tokens': []};
const {skip, limit} = getSkipLimit(request.query);
const maxDocs = fastify.manager.config.api.limits.get_tokens ?? 100;
const stateResult = await fastify.elastic.search({
"index": fastify.manager.chain + '-table-accounts-*',
"size": (limit > maxDocs ? maxDocs : limit) || 50,
"from": skip || 0,
"body": {
query: {
bool: {
filter: [{term: {"scope": query.account}}]
}
}
}
});
for (const hit of stateResult.body.hits.hits) {
const data = hit._source;
if (typeof data.present !== "undefined" && data.present === 0) {
continue;
}
let precision;
const key = `${data.code}_${data.symbol}`;
if (!fastify.tokenCache) {
fastify.tokenCache = new Map<string, any>();
}
if (fastify.tokenCache.has(key)) {
precision = fastify.tokenCache.get(key).precision;
} else {
let token_data;
try {
token_data = await fastify.eosjs.rpc.get_currency_balance(data.code, query.account, data.symbol);
if (token_data.length > 0) {
const [amount, symbol] = token_data[0].split(" ");
const amount_arr = amount.split(".");
if (amount_arr.length === 2) {
precision = amount_arr[1].length;
fastify.tokenCache.set(key, {precision});
// console.log('Caching token precision -', key, precision);
}
}
} catch (e) {
console.log(`get_currency_balance error - contract:${data.code} - account:${query.account}`);
}
}
response.tokens.push({
symbol: data.symbol,
precision: precision,
amount: parseFloat(data.amount),
contract: data.code
});
}
return response;
}
export function getTokensHandler(fastify: FastifyInstance, route: string) {
return async (request: FastifyRequest, reply: FastifyReply) => {
reply.send(await timedQuery(getTokens, fastify, request, route));
}
}
@@ -1,63 +0,0 @@
import {FastifyInstance, FastifyReply, FastifyRequest} from "fastify";
import {timedQuery} from "../../../helpers/functions";
import {getSkipLimit} from "../../v2-history/get_actions/functions";
async function getVoters(fastify: FastifyInstance, request: FastifyRequest) {
const query: any = request.query;
const {skip, limit} = getSkipLimit(request.query);
const response = {
voter_count: 0,
'voters': []
};
let queryStruct: any = {
"bool": {
"must": []
}
};
if (query.producer) {
for (const bp of query.producer.split(",")) {
queryStruct.bool.must.push({"term": {"producers": bp}});
}
}
if (query.proxy === 'true') {
queryStruct.bool.must.push({"term": {"is_proxy": true}});
}
if (queryStruct.bool.must.length === 0) {
queryStruct = {
"match_all": {}
};
}
const maxDocs = fastify.manager.config.api.limits.get_voters ?? 100;
const results = await fastify.elastic.search({
"index": fastify.manager.chain + '-table-voters-*',
"from": skip || 0,
"size": (limit > maxDocs ? maxDocs : limit) || 10,
"body": {
"query": queryStruct,
"sort": [{"last_vote_weight": "desc"}]
}
});
const hits = results['body']['hits']['hits'];
for (const hit of hits) {
const voter = hit._source;
response.voters.push({
account: voter.voter,
weight: voter.last_vote_weight,
last_vote: voter.block_num
});
}
response.voter_count = results['body']['hits']['total']['value'];
return response;
}
export function getVotersHandler(fastify: FastifyInstance, route: string) {
return async (request: FastifyRequest, reply: FastifyReply) => {
reply.send(await timedQuery(getVoters, fastify, request, route));
}
}
@@ -1,120 +0,0 @@
import {FastifyInstance, FastifyReply, FastifyRequest} from "fastify";
import {timedQuery} from "../../../helpers/functions";
async function getLastSeq(fastify: FastifyInstance, date: string) {
const req = await fastify.elastic.search({
index: fastify.manager.chain + '-action-*',
body: {
"size": 1,
"query": {
"bool": {
"must": [
{"range": {"@timestamp": {"lt": date}}}
]
}
},
"_source": {
"includes": ["global_sequence"]
},
"sort": [{"global_sequence": "desc"}]
}
});
return req.body.hits.hits[0]._source.global_sequence;
}
async function getTxCount(fastify: FastifyInstance, dateFrom: string, dateTo: string) {
const req = await fastify.elastic.count({
index: fastify.manager.chain + '-action-*',
body: {
"query": {
"bool": {
"must": [
{"term": {"creator_action_ordinal": 0}},
{"range": {"@timestamp": {"gt": dateFrom, "lt": dateTo}}}
]
}
}
}
});
return req.body.count;
}
async function getUniqueActors(fastify: FastifyInstance, dateFrom: string, dateTo: string) {
const req = await fastify.elastic.search({
index: fastify.manager.chain + '-action-*',
size: 0,
body: {
"aggs": {
"unique_actors": {
"cardinality": {
"field": "act.authorization.actor"
}
}
},
"query": {
"bool": {
"filter": [{"range": {"@timestamp": {"gt": dateFrom, "lt": dateTo}}}]
}
}
}
});
return req.body.aggregations.unique_actors.value;
}
async function getActionUsage(fastify: FastifyInstance, request: FastifyRequest) {
const query: any = request.query;
let now = new Date();
let expiration = 86400;
if (query.end_date) {
now = new Date(query.end_date);
}
now.setMinutes(0, 0, 0);
let period;
if (query.period === '1h') {
period = 3600000;
} else if (query.period === '24h' || query.period === '1d') {
period = 86400000;
} else {
return {};
}
if (!query.end_date) {
expiration = Math.floor((period - (Date.now() - now.getTime())) / 1000);
}
const response = {} as any;
const periodStart = new Date(now.getTime() - period);
const pStart = periodStart.toISOString();
const pEnd = now.toISOString();
const cacheKey = `${fastify.manager.chain}_act_stats_${pStart}_${pEnd}_${query.unique_actors}`;
const cachedValue = await fastify.redis.get(cacheKey);
if (cachedValue) {
const cachedResponse = JSON.parse(cachedValue);
cachedResponse.cached = true;
cachedResponse.cache_exp = expiration;
return cachedResponse;
}
const firstReq = await getLastSeq(fastify, pStart);
const lastReq = await getLastSeq(fastify, pEnd);
response.action_count = lastReq - firstReq;
response.tx_count = await getTxCount(fastify, pStart, pEnd);
if (query.unique_actors) {
response.unique_actors = await getUniqueActors(fastify, pStart, pEnd);
}
response.period = query.period;
response.from = pStart;
response.to = pEnd;
await fastify.redis.set(cacheKey, JSON.stringify(response), 'EX', expiration);
return response;
}
export function getActionUsageHandler(fastify: FastifyInstance, route: string) {
return async (request: FastifyRequest, reply: FastifyReply) => {
reply.send(await timedQuery(getActionUsage, fastify, request, route));
}
}
@@ -1,64 +0,0 @@
import {FastifyInstance, FastifyReply, FastifyRequest} from "fastify";
import {timedQuery} from "../../../helpers/functions";
import {Search} from "@elastic/elasticsearch/api/requestParams";
import {applyTimeFilter} from "../../v2-history/get_actions/functions";
async function getMissedBlocks(fastify: FastifyInstance, request: FastifyRequest) {
const query: any = request.query;
const response = {
stats: {
by_producer: {}
},
events: []
};
const searchParams: Search<any> = {
track_total_hits: true,
index: fastify.manager.chain + "-logs-*",
size: 100,
body: {
query: {
bool: {
must: [
{term: {"type": "missed_blocks"}}
]
}
},
sort: {
"@timestamp": "desc"
}
}
};
let minBlocks = 0;
if (query.min_blocks) {
minBlocks = parseInt(query.min_blocks);
searchParams.body.query.bool.must.push({range: {"missed_blocks.size": {gte: minBlocks}}})
}
if (query.producer) {
searchParams.body.query.bool.must.push({term: {"missed_blocks.producer": query.producer}});
}
applyTimeFilter(query, searchParams.body.query);
const apiResponse = await fastify.elastic.search(searchParams);
apiResponse.body.hits.hits.forEach(v => {
const ev = v._source;
response.events.push({
"@timestamp": ev["@timestamp"],
...ev.missed_blocks
});
if (!response.stats.by_producer[ev.missed_blocks.producer]) {
response.stats.by_producer[ev.missed_blocks.producer] = ev.missed_blocks.size;
} else {
response.stats.by_producer[ev.missed_blocks.producer] += ev.missed_blocks.size;
}
});
return response;
}
export function getMissedBlocksHandler(fastify: FastifyInstance, route: string) {
return async (request: FastifyRequest, reply: FastifyReply) => {
reply.send(await timedQuery(getMissedBlocks, fastify, request, route));
}
}
@@ -1,75 +0,0 @@
import {FastifyInstance, FastifyReply, FastifyRequest} from "fastify";
import {timedQuery} from "../../../helpers/functions";
const percentiles = [1, 5, 25, 50, 75, 95, 99];
async function getResourceUsage(fastify: FastifyInstance, request: FastifyRequest) {
const query: any = request.query;
const searchBody: any = {
query: {
bool: {
must: [
{term: {"act.account": query.code}},
{term: {"act.name": query.action}},
{term: {"action_ordinal": {"value": 1}}},
{
range: {
"@timestamp": {
gte: "now-2d/d",
lt: "now/d"
}
}
}
]
}
},
track_total_hits: true,
size: 0,
aggs: {
cpu_extended_stats: {extended_stats: {field: "cpu_usage_us"}},
net_extended_stats: {extended_stats: {field: "net_usage_words"}},
cpu_percentiles: {
percentiles: {
field: "cpu_usage_us",
percents: percentiles
}
},
net_percentiles: {
percentiles: {
field: "net_usage_words",
percents: percentiles
}
}
}
};
if (request.query['@transfer.to']) {
searchBody.query.bool.must.push({term: {"@transfer.to": request.query['@transfer.to']}});
}
const results = await fastify.elastic.search({
index: fastify.manager.chain + "-action-*",
body: searchBody
});
if (results.body) {
const data = results.body.aggregations;
return {
cpu: {
stats: data.cpu_extended_stats,
percentiles: data.cpu_percentiles.values
},
net: {
stats: data.net_extended_stats,
percentiles: data.net_percentiles.values
}
};
} else {
return {};
}
}
export function getResourceUsageHandler(fastify: FastifyInstance, route: string) {
return async (request: FastifyRequest, reply: FastifyReply) => {
reply.send(await timedQuery(getResourceUsage, fastify, request, route));
}
}
-90
View File
@@ -1,90 +0,0 @@
import {FastifyInstance, FastifyReply, FastifyRequest} from "fastify";
import {connect} from "amqplib";
import {timedQuery} from "../../../helpers/functions";
import {getLastIndexedBlockWithTotalBlocks} from "../../../../helpers/common_functions";
async function checkRabbit(fastify: FastifyInstance) {
try {
const connection = await connect(fastify.manager.ampqUrl);
await connection.close();
return createHealth('RabbitMq', 'OK');
} catch (e) {
console.log(e);
return createHealth('RabbitMq', 'Error');
}
}
async function checkNodeos(fastify: FastifyInstance) {
const rpc = fastify.manager.nodeosJsonRPC;
try {
const results = await rpc.get_info();
if (results) {
const diff = (new Date().getTime()) - (new Date(results.head_block_time + '+00:00').getTime());
return createHealth('NodeosRPC', 'OK', {
head_block_num: results.head_block_num,
head_block_time: results.head_block_time,
time_offset: diff,
last_irreversible_block: results.last_irreversible_block_num,
chain_id: results.chain_id
});
} else {
return createHealth('NodeosRPC', 'Error');
}
} catch (e) {
return createHealth('NodeosRPC', 'Error');
}
}
async function checkElastic(fastify: FastifyInstance) {
try {
let esStatus = await fastify.elastic.cat.health({format: 'json', v: true});
let indexedBlocks = await getLastIndexedBlockWithTotalBlocks(fastify.elastic, fastify.manager.chain);
const data = {
last_indexed_block: indexedBlocks[0],
total_indexed_blocks: indexedBlocks[1],
active_shards: esStatus.body[0]['active_shards_percent']
};
let stat = 'OK';
esStatus.body.forEach(status => {
if (status.status === 'yellow' && stat !== 'Error') {
stat = 'Warning'
} else if (status.status === 'red') {
stat = 'Error'
}
});
return createHealth('Elasticsearch', stat, data);
} catch (e) {
console.log(e, 'Elasticsearch Error');
return createHealth('Elasticsearch', 'Error');
}
}
function createHealth(name: string, status, data?: any) {
let time = Date.now();
return {
service: name,
status: status,
service_data: data,
time: time
}
}
async function getHealthQuery(fastify: FastifyInstance, request: FastifyRequest) {
let response = {
version: fastify.manager.current_version,
version_hash: fastify.manager.getServerHash(),
host: fastify.manager.config.api.server_name,
health: [],
features: fastify.manager.config.features
};
response.health.push(await checkRabbit(fastify));
response.health.push(await checkNodeos(fastify));
response.health.push(await checkElastic(fastify));
return response;
}
export function healthHandler(fastify: FastifyInstance, route: string) {
return async (request: FastifyRequest, reply: FastifyReply) => {
reply.send(await timedQuery(getHealthQuery, fastify, request, route));
}
}
-18
View File
@@ -1,18 +0,0 @@
import {FastifyInstance, FastifySchema} from "fastify";
import {addApiRoute, getRouteName} from "../../../helpers/functions";
import {healthHandler} from "./health";
export default function (fastify: FastifyInstance, opts: any, next) {
const schema: FastifySchema = {
tags: ['status'],
summary: "API Service Health Report"
};
addApiRoute(
fastify,
'GET',
getRouteName(__filename),
healthHandler,
schema
);
next();
}
-245
View File
@@ -1,245 +0,0 @@
import {hLog} from "../helpers/common_functions";
import {ConfigurationModule} from "../modules/config";
import {ConnectionManager} from "../connections/manager.class";
import {HyperionConfig} from "../interfaces/hyperionConfig";
import * as Redis from 'ioredis';
import fastify from 'fastify'
import {registerPlugins} from "./plugins";
import {AddressInfo} from "net";
import {registerRoutes} from "./routes";
import {generateOpenApiConfig} from "./config/open_api";
import {createWriteStream, existsSync, mkdirSync} from "fs";
import {SocketManager} from "./socketManager";
import {HyperionModuleLoader} from "../modules/loader";
import {extendedActions} from "./routes/v2-history/get_actions/definitions";
import {Socket, io} from "socket.io-client";
class HyperionApiServer {
private conf: HyperionConfig;
private readonly manager: ConnectionManager;
mLoader: HyperionModuleLoader;
private readonly fastify;
private readonly chain: string;
socketManager: SocketManager;
private hub: Socket;
constructor() {
const cm = new ConfigurationModule();
this.conf = cm.config;
this.chain = this.conf.settings.chain;
process.title = `hyp-${this.chain}-api`;
this.manager = new ConnectionManager(cm);
this.manager.calculateServerHash();
this.mLoader = new HyperionModuleLoader(cm);
if (!existsSync('./logs/' + this.chain)) {
mkdirSync('./logs/' + this.chain, {recursive: true});
}
const logStream = createWriteStream('./logs/' + this.chain + '/api.access.log');
const loggerOpts = {
stream: logStream,
redact: ['req.headers.authorization'],
level: 'info',
prettyPrint: true,
serializers: {
res: (reply) => {
return {
statusCode: reply.statusCode
};
},
req: (request) => {
return {
method: request.method,
url: request.url,
ip: request.headers['x-real-ip']
}
}
}
};
this.fastify = fastify({
ignoreTrailingSlash: false,
trustProxy: true,
pluginTimeout: 5000,
logger: this.conf.api.access_log ? loggerOpts : false
});
this.fastify.decorate('manager', this.manager);
// import get_actions query params from custom modules
const extendedActionsSet: Set<string> = new Set([...extendedActions]);
for (const qPrefix of this.mLoader.extendedActions) {
extendedActionsSet.add(qPrefix);
}
this.fastify.decorate('allowedActionQueryParamSet', extendedActionsSet);
// define chain api url for /v1/chain/ redirects
let chainApiUrl: string = this.conf.api.push_api;
if (chainApiUrl === null || chainApiUrl === "") {
chainApiUrl = this.manager.conn.chains[this.chain].http;
}
this.fastify.decorate('chain_api', chainApiUrl);
// define optional push api url for /v1/chain/push_transaction
if (this.conf.api.push_api) {
this.fastify.decorate('push_api', this.conf.api.push_api);
}
hLog(`Chain API URL: "${this.fastify.chain_api}" | Push API URL: "${this.fastify.push_api}"`);
const ioRedisClient = new Redis(this.manager.conn.redis);
let rateLimiterWhitelist = ['127.0.0.1'];
if (this.conf.api.rate_limit_allow && this.conf.api.rate_limit_allow.length > 0) {
const tempSet = new Set<string>(['127.0.0.1', ...this.conf.api.rate_limit_allow]);
rateLimiterWhitelist = [...tempSet];
}
let rateLimiterRPM = 1000;
if (this.conf.api.rate_limit_rpm) {
rateLimiterRPM = this.conf.api.rate_limit_rpm;
}
const api_rate_limit = {
max: rateLimiterRPM,
allowList: rateLimiterWhitelist,
timeWindow: '1 minute',
redis: ioRedisClient
};
if (this.conf.features.streaming.enable) {
this.activateStreaming();
}
registerPlugins(this.fastify, {
fastify_elasticsearch: {client: this.manager.elasticsearchClient},
fastify_swagger: generateOpenApiConfig(this.manager.config),
fastify_rate_limit: api_rate_limit,
fastify_redis: this.manager.conn.redis,
fastify_eosjs: this.manager,
});
this.addGenericTypeParsing();
}
activateStreaming() {
console.log('Importing stream module');
import('./socketManager').then((mod) => {
const connOpts = this.manager.conn.chains[this.chain];
let _port = 57200;
if (connOpts.WS_ROUTER_PORT) {
_port = connOpts.WS_ROUTER_PORT;
}
let _host = "127.0.0.1";
if (connOpts.WS_ROUTER_HOST) {
_host = connOpts.WS_ROUTER_HOST;
}
this.socketManager = new mod.SocketManager(
this.fastify,
`http://${_host}:${_port}`,
this.manager.conn.redis
);
this.socketManager.startRelay();
});
}
private addGenericTypeParsing() {
this.fastify.addContentTypeParser('*', (request, payload, done) => {
let data = '';
payload.on('data', chunk => {
data += chunk;
});
payload.on('end', () => {
done(null, data);
});
payload.on('error', (err) => {
console.log('---- Content Parsing Error -----');
console.log(err);
});
});
}
async init() {
await this.mLoader.init();
// add custom plugin routes
for (const plugin of this.mLoader.plugins) {
if (plugin.hasApiRoutes) {
plugin.addRoutes(this.fastify);
plugin.chainName = this.chain;
}
}
registerRoutes(this.fastify);
this.fastify.ready().then(async () => {
await this.fastify.swagger();
}, (err) => {
hLog('an error happened', err)
});
try {
await this.fastify.listen({
host: this.conf.api.server_addr,
port: this.conf.api.server_port
});
hLog(`${this.chain} hyperion api ready and listening on port ${(this.fastify.server.address() as AddressInfo).port}`);
this.startHyperionHub();
} catch (err) {
hLog(err);
process.exit(1)
}
}
startHyperionHub() {
if (this.conf.hub) {
const url = this.conf.hub.inform_url;
hLog(`Connecting API to Hyperion Hub`);
this.hub = io(url, {
query: {
key: this.conf.hub.publisher_key,
client_mode: 'false'
}
});
this.hub.on('connect', () => {
hLog(`Hyperion Hub connected!`);
this.emitHubApiUpdate();
});
}
}
private emitHubApiUpdate() {
this.hub.emit('hyp_info', {
type: 'api',
production: this.conf.hub.production,
location: this.conf.hub.location,
chainId: this.manager.conn.chains[this.chain].chain_id,
providerName: this.conf.api.provider_name,
explorerEnabled: this.conf.api.enable_explorer,
providerUrl: this.conf.api.provider_url,
providerLogo: this.conf.api.provider_logo,
chainLogo: this.conf.api.chain_logo_url,
chainCodename: this.chain,
chainName: this.conf.api.chain_name,
endpoint: this.conf.api.server_name,
features: this.conf.features,
filters: {
blacklists: this.conf.blacklists,
whitelists: this.conf.whitelists
}
});
}
}
const server = new HyperionApiServer();
server.init().catch(hLog);
-384
View File
@@ -1,384 +0,0 @@
import {checkFilter, hLog} from '../helpers/common_functions';
import {Server, Socket} from 'socket.io';
import {createAdapter} from 'socket.io-redis';
import {io} from 'socket.io-client';
import {FastifyInstance} from "fastify";
import * as Redis from "ioredis";
export interface StreamDeltasRequest {
code: string;
table: string;
scope: string;
payer: string;
start_from: number | string;
read_until: number | string;
}
export interface RequestFilter {
field: string;
value: string;
}
export interface StreamActionsRequest {
contract: string;
account: string;
action: string;
filters: RequestFilter[];
start_from: number | string;
read_until: number | string;
}
async function addBlockRangeOpts(data, search_body, fastify: FastifyInstance) {
let timeRange;
let blockRange;
let head;
if (typeof data['start_from'] === 'string' && data['start_from'] !== '') {
if (!timeRange) {
timeRange = {"@timestamp": {}};
}
timeRange["@timestamp"]['gte'] = data['start_from'];
}
if (typeof data['read_until'] === 'string' && data['read_until'] !== '') {
if (!timeRange) {
timeRange = {"@timestamp": {}};
}
timeRange["@timestamp"]['lte'] = data['read_until'];
}
if (typeof data['start_from'] === 'number' && data['start_from'] !== 0) {
if (!blockRange) {
blockRange = {"block_num": {}};
}
if (data['start_from'] < 0) {
if (!head) {
head = (await fastify.eosjs.rpc.get_info()).head_block_num;
}
blockRange["block_num"]['gte'] = head + data['start_from'];
} else {
blockRange["block_num"]['gte'] = data['start_from'];
}
}
if (typeof data['read_until'] === 'number' && data['read_until'] !== 0) {
if (!blockRange) {
blockRange = {"block_num": {}};
}
if (data['read_until'] < 0) {
if (!head) {
head = (await fastify.eosjs.rpc.get_info()).head_block_num;
}
blockRange["block_num"]['lte'] = head + data['read_until'];
} else {
blockRange["block_num"]['lte'] = data['read_until'];
}
}
if (timeRange) {
search_body.query.bool.must.push({
range: timeRange,
});
}
if (blockRange) {
search_body.query.bool.must.push({
range: blockRange,
});
}
}
function addTermMatch(data, search_body, field) {
if (data[field] !== '*' && data[field] !== '') {
const termQuery = {};
termQuery[field] = data[field];
search_body.query.bool.must.push({'term': termQuery});
}
}
const deltaQueryFields = ['code', 'table', 'scope', 'payer'];
async function streamPastDeltas(fastify: FastifyInstance, socket, data) {
const search_body = {
query: {bool: {must: []}},
sort: {block_num: 'asc'},
};
await addBlockRangeOpts(data, search_body, fastify);
deltaQueryFields.forEach(f => {
addTermMatch(data, search_body, f);
});
const responseQueue = [];
let counter = 0;
const init_response = await fastify.elastic.search({
index: fastify.manager.chain + '-delta-*',
scroll: '30s',
size: 20,
body: search_body,
});
responseQueue.push(init_response);
while (responseQueue.length) {
const {body} = responseQueue.shift();
counter += body['hits']['hits'].length;
if (socket.connected) {
socket.emit('message', {
type: 'delta_trace',
mode: 'history',
messages: body['hits']['hits'].map(doc => doc._source),
});
} else {
hLog('LOST CLIENT');
break;
}
if (body['hits'].total.value === counter) {
hLog(`${counter} past deltas streamed to ${socket.id}`);
break;
}
const next_response = await fastify.elastic.scroll({
body: {
scroll_id: body['_scroll_id'],
scroll: '30s'
}
});
responseQueue.push(next_response);
}
}
async function streamPastActions(fastify: FastifyInstance, socket, data) {
const search_body = {
query: {bool: {must: []}},
sort: {global_sequence: 'asc'},
};
await addBlockRangeOpts(data, search_body, fastify);
if (data.account !== '') {
search_body.query.bool.must.push({
bool: {
should: [
{term: {'notified': data.account}},
{term: {'act.authorization.actor': data.account}},
],
},
});
}
if (data.contract !== '*' && data.contract !== '') {
search_body.query.bool.must.push({'term': {'act.account': data.contract}});
}
if (data.action !== '*' && data.action !== '') {
search_body.query.bool.must.push({'term': {'act.name': data.action}});
}
const onDemandFilters = [];
if (data.filters.length > 0) {
data.filters.forEach(f => {
if (f.field && f.value) {
if (f.field.startsWith('@') && !f.field.startsWith('act.data')) {
const _q = {};
_q[f.field] = f.value;
search_body.query.bool.must.push({'term': _q});
} else {
onDemandFilters.push(f);
}
}
});
}
const responseQueue = [];
let counter = 0;
const init_response = await fastify.elastic.search({
index: fastify.manager.chain + '-action-*',
scroll: '30s',
size: 20,
body: search_body,
});
responseQueue.push(init_response);
while (responseQueue.length) {
const {body} = responseQueue.shift();
const enqueuedMessages = [];
counter += body['hits']['hits'].length;
for (const doc of body['hits']['hits']) {
let allow = false;
if (onDemandFilters.length > 0) {
allow = onDemandFilters.every(filter => {
return checkFilter(filter, doc._source);
});
} else {
allow = true;
}
if (allow) {
enqueuedMessages.push(doc._source);
}
}
if (socket.connected) {
socket.emit('message', {type: 'action_trace', mode: 'history', messages: enqueuedMessages});
} else {
hLog('LOST CLIENT');
break;
}
if (body['hits'].total.value === counter) {
hLog(`${counter} past actions streamed to ${socket.id}`);
break;
}
if (init_response.body.hits.total.value < 1000) {
const next_response = await fastify.elastic.scroll({
body: {scroll_id: body['_scroll_id'], scroll: '30s'}
});
responseQueue.push(next_response);
} else {
hLog('Request too large!');
socket.emit('message', {type: 'action_trace', mode: 'history', messages: []});
}
}
}
export class SocketManager {
private io: Server;
private relay;
relay_restored = true;
relay_down = false;
private readonly url;
private readonly server: FastifyInstance;
constructor(fastify: FastifyInstance, url, redisOptions) {
this.server = fastify;
this.url = url;
this.io = new Server(fastify.server, {
allowEIO3: true,
transports: ['websocket', 'polling'],
});
const pubClient = new Redis(redisOptions);
const subClient = pubClient.duplicate();
this.io.adapter(createAdapter({pubClient, subClient}));
this.io.on('connection', (socket: Socket) => {
if (socket.handshake.headers['x-forwarded-for']) {
hLog(`[socket] ${socket.id} connected via ${socket.handshake.headers['x-forwarded-for']}`);
}
socket.emit('message', {
event: 'handshake',
chain: fastify.manager.chain,
});
if (this.relay) {
this.relay.emit('event', {
type: 'client_count',
counter: this.io.sockets.sockets.size,
});
}
socket.on('delta_stream_request', async (data: StreamDeltasRequest, callback) => {
if (typeof callback === 'function' && data) {
try {
if (data.start_from) {
await streamPastDeltas(this.server, socket, data);
}
this.emitToRelay(data, 'delta_request', socket, callback);
} catch (e) {
console.log(e);
}
}
});
socket.on('action_stream_request', async (data: StreamActionsRequest, callback) => {
if (typeof callback === 'function' && data) {
try {
if (data.start_from) {
await streamPastActions(this.server, socket, data);
}
this.emitToRelay(data, 'action_request', socket, callback);
} catch (e) {
console.log(e);
}
}
});
socket.on('disconnect', (reason) => {
hLog(`[socket] ${socket.id} disconnected - ${reason}`);
this.relay.emit('event', {
type: 'client_disconnected',
id: socket.id,
reason,
});
});
});
hLog('Websocket manager loaded!');
}
startRelay() {
hLog(`starting relay - ${this.url}`);
this.relay = io(this.url, {path: '/router'});
this.relay.on('connect', () => {
hLog('Relay Connected!');
if (this.relay_down) {
this.relay_restored = true;
this.relay_down = false;
this.io.emit('status', 'relay_restored');
}
});
this.relay.on('disconnect', () => {
hLog('Relay disconnected!');
this.io.emit('status', 'relay_down');
this.relay_down = true;
this.relay_restored = false;
});
this.relay.on('delta', (traceData) => {
this.emitToClient(traceData, 'delta_trace');
});
this.relay.on('trace', (traceData) => {
this.emitToClient(traceData, 'action_trace');
});
// Relay LIB info to clients;
this.relay.on('lib_update', (data) => {
if (this.server.manager.conn.chains[this.server.manager.chain].chain_id === data.chain_id) {
this.io.emit('lib_update', data);
}
});
// Relay LIB info to clients;
this.relay.on('fork_event', (data) => {
hLog(data);
if (this.server.manager.conn.chains[this.server.manager.chain].chain_id === data.chain_id) {
this.io.emit('fork_event', data);
}
});
}
emitToClient(traceData, type) {
if (this.io.sockets.sockets.has(traceData.client)) {
this.io.sockets.sockets.get(traceData.client).emit('message', {
type: type,
mode: 'live',
message: traceData.message,
});
}
}
emitToRelay(data, type, socket, callback) {
if (this.relay.connected) {
this.relay.emit('event', {
type: type,
client_socket: socket.id,
request: data,
}, (response) => {
callback(response);
});
} else {
callback('STREAMING_OFFLINE');
}
}
}
@@ -1,5 +1,8 @@
{
"api": {
"enabled": true,
"pm2_scaling": 1,
"node_max_old_space_size": 1024,
"chain_name": "EXAMPLE Chain",
"server_addr": "127.0.0.1",
"server_port": 7000,
@@ -19,12 +22,41 @@
"get_trx_actions": 200
},
"access_log": false,
"enable_explorer": false,
"chain_api_error_log": false,
"custom_core_token": "",
"enable_export_action": false,
"disable_rate_limit": false,
"rate_limit_rpm": 1000,
"rate_limit_allow": []
"rate_limit_allow": [],
"disable_tx_cache": false,
"tx_cache_expiration_sec": 3600,
"v1_chain_cache": [
{
"path": "get_block",
"ttl": 3000
},
{
"path": "get_info",
"ttl": 500
}
]
},
"indexer": {
"enabled": true,
"node_max_old_space_size": 4096,
"start_on": 0,
"stop_on": 0,
"rewrite": false,
"purge_queues": false,
"live_reader": false,
"live_only_mode": false,
"abi_scan_mode": true,
"fetch_block": true,
"fetch_traces": true,
"disable_reading": false,
"disable_indexing": false,
"process_deltas": true,
"disable_delta_rm": true
},
"settings": {
"preview": false,
@@ -45,7 +77,8 @@
"hot_warm_policy": false,
"custom_policy": "",
"bypass_index_map": false,
"index_partition_size": 10000000
"index_partition_size": 10000000,
"es_replicas": 0
},
"blacklists": {
"actions": [],
@@ -58,35 +91,21 @@
"root_only": false
},
"scaling": {
"readers": 1,
"ds_queues": 1,
"ds_threads": 1,
"ds_pool_size": 1,
"indexing_queues": 1,
"ad_idx_queues": 1,
"dyn_idx_queues": 1,
"max_autoscale": 4,
"batch_size": 5000,
"resume_trigger": 5000,
"readers": 1,
"ds_queues": 1,
"ds_threads": 1,
"ds_pool_size": 1,
"indexing_queues": 1,
"ad_idx_queues": 1,
"dyn_idx_queues": 1,
"max_autoscale": 4,
"batch_size": 5000,
"resume_trigger": 5000,
"auto_scale_trigger": 20000,
"block_queue_limit": 10000,
"max_queue_limit": 100000,
"routing_mode": "round_robin",
"polling_interval": 10000
},
"indexer": {
"start_on": 0,
"stop_on": 0,
"rewrite": false,
"purge_queues": false,
"live_reader": false,
"live_only_mode": false,
"abi_scan_mode": true,
"fetch_block": true,
"fetch_traces": true,
"disable_reading": false,
"disable_indexing": false,
"process_deltas": true
"block_queue_limit": 10000,
"max_queue_limit": 100000,
"routing_mode": "round_robin",
"polling_interval": 10000
},
"features": {
"streaming": {
@@ -2,27 +2,33 @@
"amqp": {
"host": "127.0.0.1:5672",
"api": "127.0.0.1:15672",
"user": "username",
"pass": "password",
"vhost": "hyperion"
"protocol": "http",
"user": "guest",
"pass": "guest",
"vhost": "hyperion",
"frameMax": "0x10000"
},
"elasticsearch": {
"protocol": "http",
"protocol": "https",
"host": "127.0.0.1:9200",
"ingest_nodes": ["127.0.0.1:9200"],
"ingest_nodes": [
"127.0.0.1:9200"
],
"user": "elastic",
"pass": "password"
},
"redis": {
"host": "127.0.0.1",
"port": "6379"
"port": 6379
},
"chains": {
"eos": {
"name": "EOS Mainnet",
"chain_id": "aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906",
"http": "http://127.0.0.1:8888",
"ship": "ws://127.0.0.1:8080",
"ship": [
"ws://127.0.0.1:8080"
],
"WS_ROUTER_PORT": 7001,
"WS_ROUTER_HOST": "127.0.0.1"
}
-55
View File
@@ -1,55 +0,0 @@
{
"amqp": {
"host": "127.0.0.1:5672",
"api": "127.0.0.1:15672",
"user": "username",
"pass": "password",
"vhost": "hyperion"
},
"elasticsearch": {
"host": "127.0.0.1:9200",
"ingest_nodes": [
"127.0.0.1:9200"
],
"user": "elastic",
"pass": "password"
},
"redis": {
"host": "127.0.0.1",
"port": "6379"
},
"chains": {
"eos": {
"name": "EOS Mainnet",
"chain_id": "aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906",
"http": "http://127.0.0.1:8888",
"ship": "ws://127.0.0.1:8080",
"WS_ROUTER_PORT": 7001,
"WS_ROUTER_HOST": "127.0.0.1"
},
"eos2": {
"name": "EOS Mainnet",
"chain_id": "aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906",
"http": "http://127.0.0.1:8888",
"ship": "ws://127.0.0.1:8080",
"WS_ROUTER_PORT": 7001,
"WS_ROUTER_HOST": "127.0.0.1"
},
"demo": {
"name": "Demo Chain",
"chain_id": "aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906",
"http": "http://api.eosrio.io",
"ship": "ws://200.201.191.228:58013",
"WS_ROUTER_PORT": 57201,
"WS_ROUTER_HOST": "192.168.0.1"
},
"demo2": {
"name": "Demo Chain",
"chain_id": "aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906",
"http": "http://api.eosrio.io",
"ship": "ws://200.201.191.228:58013",
"WS_ROUTER_PORT": 57201,
"WS_ROUTER_HOST": "192.168.0.1"
}
}
}
-85
View File
@@ -1,85 +0,0 @@
import {debugLog, hLog} from "../helpers/common_functions";
import got, {HTTPError} from "got";
import {connect, Connection} from 'amqplib';
export async function createConnection(config): Promise<Connection> {
try {
const amqp_url = getAmpqUrl(config);
const conn: Connection = await connect(amqp_url);
debugLog("[AMQP] connection established");
return conn;
} catch (e) {
hLog("[AMQP] failed to connect!");
hLog(e.message);
await new Promise(resolve => setTimeout(resolve, 5000));
return await createConnection(config);
}
}
export function getAmpqUrl(config): string {
const u = encodeURIComponent(config.user);
const p = encodeURIComponent(config.pass);
const v = encodeURIComponent(config.vhost)
return `amqp://${u}:${p}@${config.host}/${v}`;
}
async function createChannels(connection) {
try {
const channel = await connection.createChannel();
const confirmChannel = await connection.createConfirmChannel();
return [channel, confirmChannel];
} catch (e) {
hLog("[AMQP] failed to create channels");
hLog(e);
return null;
}
}
export async function amqpConnect(onReconnect, config, onClose) {
let connection = await createConnection(config);
if (connection) {
const channels = await createChannels(connection);
if (channels) {
connection.on('error', (err) => {
hLog(err.message);
});
connection.on('close', () => {
hLog('Connection closed!');
onClose();
setTimeout(async () => {
hLog('Retrying in 5 seconds...');
const _channels = await amqpConnect(onReconnect, config, onClose);
onReconnect(_channels);
return _channels;
}, 5000);
});
return channels;
} else {
return null;
}
} else {
return null;
}
}
export async function checkQueueSize(q_name, config) {
try {
const v = encodeURIComponent(config.vhost);
const apiUrl = `http://${config.api}/api/queues/${v}/${encodeURIComponent(q_name)}`;
const opts = {
username: config.user,
password: config.pass
};
const data = await got.get(apiUrl, opts).json() as any;
return data.messages;
} catch (e) {
hLog('[WARNING] Checking queue size failed, HTTP API is not ready!');
if (e instanceof HTTPError) {
hLog(e.response.body);
} else {
hLog(JSON.stringify(e.response.body, null, 2));
}
return 0;
}
}
-175
View File
@@ -1,175 +0,0 @@
import {ConfigurationModule} from "../modules/config";
import {JsonRpc} from "eosjs";
import got from "got";
import {Client} from '@elastic/elasticsearch'
import {HyperionConnections} from "../interfaces/hyperionConnections";
import {HyperionConfig} from "../interfaces/hyperionConfig";
import {amqpConnect, checkQueueSize, getAmpqUrl} from "./amqp";
import {StateHistorySocket} from "./state-history";
import fetch from 'cross-fetch';
import {exec} from "child_process";
import {hLog} from "../helpers/common_functions";
export class ConnectionManager {
config: HyperionConfig;
conn: HyperionConnections;
chain: string;
last_commit_hash: string;
current_version: string;
private readonly esIngestClients: Client[];
private esIngestClient: Client;
constructor(private cm: ConfigurationModule) {
this.config = cm.config;
this.conn = cm.connections;
this.chain = this.config.settings.chain;
this.esIngestClients = [];
this.prepareESClient();
this.prepareIngestClients();
}
get nodeosJsonRPC() {
// @ts-ignore
return new JsonRpc(this.conn.chains[this.chain].http, {fetch});
}
async purgeQueues() {
hLog(`Purging all ${this.chain} queues!`);
const apiUrl = `http://${this.conn.amqp.api}`;
const vHost = encodeURIComponent(this.conn.amqp.vhost);
const getAllQueuesFromVHost = apiUrl + `/api/queues/${vHost}`;
const opts = {
username: this.conn.amqp.user,
password: this.conn.amqp.pass
};
let result;
try {
const data = await got(getAllQueuesFromVHost, opts);
if (data) {
result = JSON.parse(data.body);
}
} catch (e) {
console.log(e.message);
console.error('failed to connect to rabbitmq http api');
process.exit(1);
}
if (result) {
for (const queue of result) {
if (queue.name.startsWith(this.chain + ":")) {
const msg_count = parseInt(queue.messages);
if (msg_count > 0) {
try {
await got.delete(apiUrl + `/api/queues/${vHost}/${queue.name}/contents`, opts);
hLog(`${queue.messages} messages deleted on queue ${queue.name}`);
} catch (e) {
console.log(e.message);
console.error('failed to connect to rabbitmq http api');
process.exit(1);
}
}
}
}
}
}
prepareESClient() {
let es_url;
const _es = this.conn.elasticsearch;
if (!_es.protocol) {
_es.protocol = 'http';
}
if (_es.user !== '') {
es_url = `${_es.protocol}://${_es.user}:${_es.pass}@${_es.host}`;
} else {
es_url = `${_es.protocol}://${_es.host}`
}
this.esIngestClient = new Client({
node: es_url,
ssl: {
rejectUnauthorized: false
}
});
}
get elasticsearchClient() {
return this.esIngestClient;
}
prepareIngestClients() {
const _es = this.conn.elasticsearch;
if (!_es.protocol) {
_es.protocol = 'http';
}
if (_es.ingest_nodes) {
if (_es.ingest_nodes.length > 0) {
for (const node of _es.ingest_nodes) {
let es_url;
if (_es.user !== '') {
es_url = `${_es.protocol}://${_es.user}:${_es.pass}@${node}`;
} else {
es_url = `${_es.protocol}://${node}`
}
this.esIngestClients.push(new Client({
node: es_url,
pingTimeout: 100,
ssl: {
rejectUnauthorized: false
}
}));
}
}
}
}
get ingestClients() {
if (this.esIngestClients.length > 0) {
return this.esIngestClients;
} else {
return [this.esIngestClient];
}
}
async createAMQPChannels(onReconnect, onClose) {
return await amqpConnect(onReconnect, this.conn.amqp, onClose);
}
async checkQueueSize(queue) {
return await checkQueueSize(queue, this.conn.amqp);
}
get shipClient(): StateHistorySocket {
return new StateHistorySocket(this.conn.chains[this.config.settings.chain]['ship'], this.config.settings.max_ws_payload_mb);
}
get ampqUrl() {
return getAmpqUrl(this.conn.amqp);
}
calculateServerHash() {
exec('git rev-parse HEAD', (err, stdout) => {
if (err) {
// hLog(`\n ${err.message}\n >>> Failed to check last commit hash. Version hash will be "custom"`);
hLog(`Failed to check last commit hash. Version hash will be "custom"`);
this.last_commit_hash = 'custom';
} else {
hLog('Last commit hash on this branch is:', stdout);
this.last_commit_hash = stdout.trim();
}
this.getHyperionVersion();
});
}
getServerHash() {
return this.last_commit_hash;
}
getHyperionVersion() {
this.current_version = require('../package.json').version;
if (this.last_commit_hash === 'custom') {
this.current_version = this.current_version + '-dirty';
}
}
}
-48
View File
@@ -1,48 +0,0 @@
import {debugLog, hLog} from "../helpers/common_functions";
const WebSocket = require('ws');
export class StateHistorySocket {
private ws;
private readonly shipUrl;
private readonly max_payload_mb;
constructor(ship_url, max_payload_mb) {
this.shipUrl = ship_url;
if (max_payload_mb) {
this.max_payload_mb = max_payload_mb;
} else {
this.max_payload_mb = 256;
}
}
connect(onMessage, onDisconnect, onError, onConnected) {
debugLog(`Connecting to ${this.shipUrl}...`);
this.ws = new WebSocket(this.shipUrl, null, {
perMessageDeflate: false,
maxPayload: this.max_payload_mb * 1024 * 1024,
});
this.ws.on('open', () => {
hLog('Websocket connected!');
if (onConnected) {
onConnected();
}
});
this.ws.on('message', onMessage);
this.ws.on('close', () => {
hLog('Websocket disconnected!');
onDisconnect();
});
this.ws.on('error', (err) => {
hLog(`${this.shipUrl} :: ${err.message}`);
});
}
close() {
this.ws.close();
}
send(payload) {
this.ws.send(payload);
}
}
-260
View File
@@ -1,260 +0,0 @@
const AbiDefinitions = {
version: "eosio::abi/1.1",
structs: [
{
name: "extensions_entry",
base: "",
fields: [
{
name: "tag",
type: "uint16"
},
{
name: "value",
type: "bytes"
}
]
},
{
name: "type_def",
base: "",
fields: [
{
name: "new_type_name",
type: "string"
},
{
name: "type",
type: "string"
}
]
},
{
name: "field_def",
base: "",
fields: [
{
name: "name",
type: "string"
},
{
name: "type",
type: "string"
}
]
},
{
name: "struct_def",
base: "",
fields: [
{
name: "name",
type: "string"
},
{
name: "base",
type: "string"
},
{
name: "fields",
type: "field_def[]"
}
]
},
{
name: "action_def",
base: "",
fields: [
{
name: "name",
type: "name"
},
{
name: "type",
type: "string"
},
{
name: "ricardian_contract",
type: "string"
}
]
},
{
name: "table_def",
base: "",
fields: [
{
name: "name",
type: "name"
},
{
name: "index_type",
type: "string"
},
{
name: "key_names",
type: "string[]"
},
{
name: "key_types",
type: "string[]"
},
{
name: "type",
type: "string"
}
]
},
{
name: "clause_pair",
base: "",
fields: [
{
name: "id",
type: "string"
},
{
name: "body",
type: "string"
}
]
},
{
name: "error_message",
base: "",
fields: [
{
name: "error_code",
type: "uint64"
},
{
name: "error_msg",
type: "string"
}
]
},
{
name: "variant_def",
base: "",
fields: [
{
name: "name",
type: "string"
},
{
name: "types",
type: "string[]"
}
]
},
{
name: "abi_def",
base: "",
fields: [
{
name: "version",
type: "string"
},
{
name: "types",
type: "type_def[]"
},
{
name: "structs",
type: "struct_def[]"
},
{
name: "actions",
type: "action_def[]"
},
{
name: "tables",
type: "table_def[]"
},
{
name: "ricardian_clauses",
type: "clause_pair[]"
},
{
name: "error_messages",
type: "error_message[]"
},
{
name: "abi_extensions",
type: "extensions_entry[]"
},
{
name: "variants",
type: "variant_def[]$"
}
]
}
]
};
const RexAbi = {
version: "eosio::abi/1.1",
types: [],
structs: [
{
name: "buyresult",
base: "",
fields: [{
name: "rex_received",
type: "asset"
}
]
}, {
name: "orderresult",
base: "",
fields: [{
name: "owner",
type: "name"
}, {
name: "proceeds",
type: "asset"
}
]
}, {
name: "rentresult",
base: "",
fields: [{
name: "rented_tokens",
type: "asset"
}
]
},
{
name: "sellresult",
base: "",
fields: [{
name: "proceeds",
type: "asset"
}]
}
],
actions: [
{
name: "buyresult",
type: "buyresult",
ricardian_contract: ""
},
{
name: "orderresult",
type: "orderresult",
ricardian_contract: ""
},
{
name: "rentresult",
type: "rentresult",
ricardian_contract: ""
},
{
name: "sellresult",
type: "sellresult",
ricardian_contract: ""
}
]
};
module.exports = {AbiDefinitions, RexAbi};
-43
View File
@@ -1,43 +0,0 @@
// max js heap in MB for each indexer subprocess
const idx_js_heap = 4096;
// max js heap in MB for each api process
const api_js_heap = 1024;
function addIndexer(chainName) {
return {
script: './launcher.js',
name: chainName + '-indexer',
namespace: chainName,
interpreter: 'node',
interpreter_args: ['--max-old-space-size=' + idx_js_heap, '--trace-deprecation', '--trace-warnings'],
autorestart: false,
kill_timeout: 3600,
watch: false,
time: true, // include timestamps in pm2 logs
env: {
CONFIG_JSON: 'chains/' + chainName + '.config.json',
TRACE_LOGS: 'false',
},
};
}
function addApiServer(chainName, threads) {
return {
script: './api/server.js',
name: chainName + '-api',
namespace: chainName,
node_args: ['--max-old-space-size=' + api_js_heap, '--trace-deprecation', '--trace-warnings'],
exec_mode: 'cluster',
merge_logs: true,
instances: threads,
autorestart: true,
exp_backoff_restart_delay: 100,
watch: false,
env: {
CONFIG_JSON: 'chains/' + chainName + '.config.json',
},
};
}
module.exports = {addIndexer, addApiServer};
-103
View File
@@ -1,103 +0,0 @@
import {IlmPutLifecycle} from "@elastic/elasticsearch/api/requestParams";
// noinspection JSUnusedGlobalSymbols
export const ILPs: IlmPutLifecycle[] = [
{
policy: "hyperion-rollover",
body: {
"policy": {
"phases": {
"hot": {
"min_age": "0ms",
"actions": {
"rollover": {
"max_size": "200gb",
"max_age": "60d",
"max_docs": 100000000
},
"set_priority": {
"priority": 50
}
}
},
"warm": {
"min_age": "2d",
"actions": {
"allocate": {
"exclude": {
"data": "hot"
}
},
"set_priority": {
"priority": 25
}
}
}
}
}
}
},
{
policy: "50G30D",
body: {
policy: {
phases: {
hot: {
min_age: "0ms",
actions: {
rollover: {
max_age: "30d",
max_size: "50gb"
},
set_priority: {
priority: 100
}
}
}
}
}
}
},
{
policy: "10G30D",
body: {
policy: {
phases: {
hot: {
min_age: "0ms",
actions: {
rollover: {
max_age: "30d",
max_size: "10gb",
max_docs: 100000000
},
set_priority: {
priority: 100
}
}
}
}
}
}
},
{
policy: "200G",
body: {
policy: {
phases: {
hot: {
min_age: "0ms",
actions: {
rollover: {
max_size: "200gb"
},
set_priority: {
priority: 100
}
}
}
}
}
}
}
];
@@ -0,0 +1,5 @@
cluster.name: docker-cluster
network.host: 0.0.0.0
bootstrap.memory_lock: true
discovery.type: single-node
node.name: es01
@@ -0,0 +1,2 @@
-Xms8g
-Xmx8g
+5 -11
View File
@@ -1,11 +1,5 @@
FROM ubuntu:18.04
RUN apt-get update && apt-get upgrade -y && apt-get autoremove && apt-get install -y wget netcat
RUN wget -nv https://github.com/eosio/eos/releases/download/v2.0.5/eosio_2.0.5-1-ubuntu-18.04_amd64.deb
RUN apt-get install -y ./eosio_2.0.5-1-ubuntu-18.04_amd64.deb
RUN useradd -m -s /bin/bash eosio
USER eosio
EXPOSE 8080
FROM ubuntu:20.04
LABEL version="2.1.0" description="EOSIO 2.1.0"
RUN apt-get update && apt-get install -y wget
RUN wget -nv https://github.com/EOSIO/eos/releases/download/v2.1.0/eosio_2.1.0-1-ubuntu-20.04_amd64.deb
RUN apt-get install -y ./eosio_2.1.0-1-ubuntu-20.04_amd64.deb && rm -f ./eosio_2.1.0-1-ubuntu-20.04_amd64.deb
+7 -21
View File
@@ -1,28 +1,14 @@
# Enable block production, even if the chain is stale. (eosio::producer_plugin)
### PRODUCER PLUGIN ###
enable-stale-production = true
# ID of producer controlled by this node (eosio::producer_plugin)
producer-name = eosio
# print contract's output to console (eosio::chain_plugin)
contracts-console = true
# The local IP and port to listen for incoming http connections; set blank to disable. (eosio::http_plugin)
http-server-address = 0.0.0.0:8888
# If set to false, then any incoming "Host" header is considered valid (eosio::http_plugin)
http-validate-host = false
# enable trace history (eosio::state_history_plugin)
### STATE HISTORY PLUGIN ###
plugin = eosio::state_history_plugin
state-history-endpoint = 0.0.0.0:8080
trace-history = true
# enable chain state history (eosio::state_history_plugin)
chain-state-history = true
# the endpoint upon which to listen for incoming connections. Caution: only expose this port to your internal network. (eosio::state_history_plugin)
state-history-endpoint = 0.0.0.0:8080
# Plugin(s) to enable, may be specified multiple times
plugin = eosio::producer_api_plugin
### CHAIN API PLUGIN ###
plugin = eosio::chain_api_plugin
plugin = eosio::state_history_plugin
http-server-address = 0.0.0.0:8888
http-validate-host = false
+5 -14
View File
@@ -1,15 +1,6 @@
FROM ubuntu:18.04
RUN apt-get update && apt-get upgrade -y && apt-get autoremove && apt-get install -y build-essential git curl netcat
RUN curl -sL https://deb.nodesource.com/setup_14.x | bash -
RUN apt-get install -y nodejs && npm install pm2 -g && git clone https://github.com/eosrio/hyperion-history-api.git
RUN useradd -m -s /bin/bash hyperion && chown -R hyperion:hyperion /hyperion-history-api
USER hyperion
FROM node:16.5
RUN npm install pm2 -g
RUN git clone https://github.com/eosrio/hyperion-history-api.git
WORKDIR /hyperion-history-api
RUN npm install
EXPOSE 7001
RUN git checkout dev-3.3
RUN npm install --production
-5
View File
@@ -1,5 +0,0 @@
# Ignore everything in this directory
*
# Except this file
!.gitignore
+4
View File
@@ -0,0 +1,4 @@
default_vhost = hyperion
default_user = hyperion
default_pass = hyp123456
cluster_name = hyp-docker
Executable → Regular
View File
View File
Executable → Regular
View File
Executable → Regular
View File
Executable → Regular
View File
Executable → Regular
View File
Executable → Regular
View File

Some files were not shown because too many files have changed in this diff Show More