@onekeyfe/blockchain-libs
Version:
OneKey Blockchain Libs
202 lines • 8.14 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NearCli = void 0;
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const borsh = __importStar(require("borsh"));
const exceptions_1 = require("../../../basic/request/exceptions");
const json_rpc_1 = require("../../../basic/request/json-rpc");
const provider_1 = require("../../../types/provider");
const abc_1 = require("../../abc");
function parseJsonFromRawResponse(response) {
return JSON.parse(Buffer.from(response).toString());
}
function bytesJsonStringify(input) {
return Buffer.from(JSON.stringify(input));
}
class NearCli extends abc_1.SimpleClient {
constructor(url, defaultFinality = 'optimistic') {
super();
this.defaultFinality = defaultFinality;
this.rpc = new json_rpc_1.JsonRPCRequest(url);
}
async getInfo() {
const { blockNumber } = await this.getBestBlock();
const isReady = Number.isFinite(blockNumber) && blockNumber > 0;
return {
bestBlockNumber: blockNumber,
isReady,
};
}
async getTxCostConfig() {
const resp = await this.rpc.call('EXPERIMENTAL_protocol_config', {
finality: this.defaultFinality,
});
const { runtime_config: { transaction_costs: { action_receipt_creation_config, action_creation_config: { transfer_cost }, }, }, } = resp;
return {
action_receipt_creation_config,
transfer_cost,
};
}
async getBestBlock() {
const resp = await this.rpc.call('status', []);
return {
blockNumber: Number(resp.sync_info.latest_block_height),
blockHash: resp.sync_info.latest_block_hash,
};
}
async getAddress(address) {
var _a;
try {
const balanceInfo = await this.rpc.call('query', {
request_type: 'view_account',
account_id: address,
finality: this.defaultFinality,
});
const balance = new bignumber_js_1.default(balanceInfo.amount);
const accessKeys = await this.getAccessKeys(address);
const fullAccessKeys = accessKeys.filter((i) => i.type === 'FullAccess');
const [{ nonce }] = fullAccessKeys.length > 0 ? fullAccessKeys : accessKeys;
return {
existing: true,
balance,
nonce: Number.isFinite(nonce) && nonce > 0 ? nonce : undefined,
};
}
catch (e) {
if (e instanceof exceptions_1.JsonPRCResponseError && e.response) {
try {
const error = await e.response.json();
if (((_a = error === null || error === void 0 ? void 0 : error.cause) === null || _a === void 0 ? void 0 : _a.name) === 'UNKNOWN_ACCOUNT') {
return {
existing: false,
balance: new bignumber_js_1.default(0),
};
}
}
catch (e) {
// ignored
}
}
throw e;
}
}
async getAccessKeys(address) {
const info = await this.rpc.call('query', {
request_type: 'view_access_key_list',
account_id: address,
finality: this.defaultFinality,
});
return info.keys.map((key) => {
const permission = key.access_key.permission;
const isFullAccessKey = permission === 'FullAccess';
return {
type: isFullAccessKey ? 'FullAccess' : 'FunctionCall',
pubkey: key.public_key,
pubkeyHex: borsh
.baseDecode(key.public_key.split(':')[1] || '')
.toString('hex'),
nonce: key.access_key.nonce + 1,
functionCall: !isFullAccessKey
? {
allowance: permission.FunctionCall.allowance,
receiverId: permission.FunctionCall.receiver_id,
methodNames: permission.FunctionCall.method_names,
}
: undefined,
};
});
}
async getBalance(address, coin) {
if (coin === null || coin === void 0 ? void 0 : coin.tokenAddress) {
const tokenBalanceStr = await this.callContract(coin.tokenAddress, 'ft_balance_of', { account_id: address });
return new bignumber_js_1.default(tokenBalanceStr);
}
else {
const balanceInfo = await this.rpc.call('query', {
request_type: 'view_account',
account_id: address,
finality: this.defaultFinality,
});
return new bignumber_js_1.default(balanceInfo.amount);
}
}
async getFeePricePerUnit() {
const resp = await this.rpc.call('gas_price', [null]);
const normalPrice = new bignumber_js_1.default(resp.gas_price);
return {
normal: {
price: normalPrice,
},
};
}
async getTransactionStatus(txid) {
var _a;
try {
const resp = await this.rpc.call('tx', [
txid,
'dontcare', // required tx signer actually, but I found that just filling in any string works fine
]);
if (typeof resp.status === 'object' && 'SuccessValue' in resp.status) {
return provider_1.TransactionStatus.CONFIRM_AND_SUCCESS;
}
else {
return provider_1.TransactionStatus.CONFIRM_BUT_FAILED;
}
}
catch (e) {
if (e instanceof exceptions_1.JsonPRCResponseError && e.response) {
try {
const error = await e.response.json();
if (((_a = error === null || error === void 0 ? void 0 : error.cause) === null || _a === void 0 ? void 0 : _a.name) === 'UNKNOWN_TRANSACTION') {
return provider_1.TransactionStatus.NOT_FOUND;
}
}
catch (e) {
// ignored
}
}
throw e;
}
}
async callContract(contract, methodName, args = {}, { parse = parseJsonFromRawResponse, stringify = bytesJsonStringify } = {}) {
const serializedArgs = stringify(args).toString('base64');
const result = await this.rpc.call('query', {
request_type: 'call_function',
finality: this.defaultFinality,
method_name: methodName,
account_id: contract,
args_base64: serializedArgs,
});
return (result.result &&
result.result.length > 0 &&
parse(Buffer.from(result.result)));
}
async broadcastTransaction(rawTx) {
const tx = await this.rpc.call('broadcast_tx_commit', [rawTx]);
return tx.transaction.hash;
}
}
exports.NearCli = NearCli;
//# sourceMappingURL=nearcli.js.map