Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@near-js/accounts

Package Overview
Dependencies
Maintainers
0
Versions
34
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@near-js/accounts - npm Package Compare versions

Comparing version 1.2.1 to 1.3.0-next.0

6

lib/account_2fa.d.ts

@@ -82,3 +82,3 @@ import { FinalExecutionOutcome } from '@near-js/types';

*/
verifyCodeDefault(securityCode: string): Promise<any>;
verifyCodeDefault(securityCode: string): Promise<Response>;
/**

@@ -90,3 +90,3 @@ * Retrieves recovery methods for the account.

accountId: string;
data: any;
data: Response;
}>;

@@ -115,5 +115,5 @@ /**

*/
postSignedJson(path: any, body: any): Promise<any>;
postSignedJson(path: any, body: any): Promise<Response>;
}
export {};
//# sourceMappingURL=account_2fa.d.ts.map

@@ -1,26 +0,24 @@

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
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) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Account2FA = void 0;
const crypto_1 = require("@near-js/crypto");
const types_1 = require("@near-js/types");
const providers_1 = require("@near-js/providers");
const transactions_1 = require("@near-js/transactions");
const utils_1 = require("@near-js/utils");
const account_multisig_1 = require("./account_multisig");
const constants_1 = require("./constants");
const types_2 = require("./types");
const { addKey, deleteKey, deployContract, fullAccessKey, functionCall, functionCallAccessKey } = transactions_1.actionCreators;
class Account2FA extends account_multisig_1.AccountMultisig {
import { PublicKey } from '@near-js/crypto';
import { TypedError } from '@near-js/types';
import { actionCreators } from '@near-js/transactions';
import { Logger } from '@near-js/utils';
import unfetch from 'isomorphic-unfetch';
import { AccountMultisig } from './account_multisig';
import { MULTISIG_CHANGE_METHODS, MULTISIG_CONFIRM_METHODS, MULTISIG_DEPOSIT, MULTISIG_GAS, } from './constants';
import { MultisigStateStatus } from './types';
const { addKey, deleteKey, deployContract, fullAccessKey, functionCall, functionCallAccessKey } = actionCreators;
export class Account2FA extends AccountMultisig {
/********************************
Account2FA has options object where you can provide callbacks for:
- sendCode: how to send the 2FA code in case you don't use NEAR Contract Helper
- getCode: how to get code from user (use this to provide custom UI/UX for prompt of 2FA code)
- onResult: the tx result after it's been confirmed by NEAR Contract Helper
********************************/
sendCode;
getCode;
verifyCode;
onConfirmResult;
helperUrl = 'https://helper.testnet.near.org';
constructor(connection, accountId, options) {
super(connection, accountId, options);
this.helperUrl = 'https://helper.testnet.near.org';
this.helperUrl = options.helperUrl || this.helperUrl;

@@ -42,16 +40,11 @@ this.storage = options.storage;

*/
signAndSendTransaction({ receiverId, actions }) {
const _super = Object.create(null, {
signAndSendTransaction: { get: () => super.signAndSendTransaction }
});
return __awaiter(this, void 0, void 0, function* () {
yield _super.signAndSendTransaction.call(this, { receiverId, actions });
// TODO: Should following override onRequestResult in superclass instead of doing custom signAndSendTransaction?
yield this.sendCode();
const result = yield this.promptAndVerify();
if (this.onConfirmResult) {
yield this.onConfirmResult(result);
}
return result;
});
async signAndSendTransaction({ receiverId, actions }) {
await super.signAndSendTransaction({ receiverId, actions });
// TODO: Should following override onRequestResult in superclass instead of doing custom signAndSendTransaction?
await this.sendCode();
const result = await this.promptAndVerify();
if (this.onConfirmResult) {
await this.onConfirmResult(result);
}
return result;
}

@@ -64,37 +57,34 @@ // default helpers for CH deployments of multisig

*/
deployMultisig(contractBytes) {
const _super = Object.create(null, {
signAndSendTransactionWithAccount: { get: () => super.signAndSendTransactionWithAccount }
});
return __awaiter(this, void 0, void 0, function* () {
const { accountId } = this;
const seedOrLedgerKey = (yield this.getRecoveryMethods()).data
.filter(({ kind, publicKey }) => (kind === 'phrase' || kind === 'ledger') && publicKey !== null)
.map((rm) => rm.publicKey);
const fak2lak = (yield this.getAccessKeys())
.filter(({ public_key, access_key: { permission } }) => permission === 'FullAccess' && !seedOrLedgerKey.includes(public_key))
.map((ak) => ak.public_key)
.map(toPK);
const confirmOnlyKey = toPK((yield this.postSignedJson('/2fa/getAccessKey', { accountId })).publicKey);
const newArgs = Buffer.from(JSON.stringify({ 'num_confirmations': 2 }));
const actions = [
...fak2lak.map((pk) => deleteKey(pk)),
...fak2lak.map((pk) => addKey(pk, functionCallAccessKey(accountId, constants_1.MULTISIG_CHANGE_METHODS, null))),
addKey(confirmOnlyKey, functionCallAccessKey(accountId, constants_1.MULTISIG_CONFIRM_METHODS, null)),
deployContract(contractBytes),
];
const newFunctionCallActionBatch = actions.concat(functionCall('new', newArgs, constants_1.MULTISIG_GAS, constants_1.MULTISIG_DEPOSIT));
utils_1.Logger.log('deploying multisig contract for', accountId);
const { stateStatus: multisigStateStatus } = yield this.checkMultisigCodeAndStateStatus(contractBytes);
switch (multisigStateStatus) {
case types_2.MultisigStateStatus.STATE_NOT_INITIALIZED:
return yield _super.signAndSendTransactionWithAccount.call(this, accountId, newFunctionCallActionBatch);
case types_2.MultisigStateStatus.VALID_STATE:
return yield _super.signAndSendTransactionWithAccount.call(this, accountId, actions);
case types_2.MultisigStateStatus.INVALID_STATE:
throw new types_1.TypedError(`Can not deploy a contract to account ${this.accountId} on network ${this.connection.networkId}, the account has existing state.`, 'ContractHasExistingState');
default:
throw new types_1.TypedError(`Can not deploy a contract to account ${this.accountId} on network ${this.connection.networkId}, the account state could not be verified.`, 'ContractStateUnknown');
}
});
async deployMultisig(contractBytes) {
const { accountId } = this;
const seedOrLedgerKey = (await this.getRecoveryMethods()).data
// @ts-ignore
.filter(({ kind, publicKey }) => (kind === 'phrase' || kind === 'ledger') && publicKey !== null)
.map((rm) => rm.publicKey);
const fak2lak = (await this.getAccessKeys())
.filter(({ public_key, access_key: { permission } }) => permission === 'FullAccess' && !seedOrLedgerKey.includes(public_key))
.map((ak) => ak.public_key)
.map(toPK);
// @ts-ignore
const confirmOnlyKey = toPK((await this.postSignedJson('/2fa/getAccessKey', { accountId })).publicKey);
const newArgs = Buffer.from(JSON.stringify({ 'num_confirmations': 2 }));
const actions = [
...fak2lak.map((pk) => deleteKey(pk)),
...fak2lak.map((pk) => addKey(pk, functionCallAccessKey(accountId, MULTISIG_CHANGE_METHODS, null))),
addKey(confirmOnlyKey, functionCallAccessKey(accountId, MULTISIG_CONFIRM_METHODS, null)),
deployContract(contractBytes),
];
const newFunctionCallActionBatch = actions.concat(functionCall('new', newArgs, MULTISIG_GAS, MULTISIG_DEPOSIT));
Logger.log('deploying multisig contract for', accountId);
const { stateStatus: multisigStateStatus } = await this.checkMultisigCodeAndStateStatus(contractBytes);
switch (multisigStateStatus) {
case MultisigStateStatus.STATE_NOT_INITIALIZED:
return await super.signAndSendTransactionWithAccount(accountId, newFunctionCallActionBatch);
case MultisigStateStatus.VALID_STATE:
return await super.signAndSendTransactionWithAccount(accountId, actions);
case MultisigStateStatus.INVALID_STATE:
throw new TypedError(`Can not deploy a contract to account ${this.accountId} on network ${this.connection.networkId}, the account has existing state.`, 'ContractHasExistingState');
default:
throw new TypedError(`Can not deploy a contract to account ${this.accountId} on network ${this.connection.networkId}, the account state could not be verified.`, 'ContractStateUnknown');
}
}

@@ -108,21 +98,19 @@ /**

*/
disableWithFAK({ contractBytes, cleanupContractBytes }) {
return __awaiter(this, void 0, void 0, function* () {
let cleanupActions = [];
if (cleanupContractBytes) {
yield this.deleteAllRequests().catch(e => e);
cleanupActions = yield this.get2faDisableCleanupActions(cleanupContractBytes);
}
const keyConversionActions = yield this.get2faDisableKeyConversionActions();
const actions = [
...cleanupActions,
...keyConversionActions,
deployContract(contractBytes)
];
const accessKeyInfo = yield this.findAccessKey(this.accountId, actions);
if (accessKeyInfo && accessKeyInfo.accessKey && accessKeyInfo.accessKey.permission !== 'FullAccess') {
throw new types_1.TypedError('No full access key found in keystore. Unable to bypass multisig', 'NoFAKFound');
}
return this.signAndSendTransactionWithAccount(this.accountId, actions);
});
async disableWithFAK({ contractBytes, cleanupContractBytes }) {
let cleanupActions = [];
if (cleanupContractBytes) {
await this.deleteAllRequests().catch(e => e);
cleanupActions = await this.get2faDisableCleanupActions(cleanupContractBytes);
}
const keyConversionActions = await this.get2faDisableKeyConversionActions();
const actions = [
...cleanupActions,
...keyConversionActions,
deployContract(contractBytes)
];
const accessKeyInfo = await this.findAccessKey(this.accountId, actions);
if (accessKeyInfo && accessKeyInfo.accessKey && accessKeyInfo.accessKey.permission !== 'FullAccess') {
throw new TypedError('No full access key found in keystore. Unable to bypass multisig', 'NoFAKFound');
}
return this.signAndSendTransactionWithAccount(this.accountId, actions);
}

@@ -134,19 +122,17 @@ /**

*/
get2faDisableCleanupActions(cleanupContractBytes) {
return __awaiter(this, void 0, void 0, function* () {
const currentAccountState = yield this.viewState('').catch(error => {
const cause = error.cause && error.cause.name;
if (cause == 'NO_CONTRACT_CODE') {
return [];
}
throw cause == 'TOO_LARGE_CONTRACT_STATE'
? new types_1.TypedError(`Can not deploy a contract to account ${this.accountId} on network ${this.connection.networkId}, the account has existing state.`, 'ContractHasExistingState')
: error;
});
const currentAccountStateKeys = currentAccountState.map(({ key }) => key.toString('base64'));
return currentAccountState.length ? [
deployContract(cleanupContractBytes),
functionCall('clean', { keys: currentAccountStateKeys }, constants_1.MULTISIG_GAS, BigInt('0'))
] : [];
async get2faDisableCleanupActions(cleanupContractBytes) {
const currentAccountState = await this.viewState('').catch(error => {
const cause = error.cause && error.cause.name;
if (cause == 'NO_CONTRACT_CODE') {
return [];
}
throw cause == 'TOO_LARGE_CONTRACT_STATE'
? new TypedError(`Can not deploy a contract to account ${this.accountId} on network ${this.connection.networkId}, the account has existing state.`, 'ContractHasExistingState')
: error;
});
const currentAccountStateKeys = currentAccountState.map(({ key }) => key.toString('base64'));
return currentAccountState.length ? [
deployContract(cleanupContractBytes),
functionCall('clean', { keys: currentAccountStateKeys }, MULTISIG_GAS, 0n)
] : [];
}

@@ -157,21 +143,20 @@ /**

*/
get2faDisableKeyConversionActions() {
return __awaiter(this, void 0, void 0, function* () {
const { accountId } = this;
const accessKeys = yield this.getAccessKeys();
const lak2fak = accessKeys
.filter(({ access_key }) => access_key.permission !== 'FullAccess')
.filter(({ access_key }) => {
const perm = access_key.permission.FunctionCall;
return perm.receiver_id === accountId &&
perm.method_names.length === 4 &&
perm.method_names.includes('add_request_and_confirm');
});
const confirmOnlyKey = crypto_1.PublicKey.from((yield this.postSignedJson('/2fa/getAccessKey', { accountId })).publicKey);
return [
deleteKey(confirmOnlyKey),
...lak2fak.map(({ public_key }) => deleteKey(crypto_1.PublicKey.from(public_key))),
...lak2fak.map(({ public_key }) => addKey(crypto_1.PublicKey.from(public_key), fullAccessKey()))
];
async get2faDisableKeyConversionActions() {
const { accountId } = this;
const accessKeys = await this.getAccessKeys();
const lak2fak = accessKeys
.filter(({ access_key }) => access_key.permission !== 'FullAccess')
.filter(({ access_key }) => {
const perm = access_key.permission.FunctionCall;
return perm.receiver_id === accountId &&
perm.method_names.length === 4 &&
perm.method_names.includes('add_request_and_confirm');
});
// @ts-ignore
const confirmOnlyKey = PublicKey.from((await this.postSignedJson('/2fa/getAccessKey', { accountId })).publicKey);
return [
deleteKey(confirmOnlyKey),
...lak2fak.map(({ public_key }) => deleteKey(PublicKey.from(public_key))),
...lak2fak.map(({ public_key }) => addKey(PublicKey.from(public_key), fullAccessKey()))
];
}

@@ -184,27 +169,25 @@ /**

*/
disable(contractBytes, cleanupContractBytes) {
return __awaiter(this, void 0, void 0, function* () {
const { stateStatus } = yield this.checkMultisigCodeAndStateStatus();
if (stateStatus !== types_2.MultisigStateStatus.VALID_STATE && stateStatus !== types_2.MultisigStateStatus.STATE_NOT_INITIALIZED) {
throw new types_1.TypedError(`Can not deploy a contract to account ${this.accountId} on network ${this.connection.networkId}, the account state could not be verified.`, 'ContractStateUnknown');
async disable(contractBytes, cleanupContractBytes) {
const { stateStatus } = await this.checkMultisigCodeAndStateStatus();
if (stateStatus !== MultisigStateStatus.VALID_STATE && stateStatus !== MultisigStateStatus.STATE_NOT_INITIALIZED) {
throw new TypedError(`Can not deploy a contract to account ${this.accountId} on network ${this.connection.networkId}, the account state could not be verified.`, 'ContractStateUnknown');
}
let deleteAllRequestsError;
await this.deleteAllRequests().catch(e => deleteAllRequestsError = e);
const cleanupActions = await this.get2faDisableCleanupActions(cleanupContractBytes).catch(e => {
if (e.type === 'ContractHasExistingState') {
throw deleteAllRequestsError || e;
}
let deleteAllRequestsError;
yield this.deleteAllRequests().catch(e => deleteAllRequestsError = e);
const cleanupActions = yield this.get2faDisableCleanupActions(cleanupContractBytes).catch(e => {
if (e.type === 'ContractHasExistingState') {
throw deleteAllRequestsError || e;
}
throw e;
});
const actions = [
...cleanupActions,
...(yield this.get2faDisableKeyConversionActions()),
deployContract(contractBytes),
];
utils_1.Logger.log('disabling 2fa for', this.accountId);
return yield this.signAndSendTransaction({
receiverId: this.accountId,
actions
});
throw e;
});
const actions = [
...cleanupActions,
...(await this.get2faDisableKeyConversionActions()),
deployContract(contractBytes),
];
Logger.log('disabling 2fa for', this.accountId);
return await this.signAndSendTransaction({
receiverId: this.accountId,
actions
});
}

@@ -215,19 +198,15 @@ /**

*/
sendCodeDefault() {
return __awaiter(this, void 0, void 0, function* () {
const { accountId } = this;
const { requestId } = this.getRequest();
const method = yield this.get2faMethod();
yield this.postSignedJson('/2fa/send', {
accountId,
method,
requestId,
});
return requestId;
async sendCodeDefault() {
const { accountId } = this;
const { requestId } = this.getRequest();
const method = await this.get2faMethod();
await this.postSignedJson('/2fa/send', {
accountId,
method,
requestId,
});
return requestId;
}
getCodeDefault() {
return __awaiter(this, void 0, void 0, function* () {
throw new Error('There is no getCode callback provided. Please provide your own in AccountMultisig constructor options. It has a parameter method where method.kind is "email" or "phone".');
});
async getCodeDefault() {
throw new Error('There is no getCode callback provided. Please provide your own in AccountMultisig constructor options. It has a parameter method where method.kind is "email" or "phone".');
}

@@ -238,19 +217,17 @@ /**

*/
promptAndVerify() {
return __awaiter(this, void 0, void 0, function* () {
const method = yield this.get2faMethod();
const securityCode = yield this.getCode(method);
try {
const result = yield this.verifyCode(securityCode);
// TODO: Parse error from result for real (like in normal account.signAndSendTransaction)
return result;
async promptAndVerify() {
const method = await this.get2faMethod();
const securityCode = await this.getCode(method);
try {
const result = await this.verifyCode(securityCode);
// TODO: Parse error from result for real (like in normal account.signAndSendTransaction)
return result;
}
catch (e) {
Logger.warn('Error validating security code:', e);
if (e.toString().includes('invalid 2fa code provided') || e.toString().includes('2fa code not valid')) {
return await this.promptAndVerify();
}
catch (e) {
utils_1.Logger.warn('Error validating security code:', e);
if (e.toString().includes('invalid 2fa code provided') || e.toString().includes('2fa code not valid')) {
return yield this.promptAndVerify();
}
throw e;
}
});
throw e;
}
}

@@ -262,15 +239,13 @@ /**

*/
verifyCodeDefault(securityCode) {
return __awaiter(this, void 0, void 0, function* () {
const { accountId } = this;
const request = this.getRequest();
if (!request) {
throw new Error('no request pending');
}
const { requestId } = request;
return yield this.postSignedJson('/2fa/verify', {
accountId,
securityCode,
requestId
});
async verifyCodeDefault(securityCode) {
const { accountId } = this;
const request = this.getRequest();
if (!request) {
throw new Error('no request pending');
}
const { requestId } = request;
return await this.postSignedJson('/2fa/verify', {
accountId,
securityCode,
requestId
});

@@ -282,10 +257,8 @@ }

*/
getRecoveryMethods() {
return __awaiter(this, void 0, void 0, function* () {
const { accountId } = this;
return {
accountId,
data: yield this.postSignedJson('/account/recoveryMethods', { accountId })
};
});
async getRecoveryMethods() {
const { accountId } = this;
return {
accountId,
data: await this.postSignedJson('/account/recoveryMethods', { accountId })
};
}

@@ -296,13 +269,14 @@ /**

*/
get2faMethod() {
return __awaiter(this, void 0, void 0, function* () {
let { data } = yield this.getRecoveryMethods();
if (data && data.length) {
data = data.find((m) => m.kind.indexOf('2fa-') === 0);
}
if (!data)
return null;
const { kind, detail } = data;
return { kind, detail };
});
async get2faMethod() {
let { data } = await this.getRecoveryMethods();
// @ts-ignore
if (data && data.length) {
// @ts-ignore
data = data.find((m) => m.kind.indexOf('2fa-') === 0);
}
if (!data)
return null;
// @ts-ignore
const { kind, detail } = data;
return { kind, detail };
}

@@ -313,11 +287,9 @@ /**

*/
signatureFor() {
return __awaiter(this, void 0, void 0, function* () {
const { accountId } = this;
const block = yield this.connection.provider.block({ finality: 'final' });
const blockNumber = block.header.height.toString();
const signed = yield this.connection.signer.signMessage(Buffer.from(blockNumber), accountId, this.connection.networkId);
const blockNumberSignature = Buffer.from(signed.signature).toString('base64');
return { blockNumber, blockNumberSignature };
});
async signatureFor() {
const { accountId } = this;
const block = await this.connection.provider.block({ finality: 'final' });
const blockNumber = block.header.height.toString();
const signed = await this.connection.signer.signMessage(Buffer.from(blockNumber), accountId, this.connection.networkId);
const blockNumberSignature = Buffer.from(signed.signature).toString('base64');
return { blockNumber, blockNumberSignature };
}

@@ -330,10 +302,13 @@ /**

*/
postSignedJson(path, body) {
return __awaiter(this, void 0, void 0, function* () {
return yield (0, providers_1.fetchJson)(this.helperUrl + path, JSON.stringify(Object.assign(Object.assign({}, body), (yield this.signatureFor()))));
async postSignedJson(path, body) {
return await unfetch(this.helperUrl + path, {
body: JSON.stringify({
...body,
...(await this.signatureFor()),
}),
method: 'POST',
});
}
}
exports.Account2FA = Account2FA;
// helpers
const toPK = (pk) => crypto_1.PublicKey.from(pk);
const toPK = (pk) => PublicKey.from(pk);

@@ -1,21 +0,10 @@

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
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) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UrlAccountCreator = exports.LocalAccountCreator = exports.AccountCreator = void 0;
const providers_1 = require("@near-js/providers");
import unfetch from 'isomorphic-unfetch';
/**
* Account creator provides an interface for implementations to actually create accounts
*/
class AccountCreator {
export class AccountCreator {
}
exports.AccountCreator = AccountCreator;
class LocalAccountCreator extends AccountCreator {
export class LocalAccountCreator extends AccountCreator {
masterAccount;
initialBalance;
constructor(masterAccount, initialBalance) {

@@ -32,10 +21,9 @@ super();

*/
createAccount(newAccountId, publicKey) {
return __awaiter(this, void 0, void 0, function* () {
yield this.masterAccount.createAccount(newAccountId, publicKey, this.initialBalance);
});
async createAccount(newAccountId, publicKey) {
await this.masterAccount.createAccount(newAccountId, publicKey, this.initialBalance);
}
}
exports.LocalAccountCreator = LocalAccountCreator;
class UrlAccountCreator extends AccountCreator {
export class UrlAccountCreator extends AccountCreator {
connection;
helperUrl;
constructor(connection, helperUrl) {

@@ -53,8 +41,8 @@ super();

*/
createAccount(newAccountId, publicKey) {
return __awaiter(this, void 0, void 0, function* () {
yield (0, providers_1.fetchJson)(`${this.helperUrl}/account`, JSON.stringify({ newAccountId, newAccountPublicKey: publicKey.toString() }));
async createAccount(newAccountId, publicKey) {
await unfetch(`${this.helperUrl}/account`, {
body: JSON.stringify({ newAccountId, newAccountPublicKey: publicKey.toString() }),
method: 'POST',
});
}
}
exports.UrlAccountCreator = UrlAccountCreator;

@@ -1,19 +0,7 @@

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
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) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AccountMultisig = void 0;
const transactions_1 = require("@near-js/transactions");
const utils_1 = require("@near-js/utils");
const account_1 = require("./account");
const constants_1 = require("./constants");
const types_1 = require("./types");
const { deployContract, functionCall } = transactions_1.actionCreators;
import { actionCreators } from '@near-js/transactions';
import { Logger } from '@near-js/utils';
import { Account } from './account';
import { MULTISIG_ALLOWANCE, MULTISIG_CHANGE_METHODS, MULTISIG_DEPOSIT, MULTISIG_GAS, MULTISIG_STORAGE_KEY, } from './constants';
import { MultisigDeleteRequestRejectionError, MultisigStateStatus } from './types';
const { deployContract, functionCall } = actionCreators;
var MultisigCodeStatus;

@@ -27,5 +15,7 @@ (function (MultisigCodeStatus) {

const storageFallback = {
[constants_1.MULTISIG_STORAGE_KEY]: null
[MULTISIG_STORAGE_KEY]: null
};
class AccountMultisig extends account_1.Account {
export class AccountMultisig extends Account {
storage;
onAddRequestResult;
/**

@@ -50,9 +40,4 @@ * Constructs an instance of the `AccountMultisig` class.

*/
signAndSendTransactionWithAccount(receiverId, actions) {
const _super = Object.create(null, {
signAndSendTransaction: { get: () => super.signAndSendTransaction }
});
return __awaiter(this, void 0, void 0, function* () {
return _super.signAndSendTransaction.call(this, { receiverId, actions });
});
async signAndSendTransactionWithAccount(receiverId, actions) {
return super.signAndSendTransaction({ receiverId, actions });
}

@@ -66,50 +51,45 @@ /**

*/
signAndSendTransaction({ receiverId, actions }) {
const _super = Object.create(null, {
signAndSendTransaction: { get: () => super.signAndSendTransaction }
});
return __awaiter(this, void 0, void 0, function* () {
const { accountId } = this;
const args = Buffer.from(JSON.stringify({
request: {
receiver_id: receiverId,
actions: convertActions(actions, accountId, receiverId)
}
}));
let result;
try {
result = yield _super.signAndSendTransaction.call(this, {
receiverId: accountId,
actions: [
functionCall('add_request_and_confirm', args, constants_1.MULTISIG_GAS, constants_1.MULTISIG_DEPOSIT)
]
});
async signAndSendTransaction({ receiverId, actions }) {
const { accountId } = this;
const args = Buffer.from(JSON.stringify({
request: {
receiver_id: receiverId,
actions: convertActions(actions, accountId, receiverId)
}
catch (e) {
if (e.toString().includes('Account has too many active requests. Confirm or delete some')) {
yield this.deleteUnconfirmedRequests();
return yield this.signAndSendTransaction({ receiverId, actions });
}
throw e;
}
// TODO: Are following even needed? Seems like it throws on error already
if (!result.status) {
throw new Error('Request failed');
}
const status = Object.assign({}, result.status);
if (!status.SuccessValue || typeof status.SuccessValue !== 'string') {
throw new Error('Request failed');
}
this.setRequest({
accountId,
actions,
requestId: parseInt(Buffer.from(status.SuccessValue, 'base64').toString('ascii'), 10)
}));
let result;
try {
result = await super.signAndSendTransaction({
receiverId: accountId,
actions: [
functionCall('add_request_and_confirm', args, MULTISIG_GAS, MULTISIG_DEPOSIT)
]
});
if (this.onAddRequestResult) {
yield this.onAddRequestResult(result);
}
catch (e) {
if (e.toString().includes('Account has too many active requests. Confirm or delete some')) {
await this.deleteUnconfirmedRequests();
return await this.signAndSendTransaction({ receiverId, actions });
}
// NOTE there is no await on purpose to avoid blocking for 2fa
this.deleteUnconfirmedRequests();
return result;
throw e;
}
// TODO: Are following even needed? Seems like it throws on error already
if (!result.status) {
throw new Error('Request failed');
}
const status = { ...result.status };
if (!status.SuccessValue || typeof status.SuccessValue !== 'string') {
throw new Error('Request failed');
}
this.setRequest({
accountId,
actions,
requestId: parseInt(Buffer.from(status.SuccessValue, 'base64').toString('ascii'), 10)
});
if (this.onAddRequestResult) {
await this.onAddRequestResult(result);
}
// NOTE there is no await on purpose to avoid blocking for 2fa
this.deleteUnconfirmedRequests();
return result;
}

@@ -123,40 +103,35 @@ /**

*/
checkMultisigCodeAndStateStatus(contractBytes) {
const _super = Object.create(null, {
signAndSendTransaction: { get: () => super.signAndSendTransaction }
});
return __awaiter(this, void 0, void 0, function* () {
const u32_max = 4294967295;
const validCodeStatusIfNoDeploy = contractBytes ? MultisigCodeStatus.UNKNOWN_CODE : MultisigCodeStatus.VALID_CODE;
try {
if (contractBytes) {
yield _super.signAndSendTransaction.call(this, {
receiverId: this.accountId, actions: [
deployContract(contractBytes),
functionCall('delete_request', { request_id: u32_max }, constants_1.MULTISIG_GAS, constants_1.MULTISIG_DEPOSIT)
]
});
}
else {
yield this.deleteRequest(u32_max);
}
return { codeStatus: MultisigCodeStatus.VALID_CODE, stateStatus: types_1.MultisigStateStatus.VALID_STATE };
async checkMultisigCodeAndStateStatus(contractBytes) {
const u32_max = 4_294_967_295;
const validCodeStatusIfNoDeploy = contractBytes ? MultisigCodeStatus.UNKNOWN_CODE : MultisigCodeStatus.VALID_CODE;
try {
if (contractBytes) {
await super.signAndSendTransaction({
receiverId: this.accountId, actions: [
deployContract(contractBytes),
functionCall('delete_request', { request_id: u32_max }, MULTISIG_GAS, MULTISIG_DEPOSIT)
]
});
}
catch (e) {
if (new RegExp(types_1.MultisigDeleteRequestRejectionError.CANNOT_DESERIALIZE_STATE).test(e && e.kind && e.kind.ExecutionError)) {
return { codeStatus: validCodeStatusIfNoDeploy, stateStatus: types_1.MultisigStateStatus.INVALID_STATE };
}
else if (new RegExp(types_1.MultisigDeleteRequestRejectionError.MULTISIG_NOT_INITIALIZED).test(e && e.kind && e.kind.ExecutionError)) {
return { codeStatus: validCodeStatusIfNoDeploy, stateStatus: types_1.MultisigStateStatus.STATE_NOT_INITIALIZED };
}
else if (new RegExp(types_1.MultisigDeleteRequestRejectionError.NO_SUCH_REQUEST).test(e && e.kind && e.kind.ExecutionError)) {
return { codeStatus: validCodeStatusIfNoDeploy, stateStatus: types_1.MultisigStateStatus.VALID_STATE };
}
else if (new RegExp(types_1.MultisigDeleteRequestRejectionError.METHOD_NOT_FOUND).test(e && e.message)) {
// not reachable if transaction included a deploy
return { codeStatus: MultisigCodeStatus.INVALID_CODE, stateStatus: types_1.MultisigStateStatus.UNKNOWN_STATE };
}
throw e;
else {
await this.deleteRequest(u32_max);
}
});
return { codeStatus: MultisigCodeStatus.VALID_CODE, stateStatus: MultisigStateStatus.VALID_STATE };
}
catch (e) {
if (new RegExp(MultisigDeleteRequestRejectionError.CANNOT_DESERIALIZE_STATE).test(e && e.kind && e.kind.ExecutionError)) {
return { codeStatus: validCodeStatusIfNoDeploy, stateStatus: MultisigStateStatus.INVALID_STATE };
}
else if (new RegExp(MultisigDeleteRequestRejectionError.MULTISIG_NOT_INITIALIZED).test(e && e.kind && e.kind.ExecutionError)) {
return { codeStatus: validCodeStatusIfNoDeploy, stateStatus: MultisigStateStatus.STATE_NOT_INITIALIZED };
}
else if (new RegExp(MultisigDeleteRequestRejectionError.NO_SUCH_REQUEST).test(e && e.kind && e.kind.ExecutionError)) {
return { codeStatus: validCodeStatusIfNoDeploy, stateStatus: MultisigStateStatus.VALID_STATE };
}
else if (new RegExp(MultisigDeleteRequestRejectionError.METHOD_NOT_FOUND).test(e && e.message)) {
// not reachable if transaction included a deploy
return { codeStatus: MultisigCodeStatus.INVALID_CODE, stateStatus: MultisigStateStatus.UNKNOWN_STATE };
}
throw e;
}
}

@@ -171,3 +146,3 @@ /**

receiverId: this.accountId,
actions: [functionCall('delete_request', { request_id }, constants_1.MULTISIG_GAS, constants_1.MULTISIG_DEPOSIT)]
actions: [functionCall('delete_request', { request_id }, MULTISIG_GAS, MULTISIG_DEPOSIT)]
});

@@ -179,9 +154,7 @@ }

*/
deleteAllRequests() {
return __awaiter(this, void 0, void 0, function* () {
const request_ids = yield this.getRequestIds();
if (request_ids.length) {
yield Promise.all(request_ids.map((id) => this.deleteRequest(id)));
}
});
async deleteAllRequests() {
const request_ids = await this.getRequestIds();
if (request_ids.length) {
await Promise.all(request_ids.map((id) => this.deleteRequest(id)));
}
}

@@ -192,36 +165,29 @@ /**

*/
deleteUnconfirmedRequests() {
const _super = Object.create(null, {
signAndSendTransaction: { get: () => super.signAndSendTransaction }
});
return __awaiter(this, void 0, void 0, function* () {
// TODO: Delete in batch, don't delete unexpired
// TODO: Delete in batch, don't delete unexpired (can reduce gas usage dramatically)
const request_ids = yield this.getRequestIds();
const { requestId } = this.getRequest();
for (const requestIdToDelete of request_ids) {
if (requestIdToDelete == requestId) {
continue;
}
try {
yield _super.signAndSendTransaction.call(this, {
receiverId: this.accountId,
actions: [functionCall('delete_request', { request_id: requestIdToDelete }, constants_1.MULTISIG_GAS, constants_1.MULTISIG_DEPOSIT)]
});
}
catch (e) {
utils_1.Logger.warn('Attempt to delete an earlier request before 15 minutes failed. Will try again.');
}
async deleteUnconfirmedRequests() {
// TODO: Delete in batch, don't delete unexpired
// TODO: Delete in batch, don't delete unexpired (can reduce gas usage dramatically)
const request_ids = await this.getRequestIds();
const { requestId } = this.getRequest();
for (const requestIdToDelete of request_ids) {
if (requestIdToDelete == requestId) {
continue;
}
});
try {
await super.signAndSendTransaction({
receiverId: this.accountId,
actions: [functionCall('delete_request', { request_id: requestIdToDelete }, MULTISIG_GAS, MULTISIG_DEPOSIT)]
});
}
catch (e) {
Logger.warn('Attempt to delete an earlier request before 15 minutes failed. Will try again.');
}
}
}
// helpers
getRequestIds() {
return __awaiter(this, void 0, void 0, function* () {
// TODO: Read requests from state to allow filtering by expiration time
// TODO: https://github.com/near/core-contracts/blob/305d1db4f4f2cf5ce4c1ef3479f7544957381f11/multisig/src/lib.rs#L84
return this.viewFunction({
contractId: this.accountId,
methodName: 'list_request_ids',
});
async getRequestIds() {
// TODO: Read requests from state to allow filtering by expiration time
// TODO: https://github.com/near/core-contracts/blob/305d1db4f4f2cf5ce4c1ef3479f7544957381f11/multisig/src/lib.rs#L84
return this.viewFunction({
contractId: this.accountId,
methodName: 'list_request_ids',
});

@@ -231,14 +197,13 @@ }

if (this.storage) {
return JSON.parse(this.storage.getItem(constants_1.MULTISIG_STORAGE_KEY) || '{}');
return JSON.parse(this.storage.getItem(MULTISIG_STORAGE_KEY) || '{}');
}
return storageFallback[constants_1.MULTISIG_STORAGE_KEY];
return storageFallback[MULTISIG_STORAGE_KEY];
}
setRequest(data) {
if (this.storage) {
return this.storage.setItem(constants_1.MULTISIG_STORAGE_KEY, JSON.stringify(data));
return this.storage.setItem(MULTISIG_STORAGE_KEY, JSON.stringify(data));
}
storageFallback[constants_1.MULTISIG_STORAGE_KEY] = data;
storageFallback[MULTISIG_STORAGE_KEY] = data;
}
}
exports.AccountMultisig = AccountMultisig;
const convertPKForContract = (pk) => pk.toString().replace('ed25519:', '');

@@ -263,4 +228,4 @@ const convertActions = (actions, accountId, receiverId) => actions.map((a) => {

receiver_id: accountId,
allowance: constants_1.MULTISIG_ALLOWANCE.toString(),
method_names: constants_1.MULTISIG_CHANGE_METHODS,
allowance: MULTISIG_ALLOWANCE.toString(),
method_names: MULTISIG_CHANGE_METHODS,
};

@@ -267,0 +232,0 @@ }

@@ -1,20 +0,8 @@

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
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) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Account = void 0;
const crypto_1 = require("@near-js/crypto");
const providers_1 = require("@near-js/providers");
const transactions_1 = require("@near-js/transactions");
const types_1 = require("@near-js/types");
const utils_1 = require("@near-js/utils");
const utils_2 = require("./utils");
const { addKey, createAccount, deleteAccount, deleteKey, deployContract, fullAccessKey, functionCall, functionCallAccessKey, stake, transfer, } = transactions_1.actionCreators;
import { PublicKey } from '@near-js/crypto';
import { exponentialBackoff } from '@near-js/providers';
import { actionCreators, buildDelegateAction, signDelegateAction, signTransaction, stringifyJsonOrBytes, } from '@near-js/transactions';
import { PositionalArgsError, TypedError, ErrorContext, } from '@near-js/types';
import { baseDecode, baseEncode, Logger, parseResultError, DEFAULT_FUNCTION_CALL_GAS, printTxOutcomeLogsAndFailures, } from '@near-js/utils';
import { viewFunction, viewState } from './utils';
const { addKey, createAccount, deleteAccount, deleteKey, deployContract, fullAccessKey, functionCall, functionCallAccessKey, stake, transfer, } = actionCreators;
// Default number of retries with different nonce before giving up on a transaction.

@@ -29,6 +17,6 @@ const TX_NONCE_RETRY_NUMBER = 12;

*/
class Account {
export class Account {
connection;
accountId;
constructor(connection, accountId) {
/** @hidden */
this.accessKeyByPublicKeyCache = {};
this.connection = connection;

@@ -44,9 +32,7 @@ this.accountId = accountId;

*/
state() {
return __awaiter(this, void 0, void 0, function* () {
return this.connection.provider.query({
request_type: 'view_account',
account_id: this.accountId,
finality: 'optimistic'
});
async state() {
return this.connection.provider.query({
request_type: 'view_account',
account_id: this.accountId,
finality: 'optimistic'
});

@@ -60,14 +46,12 @@ }

*/
signTransaction(receiverId, actions) {
return __awaiter(this, void 0, void 0, function* () {
const accessKeyInfo = yield this.findAccessKey(receiverId, actions);
if (!accessKeyInfo) {
throw new types_1.TypedError(`Can not sign transactions for account ${this.accountId} on network ${this.connection.networkId}, no matching key pair exists for this account`, 'KeyNotFound');
}
const { accessKey } = accessKeyInfo;
const block = yield this.connection.provider.block({ finality: 'final' });
const blockHash = block.header.hash;
const nonce = accessKey.nonce + BigInt(1);
return yield (0, transactions_1.signTransaction)(receiverId, nonce, actions, (0, utils_1.baseDecode)(blockHash), this.connection.signer, this.accountId, this.connection.networkId);
});
async signTransaction(receiverId, actions) {
const accessKeyInfo = await this.findAccessKey(receiverId, actions);
if (!accessKeyInfo) {
throw new TypedError(`Can not sign transactions for account ${this.accountId} on network ${this.connection.networkId}, no matching key pair exists for this account`, 'KeyNotFound');
}
const { accessKey } = accessKeyInfo;
const block = await this.connection.provider.block({ finality: 'final' });
const blockHash = block.header.hash;
const nonce = accessKey.nonce + 1n;
return await signTransaction(receiverId, nonce, actions, baseDecode(blockHash), this.connection.signer, this.accountId, this.connection.networkId);
}

@@ -84,45 +68,45 @@ /**

*/
signAndSendTransaction({ receiverId, actions, returnError }) {
return __awaiter(this, void 0, void 0, function* () {
let txHash, signedTx;
// TODO: TX_NONCE (different constants for different uses of exponentialBackoff?)
const result = yield (0, providers_1.exponentialBackoff)(TX_NONCE_RETRY_WAIT, TX_NONCE_RETRY_NUMBER, TX_NONCE_RETRY_WAIT_BACKOFF, () => __awaiter(this, void 0, void 0, function* () {
[txHash, signedTx] = yield this.signTransaction(receiverId, actions);
const publicKey = signedTx.transaction.publicKey;
try {
return yield this.connection.provider.sendTransaction(signedTx);
}
catch (error) {
if (error.type === 'InvalidNonce') {
utils_1.Logger.warn(`Retrying transaction ${receiverId}:${(0, utils_1.baseEncode)(txHash)} with new nonce.`);
delete this.accessKeyByPublicKeyCache[publicKey.toString()];
return null;
}
if (error.type === 'Expired') {
utils_1.Logger.warn(`Retrying transaction ${receiverId}:${(0, utils_1.baseEncode)(txHash)} due to expired block hash`);
return null;
}
error.context = new types_1.ErrorContext((0, utils_1.baseEncode)(txHash));
throw error;
}
}));
if (!result) {
// TODO: This should have different code actually, as means "transaction not submitted for sure"
throw new types_1.TypedError('nonce retries exceeded for transaction. This usually means there are too many parallel requests with the same access key.', 'RetriesExceeded');
async signAndSendTransaction({ receiverId, actions, returnError }) {
let txHash, signedTx;
// TODO: TX_NONCE (different constants for different uses of exponentialBackoff?)
const result = await exponentialBackoff(TX_NONCE_RETRY_WAIT, TX_NONCE_RETRY_NUMBER, TX_NONCE_RETRY_WAIT_BACKOFF, async () => {
[txHash, signedTx] = await this.signTransaction(receiverId, actions);
const publicKey = signedTx.transaction.publicKey;
try {
return await this.connection.provider.sendTransaction(signedTx);
}
(0, utils_1.printTxOutcomeLogsAndFailures)({ contractId: signedTx.transaction.receiverId, outcome: result });
// Should be falsy if result.status.Failure is null
if (!returnError && typeof result.status === 'object' && typeof result.status.Failure === 'object' && result.status.Failure !== null) {
// if error data has error_message and error_type properties, we consider that node returned an error in the old format
if (result.status.Failure.error_message && result.status.Failure.error_type) {
throw new types_1.TypedError(`Transaction ${result.transaction_outcome.id} failed. ${result.status.Failure.error_message}`, result.status.Failure.error_type);
catch (error) {
if (error.type === 'InvalidNonce') {
Logger.warn(`Retrying transaction ${receiverId}:${baseEncode(txHash)} with new nonce.`);
delete this.accessKeyByPublicKeyCache[publicKey.toString()];
return null;
}
else {
throw (0, utils_1.parseResultError)(result);
if (error.type === 'Expired') {
Logger.warn(`Retrying transaction ${receiverId}:${baseEncode(txHash)} due to expired block hash`);
return null;
}
error.context = new ErrorContext(baseEncode(txHash));
throw error;
}
// TODO: if Tx is Unknown or Started.
return result;
});
if (!result) {
// TODO: This should have different code actually, as means "transaction not submitted for sure"
throw new TypedError('nonce retries exceeded for transaction. This usually means there are too many parallel requests with the same access key.', 'RetriesExceeded');
}
printTxOutcomeLogsAndFailures({ contractId: signedTx.transaction.receiverId, outcome: result });
// Should be falsy if result.status.Failure is null
if (!returnError && typeof result.status === 'object' && typeof result.status.Failure === 'object' && result.status.Failure !== null) {
// if error data has error_message and error_type properties, we consider that node returned an error in the old format
if (result.status.Failure.error_message && result.status.Failure.error_type) {
throw new TypedError(`Transaction ${result.transaction_outcome.id} failed. ${result.status.Failure.error_message}`, result.status.Failure.error_type);
}
else {
throw parseResultError(result);
}
}
// TODO: if Tx is Unknown or Started.
return result;
}
/** @hidden */
accessKeyByPublicKeyCache = {};
/**

@@ -138,39 +122,40 @@ * Finds the {@link AccessKeyView} associated with the accounts {@link PublicKey} stored in the {@link "@near-js/keystores".keystore.KeyStore | Keystore}.

// eslint-disable-next-line @typescript-eslint/no-unused-vars
findAccessKey(receiverId, actions) {
return __awaiter(this, void 0, void 0, function* () {
// TODO: Find matching access key based on transaction (i.e. receiverId and actions)
const publicKey = yield this.connection.signer.getPublicKey(this.accountId, this.connection.networkId);
if (!publicKey) {
throw new types_1.TypedError(`no matching key pair found in ${this.connection.signer}`, 'PublicKeyNotFound');
async findAccessKey(receiverId, actions) {
// TODO: Find matching access key based on transaction (i.e. receiverId and actions)
const publicKey = await this.connection.signer.getPublicKey(this.accountId, this.connection.networkId);
if (!publicKey) {
throw new TypedError(`no matching key pair found in ${this.connection.signer}`, 'PublicKeyNotFound');
}
const cachedAccessKey = this.accessKeyByPublicKeyCache[publicKey.toString()];
if (cachedAccessKey !== undefined) {
return { publicKey, accessKey: cachedAccessKey };
}
try {
const rawAccessKey = await this.connection.provider.query({
request_type: 'view_access_key',
account_id: this.accountId,
public_key: publicKey.toString(),
finality: 'optimistic'
});
// store nonce as BigInt to preserve precision on big number
const accessKey = {
...rawAccessKey,
nonce: BigInt(rawAccessKey.nonce || 0)
};
// this function can be called multiple times and retrieve the same access key
// this checks to see if the access key was already retrieved and cached while
// the above network call was in flight. To keep nonce values in line, we return
// the cached access key.
if (this.accessKeyByPublicKeyCache[publicKey.toString()]) {
return { publicKey, accessKey: this.accessKeyByPublicKeyCache[publicKey.toString()] };
}
const cachedAccessKey = this.accessKeyByPublicKeyCache[publicKey.toString()];
if (cachedAccessKey !== undefined) {
return { publicKey, accessKey: cachedAccessKey };
this.accessKeyByPublicKeyCache[publicKey.toString()] = accessKey;
return { publicKey, accessKey };
}
catch (e) {
if (e.type == 'AccessKeyDoesNotExist') {
return null;
}
try {
const rawAccessKey = yield this.connection.provider.query({
request_type: 'view_access_key',
account_id: this.accountId,
public_key: publicKey.toString(),
finality: 'optimistic'
});
// store nonce as BigInt to preserve precision on big number
const accessKey = Object.assign(Object.assign({}, rawAccessKey), { nonce: BigInt(rawAccessKey.nonce || 0) });
// this function can be called multiple times and retrieve the same access key
// this checks to see if the access key was already retrieved and cached while
// the above network call was in flight. To keep nonce values in line, we return
// the cached access key.
if (this.accessKeyByPublicKeyCache[publicKey.toString()]) {
return { publicKey, accessKey: this.accessKeyByPublicKeyCache[publicKey.toString()] };
}
this.accessKeyByPublicKeyCache[publicKey.toString()] = accessKey;
return { publicKey, accessKey };
}
catch (e) {
if (e.type == 'AccessKeyDoesNotExist') {
return null;
}
throw e;
}
});
throw e;
}
}

@@ -185,12 +170,10 @@ /**

*/
createAndDeployContract(contractId, publicKey, data, amount) {
return __awaiter(this, void 0, void 0, function* () {
const accessKey = fullAccessKey();
yield this.signAndSendTransaction({
receiverId: contractId,
actions: [createAccount(), transfer(amount), addKey(crypto_1.PublicKey.from(publicKey), accessKey), deployContract(data)]
});
const contractAccount = new Account(this.connection, contractId);
return contractAccount;
async createAndDeployContract(contractId, publicKey, data, amount) {
const accessKey = fullAccessKey();
await this.signAndSendTransaction({
receiverId: contractId,
actions: [createAccount(), transfer(amount), addKey(PublicKey.from(publicKey), accessKey), deployContract(data)]
});
const contractAccount = new Account(this.connection, contractId);
return contractAccount;
}

@@ -201,8 +184,6 @@ /**

*/
sendMoney(receiverId, amount) {
return __awaiter(this, void 0, void 0, function* () {
return this.signAndSendTransaction({
receiverId,
actions: [transfer(amount)]
});
async sendMoney(receiverId, amount) {
return this.signAndSendTransaction({
receiverId,
actions: [transfer(amount)]
});

@@ -214,9 +195,7 @@ }

*/
createAccount(newAccountId, publicKey, amount) {
return __awaiter(this, void 0, void 0, function* () {
const accessKey = fullAccessKey();
return this.signAndSendTransaction({
receiverId: newAccountId,
actions: [createAccount(), transfer(amount), addKey(crypto_1.PublicKey.from(publicKey), accessKey)]
});
async createAccount(newAccountId, publicKey, amount) {
const accessKey = fullAccessKey();
return this.signAndSendTransaction({
receiverId: newAccountId,
actions: [createAccount(), transfer(amount), addKey(PublicKey.from(publicKey), accessKey)]
});

@@ -227,9 +206,7 @@ }

*/
deleteAccount(beneficiaryId) {
return __awaiter(this, void 0, void 0, function* () {
utils_1.Logger.log('Deleting an account does not automatically transfer NFTs and FTs to the beneficiary address. Ensure to transfer assets before deleting.');
return this.signAndSendTransaction({
receiverId: this.accountId,
actions: [deleteAccount(beneficiaryId)]
});
async deleteAccount(beneficiaryId) {
Logger.log('Deleting an account does not automatically transfer NFTs and FTs to the beneficiary address. Ensure to transfer assets before deleting.');
return this.signAndSendTransaction({
receiverId: this.accountId,
actions: [deleteAccount(beneficiaryId)]
});

@@ -240,8 +217,6 @@ }

*/
deployContract(data) {
return __awaiter(this, void 0, void 0, function* () {
return this.signAndSendTransaction({
receiverId: this.accountId,
actions: [deployContract(data)]
});
async deployContract(data) {
return this.signAndSendTransaction({
receiverId: this.accountId,
actions: [deployContract(data)]
});

@@ -267,21 +242,19 @@ }

*/
functionCall({ contractId, methodName, args = {}, gas = utils_1.DEFAULT_FUNCTION_CALL_GAS, attachedDeposit, walletMeta, walletCallbackUrl, stringify, jsContract }) {
return __awaiter(this, void 0, void 0, function* () {
this.validateArgs(args);
let functionCallArgs;
if (jsContract) {
const encodedArgs = this.encodeJSContractArgs(contractId, methodName, JSON.stringify(args));
functionCallArgs = ['call_js_contract', encodedArgs, gas, attachedDeposit, null, true];
}
else {
const stringifyArg = stringify === undefined ? transactions_1.stringifyJsonOrBytes : stringify;
functionCallArgs = [methodName, args, gas, attachedDeposit, stringifyArg, false];
}
return this.signAndSendTransaction({
receiverId: jsContract ? this.connection.jsvmAccountId : contractId,
// eslint-disable-next-line prefer-spread
actions: [functionCall.apply(void 0, functionCallArgs)],
walletMeta,
walletCallbackUrl
});
async functionCall({ contractId, methodName, args = {}, gas = DEFAULT_FUNCTION_CALL_GAS, attachedDeposit, walletMeta, walletCallbackUrl, stringify, jsContract }) {
this.validateArgs(args);
let functionCallArgs;
if (jsContract) {
const encodedArgs = this.encodeJSContractArgs(contractId, methodName, JSON.stringify(args));
functionCallArgs = ['call_js_contract', encodedArgs, gas, attachedDeposit, null, true];
}
else {
const stringifyArg = stringify === undefined ? stringifyJsonOrBytes : stringify;
functionCallArgs = [methodName, args, gas, attachedDeposit, stringifyArg, false];
}
return this.signAndSendTransaction({
receiverId: jsContract ? this.connection.jsvmAccountId : contractId,
// eslint-disable-next-line prefer-spread
actions: [functionCall.apply(void 0, functionCallArgs)],
walletMeta,
walletCallbackUrl
});

@@ -297,21 +270,19 @@ }

*/
addKey(publicKey, contractId, methodNames, amount) {
return __awaiter(this, void 0, void 0, function* () {
if (!methodNames) {
methodNames = [];
}
if (!Array.isArray(methodNames)) {
methodNames = [methodNames];
}
let accessKey;
if (!contractId) {
accessKey = fullAccessKey();
}
else {
accessKey = functionCallAccessKey(contractId, methodNames, amount);
}
return this.signAndSendTransaction({
receiverId: this.accountId,
actions: [addKey(crypto_1.PublicKey.from(publicKey), accessKey)]
});
async addKey(publicKey, contractId, methodNames, amount) {
if (!methodNames) {
methodNames = [];
}
if (!Array.isArray(methodNames)) {
methodNames = [methodNames];
}
let accessKey;
if (!contractId) {
accessKey = fullAccessKey();
}
else {
accessKey = functionCallAccessKey(contractId, methodNames, amount);
}
return this.signAndSendTransaction({
receiverId: this.accountId,
actions: [addKey(PublicKey.from(publicKey), accessKey)]
});

@@ -323,8 +294,6 @@ }

*/
deleteKey(publicKey) {
return __awaiter(this, void 0, void 0, function* () {
return this.signAndSendTransaction({
receiverId: this.accountId,
actions: [deleteKey(crypto_1.PublicKey.from(publicKey))]
});
async deleteKey(publicKey) {
return this.signAndSendTransaction({
receiverId: this.accountId,
actions: [deleteKey(PublicKey.from(publicKey))]
});

@@ -338,8 +307,6 @@ }

*/
stake(publicKey, amount) {
return __awaiter(this, void 0, void 0, function* () {
return this.signAndSendTransaction({
receiverId: this.accountId,
actions: [stake(amount, crypto_1.PublicKey.from(publicKey))]
});
async stake(publicKey, amount) {
return this.signAndSendTransaction({
receiverId: this.accountId,
actions: [stake(amount, PublicKey.from(publicKey))]
});

@@ -355,26 +322,24 @@ }

*/
signedDelegate({ actions, blockHeightTtl, receiverId, }) {
return __awaiter(this, void 0, void 0, function* () {
const { provider, signer } = this.connection;
const { header } = yield provider.block({ finality: 'final' });
const { accessKey, publicKey } = yield this.findAccessKey(null, null);
const delegateAction = (0, transactions_1.buildDelegateAction)({
actions,
maxBlockHeight: BigInt(header.height) + BigInt(blockHeightTtl),
nonce: BigInt(accessKey.nonce) + BigInt(1),
publicKey,
receiverId,
senderId: this.accountId,
});
const { signedDelegateAction } = yield (0, transactions_1.signDelegateAction)({
delegateAction,
signer: {
sign: (message) => __awaiter(this, void 0, void 0, function* () {
const { signature } = yield signer.signMessage(message, delegateAction.senderId, this.connection.networkId);
return signature;
}),
}
});
return signedDelegateAction;
async signedDelegate({ actions, blockHeightTtl, receiverId, }) {
const { provider, signer } = this.connection;
const { header } = await provider.block({ finality: 'final' });
const { accessKey, publicKey } = await this.findAccessKey(null, null);
const delegateAction = buildDelegateAction({
actions,
maxBlockHeight: BigInt(header.height) + BigInt(blockHeightTtl),
nonce: BigInt(accessKey.nonce) + 1n,
publicKey,
receiverId,
senderId: this.accountId,
});
const { signedDelegateAction } = await signDelegateAction({
delegateAction,
signer: {
sign: async (message) => {
const { signature } = await signer.signMessage(message, delegateAction.senderId, this.connection.networkId);
return signature;
},
}
});
return signedDelegateAction;
}

@@ -388,3 +353,3 @@ /** @hidden */

if (Array.isArray(args) || typeof args !== 'object') {
throw new types_1.PositionalArgsError();
throw new PositionalArgsError();
}

@@ -406,6 +371,4 @@ }

*/
viewFunction(options) {
return __awaiter(this, void 0, void 0, function* () {
return yield (0, utils_2.viewFunction)(this.connection, options);
});
async viewFunction(options) {
return await viewFunction(this.connection, options);
}

@@ -420,6 +383,4 @@ /**

*/
viewState(prefix, blockQuery = { finality: 'optimistic' }) {
return __awaiter(this, void 0, void 0, function* () {
return yield (0, utils_2.viewState)(this.connection, this.accountId, prefix, blockQuery);
});
async viewState(prefix, blockQuery = { finality: 'optimistic' }) {
return await viewState(this.connection, this.accountId, prefix, blockQuery);
}

@@ -430,13 +391,10 @@ /**

*/
getAccessKeys() {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const response = yield this.connection.provider.query({
request_type: 'view_access_key_list',
account_id: this.accountId,
finality: 'optimistic'
});
// Replace raw nonce into a new BigInt
return (_a = response === null || response === void 0 ? void 0 : response.keys) === null || _a === void 0 ? void 0 : _a.map((key) => (Object.assign(Object.assign({}, key), { access_key: Object.assign(Object.assign({}, key.access_key), { nonce: BigInt(key.access_key.nonce) }) })));
async getAccessKeys() {
const response = await this.connection.provider.query({
request_type: 'view_access_key_list',
account_id: this.accountId,
finality: 'optimistic'
});
// Replace raw nonce into a new BigInt
return response?.keys?.map((key) => ({ ...key, access_key: { ...key.access_key, nonce: BigInt(key.access_key.nonce) } }));
}

@@ -447,19 +405,17 @@ /**

*/
getAccountDetails() {
return __awaiter(this, void 0, void 0, function* () {
// TODO: update the response value to return all the different keys, not just app keys.
// Also if we need this function, or getAccessKeys is good enough.
const accessKeys = yield this.getAccessKeys();
const authorizedApps = accessKeys
.filter(item => item.access_key.permission !== 'FullAccess')
.map(item => {
const perm = item.access_key.permission;
return {
contractId: perm.FunctionCall.receiver_id,
amount: perm.FunctionCall.allowance,
publicKey: item.public_key,
};
});
return { authorizedApps };
async getAccountDetails() {
// TODO: update the response value to return all the different keys, not just app keys.
// Also if we need this function, or getAccessKeys is good enough.
const accessKeys = await this.getAccessKeys();
const authorizedApps = accessKeys
.filter(item => item.access_key.permission !== 'FullAccess')
.map(item => {
const perm = item.access_key.permission;
return {
contractId: perm.FunctionCall.receiver_id,
amount: perm.FunctionCall.allowance,
publicKey: item.public_key,
};
});
return { authorizedApps };
}

@@ -469,18 +425,16 @@ /**

*/
getAccountBalance() {
return __awaiter(this, void 0, void 0, function* () {
const protocolConfig = yield this.connection.provider.experimental_protocolConfig({ finality: 'final' });
const state = yield this.state();
const costPerByte = BigInt(protocolConfig.runtime_config.storage_amount_per_byte);
const stateStaked = BigInt(state.storage_usage) * costPerByte;
const staked = BigInt(state.locked);
const totalBalance = BigInt(state.amount) + staked;
const availableBalance = totalBalance - (staked > stateStaked ? staked : stateStaked);
return {
total: totalBalance.toString(),
stateStaked: stateStaked.toString(),
staked: staked.toString(),
available: availableBalance.toString()
};
});
async getAccountBalance() {
const protocolConfig = await this.connection.provider.experimental_protocolConfig({ finality: 'final' });
const state = await this.state();
const costPerByte = BigInt(protocolConfig.runtime_config.storage_amount_per_byte);
const stateStaked = BigInt(state.storage_usage) * costPerByte;
const staked = BigInt(state.locked);
const totalBalance = BigInt(state.amount) + staked;
const availableBalance = totalBalance - (staked > stateStaked ? staked : stateStaked);
return {
total: totalBalance.toString(),
stateStaked: stateStaked.toString(),
staked: staked.toString(),
available: availableBalance.toString()
};
}

@@ -493,47 +447,54 @@ /**

*/
getActiveDelegatedStakeBalance() {
return __awaiter(this, void 0, void 0, function* () {
const block = yield this.connection.provider.block({ finality: 'final' });
const blockHash = block.header.hash;
const epochId = block.header.epoch_id;
const { current_validators, next_validators, current_proposals } = yield this.connection.provider.validators(epochId);
const pools = new Set();
[...current_validators, ...next_validators, ...current_proposals]
.forEach((validator) => pools.add(validator.account_id));
const uniquePools = [...pools];
const promises = uniquePools
.map((validator) => (this.viewFunction({
contractId: validator,
methodName: 'get_account_total_balance',
args: { account_id: this.accountId },
blockQuery: { blockId: blockHash }
})));
const results = yield Promise.allSettled(promises);
const hasTimeoutError = results.some((result) => {
if (result.status === 'rejected' && result.reason.type === 'TimeoutError') {
return true;
async getActiveDelegatedStakeBalance() {
const block = await this.connection.provider.block({ finality: 'final' });
const blockHash = block.header.hash;
const epochId = block.header.epoch_id;
const { current_validators, next_validators, current_proposals } = await this.connection.provider.validators(epochId);
const pools = new Set();
[...current_validators, ...next_validators, ...current_proposals]
.forEach((validator) => pools.add(validator.account_id));
const uniquePools = [...pools];
const promises = uniquePools
.map((validator) => (this.viewFunction({
contractId: validator,
methodName: 'get_account_total_balance',
args: { account_id: this.accountId },
blockQuery: { blockId: blockHash }
})));
const results = await Promise.allSettled(promises);
const hasTimeoutError = results.some((result) => {
if (result.status === 'rejected' && result.reason.type === 'TimeoutError') {
return true;
}
return false;
});
// When RPC is down and return timeout error, throw error
if (hasTimeoutError) {
throw new Error('Failed to get delegated stake balance');
}
const summary = results.reduce((result, state, index) => {
const validatorId = uniquePools[index];
if (state.status === 'fulfilled') {
const currentBN = BigInt(state.value);
if (currentBN !== 0n) {
return {
...result,
stakedValidators: [...result.stakedValidators, { validatorId, amount: currentBN.toString() }],
total: result.total + currentBN,
};
}
return false;
});
// When RPC is down and return timeout error, throw error
if (hasTimeoutError) {
throw new Error('Failed to get delegated stake balance');
}
const summary = results.reduce((result, state, index) => {
const validatorId = uniquePools[index];
if (state.status === 'fulfilled') {
const currentBN = BigInt(state.value);
if (currentBN !== BigInt(0)) {
return Object.assign(Object.assign({}, result), { stakedValidators: [...result.stakedValidators, { validatorId, amount: currentBN.toString() }], total: result.total + currentBN });
}
}
if (state.status === 'rejected') {
return Object.assign(Object.assign({}, result), { failedValidators: [...result.failedValidators, { validatorId, error: state.reason }] });
}
return result;
}, { stakedValidators: [], failedValidators: [], total: BigInt(0) });
return Object.assign(Object.assign({}, summary), { total: summary.total.toString() });
});
if (state.status === 'rejected') {
return {
...result,
failedValidators: [...result.failedValidators, { validatorId, error: state.reason }],
};
}
return result;
}, { stakedValidators: [], failedValidators: [], total: 0n });
return {
...summary,
total: summary.total.toString(),
};
}
}
exports.Account = Account;

@@ -1,6 +0,3 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Connection = void 0;
const signers_1 = require("@near-js/signers");
const providers_1 = require("@near-js/providers");
import { InMemorySigner } from '@near-js/signers';
import { JsonRpcProvider, FailoverRpcProvider } from '@near-js/providers';
/**

@@ -14,6 +11,6 @@ * @param config Contains connection info details

return config;
case 'JsonRpcProvider': return new providers_1.JsonRpcProvider(Object.assign({}, config.args));
case 'JsonRpcProvider': return new JsonRpcProvider({ ...config.args });
case 'FailoverRpcProvider': {
const providers = ((config === null || config === void 0 ? void 0 : config.args) || []).map((arg) => new providers_1.JsonRpcProvider(arg));
return new providers_1.FailoverRpcProvider(providers);
const providers = (config?.args || []).map((arg) => new JsonRpcProvider(arg));
return new FailoverRpcProvider(providers);
}

@@ -32,3 +29,3 @@ default: throw new Error(`Unknown provider type ${config.type}`);

case 'InMemorySigner': {
return new signers_1.InMemorySigner(config.keyStore);
return new InMemorySigner(config.keyStore);
}

@@ -41,3 +38,7 @@ default: throw new Error(`Unknown signer type ${config.type}`);

*/
class Connection {
export class Connection {
networkId;
provider;
signer;
jsvmAccountId;
constructor(networkId, provider, signer, jsvmAccountId) {

@@ -61,2 +62,1 @@ this.networkId = networkId;

}
exports.Connection = Connection;
export declare const MULTISIG_STORAGE_KEY = "__multisigRequest";
export declare const MULTISIG_ALLOWANCE: bigint;
export declare const MULTISIG_GAS: bigint;
export declare const MULTISIG_DEPOSIT: bigint;
export declare const MULTISIG_GAS = 100000000000000n;
export declare const MULTISIG_DEPOSIT = 0n;
export declare const MULTISIG_CHANGE_METHODS: string[];
export declare const MULTISIG_CONFIRM_METHODS: string[];
//# sourceMappingURL=constants.d.ts.map

@@ -1,11 +0,8 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MULTISIG_CONFIRM_METHODS = exports.MULTISIG_CHANGE_METHODS = exports.MULTISIG_DEPOSIT = exports.MULTISIG_GAS = exports.MULTISIG_ALLOWANCE = exports.MULTISIG_STORAGE_KEY = void 0;
const utils_1 = require("@near-js/utils");
exports.MULTISIG_STORAGE_KEY = '__multisigRequest';
exports.MULTISIG_ALLOWANCE = BigInt((0, utils_1.parseNearAmount)('1'));
import { parseNearAmount } from '@near-js/utils';
export const MULTISIG_STORAGE_KEY = '__multisigRequest';
export const MULTISIG_ALLOWANCE = BigInt(parseNearAmount('1'));
// TODO: Different gas value for different requests (can reduce gas usage dramatically)
exports.MULTISIG_GAS = BigInt('100000000000000');
exports.MULTISIG_DEPOSIT = BigInt('0');
exports.MULTISIG_CHANGE_METHODS = ['add_request', 'add_request_and_confirm', 'delete_request', 'confirm'];
exports.MULTISIG_CONFIRM_METHODS = ['confirm'];
export const MULTISIG_GAS = 100000000000000n;
export const MULTISIG_DEPOSIT = 0n;
export const MULTISIG_CHANGE_METHODS = ['add_request', 'add_request_and_confirm', 'delete_request', 'confirm'];
export const MULTISIG_CONFIRM_METHODS = ['confirm'];

@@ -1,25 +0,10 @@

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
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) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Contract = void 0;
const utils_1 = require("@near-js/utils");
const types_1 = require("@near-js/types");
const local_view_execution_1 = require("./local-view-execution");
const is_my_json_valid_1 = __importDefault(require("is-my-json-valid"));
const depd_1 = __importDefault(require("depd"));
const near_abi_1 = require("near-abi");
const account_1 = require("./account");
const errors_1 = require("./errors");
const utils_2 = require("./utils");
import { getTransactionLastResult, Logger } from "@near-js/utils";
import { ArgumentTypeError, PositionalArgsError } from "@near-js/types";
import { LocalViewExecution } from "./local-view-execution";
import validator from "is-my-json-valid";
import depd from "depd";
import { AbiFunctionKind, AbiSerializationType, } from "near-abi";
import { Account } from "./account";
import { UnsupportedSerializationError, UnknownArgumentError, ArgumentSchemaError, ConflictingOptions, } from "./errors";
import { viewFunction } from "./utils";
// Makes `function.name` return given name

@@ -34,14 +19,13 @@ function nameFunction(name, body) {

function validateArguments(args, abiFunction, abiRoot) {
var _a;
if (!isObject(args))
return;
if (abiFunction.params &&
abiFunction.params.serialization_type !== near_abi_1.AbiSerializationType.Json) {
throw new errors_1.UnsupportedSerializationError(abiFunction.name, abiFunction.params.serialization_type);
abiFunction.params.serialization_type !== AbiSerializationType.Json) {
throw new UnsupportedSerializationError(abiFunction.name, abiFunction.params.serialization_type);
}
if (abiFunction.result &&
abiFunction.result.serialization_type !== near_abi_1.AbiSerializationType.Json) {
throw new errors_1.UnsupportedSerializationError(abiFunction.name, abiFunction.result.serialization_type);
abiFunction.result.serialization_type !== AbiSerializationType.Json) {
throw new UnsupportedSerializationError(abiFunction.name, abiFunction.result.serialization_type);
}
const params = ((_a = abiFunction.params) === null || _a === void 0 ? void 0 : _a.args) || [];
const params = abiFunction.params?.args || [];
for (const p of params) {

@@ -51,6 +35,6 @@ const arg = args[p.name];

typeSchema.definitions = abiRoot.body.root_schema.definitions;
const validate = (0, is_my_json_valid_1.default)(typeSchema);
const validate = validator(typeSchema);
const valid = validate(arg);
if (!valid) {
throw new errors_1.ArgumentSchemaError(p.name, validate.errors);
throw new ArgumentSchemaError(p.name, validate.errors);
}

@@ -62,3 +46,3 @@ }

if (!param) {
throw new errors_1.UnknownArgumentError(argName, params.map((p) => p.name));
throw new UnknownArgumentError(argName, params.map((p) => p.name));
}

@@ -103,3 +87,8 @@ }

*/
class Contract {
export class Contract {
/** @deprecated */
account;
connection;
contractId;
lve;
/**

@@ -112,4 +101,4 @@ * @param account NEAR account to sign change method transactions

this.connection = connection.getConnection();
if (connection instanceof account_1.Account) {
const deprecate = (0, depd_1.default)("new Contract(account, contractId, options)");
if (connection instanceof Account) {
const deprecate = depd("new Contract(account, contractId, options)");
deprecate("use `new Contract(connection, contractId, options)` instead");

@@ -119,3 +108,3 @@ this.account = connection;

this.contractId = contractId;
this.lve = new local_view_execution_1.LocalViewExecution(connection);
this.lve = new LocalViewExecution(connection);
const { viewMethods = [], changeMethods = [], abi: abiRoot, useLocalViewExecution, } = options;

@@ -133,9 +122,9 @@ let viewMethodsWithAbi = viewMethods.map((name) => ({

changeMethodsWithAbi.length > 0) {
throw new errors_1.ConflictingOptions();
throw new ConflictingOptions();
}
viewMethodsWithAbi = abiRoot.body.functions
.filter((m) => m.kind === near_abi_1.AbiFunctionKind.View)
.filter((m) => m.kind === AbiFunctionKind.View)
.map((m) => ({ name: m.name, abi: m }));
changeMethodsWithAbi = abiRoot.body.functions
.filter((methodAbi) => methodAbi.kind === near_abi_1.AbiFunctionKind.Call)
.filter((methodAbi) => methodAbi.kind === AbiFunctionKind.Call)
.map((methodAbi) => ({ name: methodAbi.name, abi: methodAbi }));

@@ -147,7 +136,7 @@ }

enumerable: true,
value: nameFunction(name, (args = {}, options = {}, ...ignored) => __awaiter(this, void 0, void 0, function* () {
value: nameFunction(name, async (args = {}, options = {}, ...ignored) => {
if (ignored.length ||
!(isObject(args) || isUint8Array(args)) ||
!isObject(options)) {
throw new types_1.PositionalArgsError();
throw new PositionalArgsError();
}

@@ -159,14 +148,29 @@ if (abi) {

try {
return yield this.lve.viewFunction(Object.assign({ contractId: this.contractId, methodName: name, args }, options));
return await this.lve.viewFunction({
contractId: this.contractId,
methodName: name,
args,
...options,
});
}
catch (error) {
utils_1.Logger.warn(`Local view execution failed with: "${error.message}"`);
utils_1.Logger.warn(`Fallback to normal RPC call`);
Logger.warn(`Local view execution failed with: "${error.message}"`);
Logger.warn(`Fallback to normal RPC call`);
}
}
if (this.account) {
return this.account.viewFunction(Object.assign({ contractId: this.contractId, methodName: name, args }, options));
return this.account.viewFunction({
contractId: this.contractId,
methodName: name,
args,
...options,
});
}
return (0, utils_2.viewFunction)(this.connection, Object.assign({ contractId: this.contractId, methodName: name, args }, options));
})),
return viewFunction(this.connection, {
contractId: this.contractId,
methodName: name,
args,
...options,
});
}),
});

@@ -178,10 +182,10 @@ });

enumerable: true,
value: nameFunction(name, (...args) => __awaiter(this, void 0, void 0, function* () {
value: nameFunction(name, async (...args) => {
if (args.length &&
(args.length > 3 ||
!(isObject(args[0]) || isUint8Array(args[0])))) {
throw new types_1.PositionalArgsError();
throw new PositionalArgsError();
}
if (args.length > 1 || !(args[0] && args[0].args)) {
const deprecate = (0, depd_1.default)("contract.methodName(args, gas, amount)");
const deprecate = depd("contract.methodName(args, gas, amount)");
deprecate("use `contract.methodName({ signerAccount, args, gas?, amount?, callbackUrl?, meta? })` instead");

@@ -197,27 +201,24 @@ args[0] = {

}
return this._changeMethod(Object.assign({ methodName: name }, args[0]));
})),
return this._changeMethod({ methodName: name, ...args[0] });
}),
});
});
}
_changeMethod({ signerAccount, args, methodName, gas, amount, meta, callbackUrl, }) {
return __awaiter(this, void 0, void 0, function* () {
validateBNLike({ gas, amount });
const account = this.account || signerAccount;
if (!account)
throw new Error(`signerAccount must be specified`);
const rawResult = yield account.functionCall({
contractId: this.contractId,
methodName,
args,
gas,
attachedDeposit: amount,
walletMeta: meta,
walletCallbackUrl: callbackUrl,
});
return (0, utils_1.getTransactionLastResult)(rawResult);
async _changeMethod({ signerAccount, args, methodName, gas, amount, meta, callbackUrl, }) {
validateBNLike({ gas, amount });
const account = this.account || signerAccount;
if (!account)
throw new Error(`signerAccount must be specified`);
const rawResult = await account.functionCall({
contractId: this.contractId,
methodName,
args,
gas,
attachedDeposit: amount,
walletMeta: meta,
walletCallbackUrl: callbackUrl,
});
return getTransactionLastResult(rawResult);
}
}
exports.Contract = Contract;
/**

@@ -232,5 +233,5 @@ * Throws if an argument is not in BigInt format or otherwise invalid

if (argValue && typeof argValue !== "bigint" && isNaN(argValue)) {
throw new types_1.ArgumentTypeError(argName, bnLike, argValue);
throw new ArgumentTypeError(argName, bnLike, argValue);
}
}
}

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

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConflictingOptions = exports.ArgumentSchemaError = exports.UnknownArgumentError = exports.UnsupportedSerializationError = void 0;
class UnsupportedSerializationError extends Error {
export class UnsupportedSerializationError extends Error {
constructor(methodName, serializationType) {

@@ -9,4 +6,3 @@ super(`Contract method '${methodName}' is using an unsupported serialization type ${serializationType}`);

}
exports.UnsupportedSerializationError = UnsupportedSerializationError;
class UnknownArgumentError extends Error {
export class UnknownArgumentError extends Error {
constructor(actualArgName, expectedArgNames) {

@@ -16,4 +12,3 @@ super(`Unrecognized argument '${actualArgName}', expected '${JSON.stringify(expectedArgNames)}'`);

}
exports.UnknownArgumentError = UnknownArgumentError;
class ArgumentSchemaError extends Error {
export class ArgumentSchemaError extends Error {
constructor(argName, errors) {

@@ -23,4 +18,3 @@ super(`Argument '${argName}' does not conform to the specified ABI schema: '${JSON.stringify(errors)}'`);

}
exports.ArgumentSchemaError = ArgumentSchemaError;
class ConflictingOptions extends Error {
export class ConflictingOptions extends Error {
constructor() {

@@ -30,2 +24,1 @@ super('Conflicting contract method options have been passed. You can either specify ABI or a list of view/call methods.');

}
exports.ConflictingOptions = ConflictingOptions;

@@ -1,32 +0,9 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MultisigStateStatus = exports.MultisigDeleteRequestRejectionError = exports.UnsupportedSerializationError = exports.UnknownArgumentError = exports.ConflictingOptions = exports.ArgumentSchemaError = exports.Contract = exports.MULTISIG_CONFIRM_METHODS = exports.MULTISIG_CHANGE_METHODS = exports.MULTISIG_DEPOSIT = exports.MULTISIG_GAS = exports.MULTISIG_ALLOWANCE = exports.MULTISIG_STORAGE_KEY = exports.Connection = exports.AccountMultisig = exports.UrlAccountCreator = exports.LocalAccountCreator = exports.AccountCreator = exports.Account2FA = exports.Account = void 0;
var account_1 = require("./account");
Object.defineProperty(exports, "Account", { enumerable: true, get: function () { return account_1.Account; } });
var account_2fa_1 = require("./account_2fa");
Object.defineProperty(exports, "Account2FA", { enumerable: true, get: function () { return account_2fa_1.Account2FA; } });
var account_creator_1 = require("./account_creator");
Object.defineProperty(exports, "AccountCreator", { enumerable: true, get: function () { return account_creator_1.AccountCreator; } });
Object.defineProperty(exports, "LocalAccountCreator", { enumerable: true, get: function () { return account_creator_1.LocalAccountCreator; } });
Object.defineProperty(exports, "UrlAccountCreator", { enumerable: true, get: function () { return account_creator_1.UrlAccountCreator; } });
var account_multisig_1 = require("./account_multisig");
Object.defineProperty(exports, "AccountMultisig", { enumerable: true, get: function () { return account_multisig_1.AccountMultisig; } });
var connection_1 = require("./connection");
Object.defineProperty(exports, "Connection", { enumerable: true, get: function () { return connection_1.Connection; } });
var constants_1 = require("./constants");
Object.defineProperty(exports, "MULTISIG_STORAGE_KEY", { enumerable: true, get: function () { return constants_1.MULTISIG_STORAGE_KEY; } });
Object.defineProperty(exports, "MULTISIG_ALLOWANCE", { enumerable: true, get: function () { return constants_1.MULTISIG_ALLOWANCE; } });
Object.defineProperty(exports, "MULTISIG_GAS", { enumerable: true, get: function () { return constants_1.MULTISIG_GAS; } });
Object.defineProperty(exports, "MULTISIG_DEPOSIT", { enumerable: true, get: function () { return constants_1.MULTISIG_DEPOSIT; } });
Object.defineProperty(exports, "MULTISIG_CHANGE_METHODS", { enumerable: true, get: function () { return constants_1.MULTISIG_CHANGE_METHODS; } });
Object.defineProperty(exports, "MULTISIG_CONFIRM_METHODS", { enumerable: true, get: function () { return constants_1.MULTISIG_CONFIRM_METHODS; } });
var contract_1 = require("./contract");
Object.defineProperty(exports, "Contract", { enumerable: true, get: function () { return contract_1.Contract; } });
var errors_1 = require("./errors");
Object.defineProperty(exports, "ArgumentSchemaError", { enumerable: true, get: function () { return errors_1.ArgumentSchemaError; } });
Object.defineProperty(exports, "ConflictingOptions", { enumerable: true, get: function () { return errors_1.ConflictingOptions; } });
Object.defineProperty(exports, "UnknownArgumentError", { enumerable: true, get: function () { return errors_1.UnknownArgumentError; } });
Object.defineProperty(exports, "UnsupportedSerializationError", { enumerable: true, get: function () { return errors_1.UnsupportedSerializationError; } });
var types_1 = require("./types");
Object.defineProperty(exports, "MultisigDeleteRequestRejectionError", { enumerable: true, get: function () { return types_1.MultisigDeleteRequestRejectionError; } });
Object.defineProperty(exports, "MultisigStateStatus", { enumerable: true, get: function () { return types_1.MultisigStateStatus; } });
export { Account } from './account';
export { Account2FA } from './account_2fa';
export { AccountCreator, LocalAccountCreator, UrlAccountCreator, } from './account_creator';
export { AccountMultisig } from './account_multisig';
export { Connection } from './connection';
export { MULTISIG_STORAGE_KEY, MULTISIG_ALLOWANCE, MULTISIG_GAS, MULTISIG_DEPOSIT, MULTISIG_CHANGE_METHODS, MULTISIG_CONFIRM_METHODS, } from './constants';
export { Contract, } from './contract';
export { ArgumentSchemaError, ConflictingOptions, UnknownArgumentError, UnsupportedSerializationError, } from './errors';
export { MultisigDeleteRequestRejectionError, MultisigStateStatus, } from './types';

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

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
export {};

@@ -24,5 +24,5 @@ import { BlockReference } from '@near-js/types';

*/
viewFunction({ contractId, methodName, args, blockQuery, ...ignored }: ViewFunctionCallOptions): Promise<any>;
viewFunction({ contractId, methodName, args, blockQuery }: ViewFunctionCallOptions): Promise<any>;
}
export {};
//# sourceMappingURL=index.d.ts.map

@@ -1,71 +0,46 @@

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
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) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
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 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LocalViewExecution = void 0;
const utils_1 = require("@near-js/utils");
const storage_1 = require("./storage");
const runtime_1 = require("./runtime");
const utils_2 = require("../utils");
class LocalViewExecution {
import { printTxOutcomeLogs } from '@near-js/utils';
import { Storage } from './storage';
import { Runtime } from './runtime';
import { viewState } from '../utils';
export class LocalViewExecution {
connection;
storage;
constructor(connection) {
this.connection = connection.getConnection();
this.storage = new storage_1.Storage();
this.storage = new Storage();
}
fetchContractCode(contractId, blockQuery) {
return __awaiter(this, void 0, void 0, function* () {
const result = yield this.connection.provider.query(Object.assign({ request_type: 'view_code', account_id: contractId }, blockQuery));
return result.code_base64;
async fetchContractCode(contractId, blockQuery) {
const result = await this.connection.provider.query({
request_type: 'view_code',
account_id: contractId,
...blockQuery,
});
return result.code_base64;
}
fetchContractState(contractId, blockQuery) {
return __awaiter(this, void 0, void 0, function* () {
return (0, utils_2.viewState)(this.connection, contractId, '', blockQuery);
});
async fetchContractState(contractId, blockQuery) {
return viewState(this.connection, contractId, '', blockQuery);
}
fetch(contractId, blockQuery) {
return __awaiter(this, void 0, void 0, function* () {
const block = yield this.connection.provider.block(blockQuery);
const blockHash = block.header.hash;
const blockHeight = block.header.height;
const blockTimestamp = block.header.timestamp;
const contractCode = yield this.fetchContractCode(contractId, blockQuery);
const contractState = yield this.fetchContractState(contractId, blockQuery);
return {
blockHash,
blockHeight,
blockTimestamp,
contractCode,
contractState,
};
});
async fetch(contractId, blockQuery) {
const block = await this.connection.provider.block(blockQuery);
const blockHash = block.header.hash;
const blockHeight = block.header.height;
const blockTimestamp = block.header.timestamp;
const contractCode = await this.fetchContractCode(contractId, blockQuery);
const contractState = await this.fetchContractState(contractId, blockQuery);
return {
blockHash,
blockHeight,
blockTimestamp,
contractCode,
contractState,
};
}
loadOrFetch(contractId, blockQuery) {
return __awaiter(this, void 0, void 0, function* () {
const stored = this.storage.load(blockQuery);
if (stored) {
return stored;
}
const _a = yield this.fetch(contractId, blockQuery), { blockHash } = _a, fetched = __rest(_a, ["blockHash"]);
this.storage.save(blockHash, fetched);
return fetched;
});
async loadOrFetch(contractId, blockQuery) {
const stored = this.storage.load(blockQuery);
if (stored) {
return stored;
}
const { blockHash, ...fetched } = await this.fetch(contractId, blockQuery);
this.storage.save(blockHash, fetched);
return fetched;
}

@@ -81,16 +56,12 @@ /**

*/
viewFunction(_a) {
var { contractId, methodName, args = {}, blockQuery = { finality: 'optimistic' } } = _a, ignored = __rest(_a, ["contractId", "methodName", "args", "blockQuery"]);
return __awaiter(this, void 0, void 0, function* () {
const methodArgs = JSON.stringify(args);
const { contractCode, contractState, blockHeight, blockTimestamp } = yield this.loadOrFetch(contractId, blockQuery);
const runtime = new runtime_1.Runtime({ contractId, contractCode, contractState, blockHeight, blockTimestamp, methodArgs });
const { result, logs } = yield runtime.execute(methodName);
if (logs) {
(0, utils_1.printTxOutcomeLogs)({ contractId, logs });
}
return JSON.parse(Buffer.from(result).toString());
});
async viewFunction({ contractId, methodName, args = {}, blockQuery = { finality: 'optimistic' } }) {
const methodArgs = JSON.stringify(args);
const { contractCode, contractState, blockHeight, blockTimestamp } = await this.loadOrFetch(contractId, blockQuery);
const runtime = new Runtime({ contractId, contractCode, contractState, blockHeight, blockTimestamp, methodArgs });
const { result, logs } = await runtime.execute(methodName);
if (logs) {
printTxOutcomeLogs({ contractId, logs });
}
return JSON.parse(Buffer.from(result).toString());
}
}
exports.LocalViewExecution = LocalViewExecution;

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

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
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) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
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 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Runtime = void 0;
const crypto_1 = require("crypto");
import { sha256 } from '@noble/hashes/sha256';
const notImplemented = (name) => () => {

@@ -31,5 +8,10 @@ throw new Error('method not implemented: ' + name);

};
class Runtime {
constructor(_a) {
var { contractCode } = _a, context = __rest(_a, ["contractCode"]);
export class Runtime {
context;
wasm;
memory;
registers;
logs;
result;
constructor({ contractCode, ...context }) {
this.context = context;

@@ -174,3 +156,3 @@ this.wasm = this.prepareWASM(Buffer.from(contractCode, 'base64'));

encodeString('memory'),
Buffer.from([2]),
Buffer.from([2]), // Memory import
Buffer.from([0]),

@@ -185,3 +167,3 @@ encodeLEB128(1),

parts.push(Buffer.concat([
Buffer.from([2]),
Buffer.from([2]), // Import section
encodeLEB128(sectionData.length),

@@ -211,3 +193,3 @@ sectionData

parts.push(Buffer.concat([
Buffer.from([7]),
Buffer.from([7]), // Export section
encodeLEB128(sectionData.length),

@@ -246,5 +228,3 @@ sectionData

const value = new Uint8Array(this.memory.buffer, Number(valuePtr), Number(valueLen));
const hash = (0, crypto_1.createHash)('sha256');
hash.update(value);
this.registers[registerId.toString()] = hash.digest();
this.registers[registerId.toString()] = sha256(value);
}

@@ -272,6 +252,6 @@ returnValue(valueLen, valuePtr) {

if (result == null) {
return BigInt(0);
return 0n;
}
this.registers[register_id] = result;
return BigInt(1);
return 1n;
}

@@ -281,5 +261,5 @@ hasStorageKey(key_len, key_ptr) {

if (result == null) {
return BigInt(0);
return 0n;
}
return BigInt(1);
return 1n;
}

@@ -345,18 +325,15 @@ getHostImports() {

}
execute(methodName) {
return __awaiter(this, void 0, void 0, function* () {
const module = yield WebAssembly.compile(this.wasm);
const instance = yield WebAssembly.instantiate(module, { env: Object.assign(Object.assign({}, this.getHostImports()), { memory: this.memory }) });
const callMethod = instance.exports[methodName];
if (callMethod == undefined) {
throw new Error(`Contract method '${methodName}' does not exists in contract ${this.context.contractId} for block id ${this.context.blockHeight}`);
}
callMethod();
return {
result: this.result,
logs: this.logs
};
});
async execute(methodName) {
const module = await WebAssembly.compile(this.wasm);
const instance = await WebAssembly.instantiate(module, { env: { ...this.getHostImports(), memory: this.memory } });
const callMethod = instance.exports[methodName];
if (callMethod == undefined) {
throw new Error(`Contract method '${methodName}' does not exists in contract ${this.context.contractId} for block id ${this.context.blockHeight}`);
}
callMethod();
return {
result: this.result,
logs: this.logs
};
}
}
exports.Runtime = Runtime;

@@ -1,8 +0,9 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Storage = void 0;
const lru_map_1 = require("lru_map");
class Storage {
import { LRUMap } from 'lru_map';
export class Storage {
cache;
static MAX_ELEMENTS = 100;
// map block hash to block height
blockHeights;
constructor(options = { max: Storage.MAX_ELEMENTS }) {
this.cache = new lru_map_1.LRUMap(options.max);
this.cache = new LRUMap(options.max);
this.blockHeights = new Map();

@@ -27,3 +28,1 @@ }

}
exports.Storage = Storage;
Storage.MAX_ELEMENTS = 100;

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

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
export {};

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

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MultisigStateStatus = exports.MultisigDeleteRequestRejectionError = void 0;
var MultisigDeleteRequestRejectionError;
export var MultisigDeleteRequestRejectionError;
(function (MultisigDeleteRequestRejectionError) {

@@ -11,4 +8,4 @@ MultisigDeleteRequestRejectionError["CANNOT_DESERIALIZE_STATE"] = "Cannot deserialize the contract state";

MultisigDeleteRequestRejectionError["METHOD_NOT_FOUND"] = "Contract method is not found";
})(MultisigDeleteRequestRejectionError = exports.MultisigDeleteRequestRejectionError || (exports.MultisigDeleteRequestRejectionError = {}));
var MultisigStateStatus;
})(MultisigDeleteRequestRejectionError || (MultisigDeleteRequestRejectionError = {}));
export var MultisigStateStatus;
(function (MultisigStateStatus) {

@@ -19,2 +16,2 @@ MultisigStateStatus[MultisigStateStatus["INVALID_STATE"] = 0] = "INVALID_STATE";

MultisigStateStatus[MultisigStateStatus["UNKNOWN_STATE"] = 3] = "UNKNOWN_STATE";
})(MultisigStateStatus = exports.MultisigStateStatus || (exports.MultisigStateStatus = {}));
})(MultisigStateStatus || (MultisigStateStatus = {}));

@@ -1,15 +0,3 @@

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
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) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.viewFunction = exports.viewState = exports.encodeJSContractArgs = exports.validateArgs = void 0;
const types_1 = require("@near-js/types");
const utils_1 = require("@near-js/utils");
import { PositionalArgsError, } from '@near-js/types';
import { printTxOutcomeLogs } from '@near-js/utils';
function parseJsonFromRawResponse(response) {

@@ -21,3 +9,3 @@ return JSON.parse(Buffer.from(response).toString());

}
function validateArgs(args) {
export function validateArgs(args) {
const isUint8Array = args.byteLength !== undefined && args.byteLength === args.length;

@@ -28,10 +16,8 @@ if (isUint8Array) {

if (Array.isArray(args) || typeof args !== 'object') {
throw new types_1.PositionalArgsError();
throw new PositionalArgsError();
}
}
exports.validateArgs = validateArgs;
function encodeJSContractArgs(contractId, method, args) {
export function encodeJSContractArgs(contractId, method, args) {
return Buffer.concat([Buffer.from(contractId), Buffer.from([0]), Buffer.from(method), Buffer.from([0]), Buffer.from(args)]);
}
exports.encodeJSContractArgs = encodeJSContractArgs;
/**

@@ -47,12 +33,14 @@ * Returns the state (key value pairs) of account's contract based on the key prefix.

*/
function viewState(connection, accountId, prefix, blockQuery = { finality: 'optimistic' }) {
return __awaiter(this, void 0, void 0, function* () {
const { values } = yield connection.provider.query(Object.assign(Object.assign({ request_type: 'view_state' }, blockQuery), { account_id: accountId, prefix_base64: Buffer.from(prefix).toString('base64') }));
return values.map(({ key, value }) => ({
key: Buffer.from(key, 'base64'),
value: Buffer.from(value, 'base64')
}));
export async function viewState(connection, accountId, prefix, blockQuery = { finality: 'optimistic' }) {
const { values } = await connection.provider.query({
request_type: 'view_state',
...blockQuery,
account_id: accountId,
prefix_base64: Buffer.from(prefix).toString('base64')
});
return values.map(({ key, value }) => ({
key: Buffer.from(key, 'base64'),
value: Buffer.from(value, 'base64')
}));
}
exports.viewState = viewState;
/**

@@ -72,19 +60,22 @@ * Invoke a contract view function using the RPC API.

*/
function viewFunction(connection, { contractId, methodName, args = {}, parse = parseJsonFromRawResponse, stringify = bytesJsonStringify, jsContract = false, blockQuery = { finality: 'optimistic' } }) {
return __awaiter(this, void 0, void 0, function* () {
let encodedArgs;
validateArgs(args);
if (jsContract) {
encodedArgs = encodeJSContractArgs(contractId, methodName, Object.keys(args).length > 0 ? JSON.stringify(args) : '');
}
else {
encodedArgs = stringify(args);
}
const result = yield connection.provider.query(Object.assign(Object.assign({ request_type: 'call_function' }, blockQuery), { account_id: jsContract ? connection.jsvmAccountId : contractId, method_name: jsContract ? 'view_js_contract' : methodName, args_base64: encodedArgs.toString('base64') }));
if (result.logs) {
(0, utils_1.printTxOutcomeLogs)({ contractId, logs: result.logs });
}
return result.result && result.result.length > 0 && parse(Buffer.from(result.result));
export async function viewFunction(connection, { contractId, methodName, args = {}, parse = parseJsonFromRawResponse, stringify = bytesJsonStringify, jsContract = false, blockQuery = { finality: 'optimistic' } }) {
let encodedArgs;
validateArgs(args);
if (jsContract) {
encodedArgs = encodeJSContractArgs(contractId, methodName, Object.keys(args).length > 0 ? JSON.stringify(args) : '');
}
else {
encodedArgs = stringify(args);
}
const result = await connection.provider.query({
request_type: 'call_function',
...blockQuery,
account_id: jsContract ? connection.jsvmAccountId : contractId,
method_name: jsContract ? 'view_js_contract' : methodName,
args_base64: encodedArgs.toString('base64')
});
if (result.logs) {
printTxOutcomeLogs({ contractId, logs: result.logs });
}
return result.result && result.result.length > 0 && parse(Buffer.from(result.result));
}
exports.viewFunction = viewFunction;
{
"name": "@near-js/accounts",
"version": "1.2.1",
"version": "1.3.0-next.0",
"description": "Classes encapsulating account-specific functionality",
"main": "lib/index.js",
"type": "module",
"keywords": [],

@@ -10,23 +11,30 @@ "author": "",

"dependencies": {
"@noble/hashes": "1.3.3",
"borsh": "1.0.0",
"depd": "2.0.0",
"is-my-json-valid": "^2.20.6",
"isomorphic-unfetch": "^3.1.0",
"lru_map": "0.4.1",
"near-abi": "0.1.1",
"@near-js/crypto": "1.2.4",
"@near-js/providers": "0.2.2",
"@near-js/signers": "0.1.4",
"@near-js/transactions": "1.2.2",
"@near-js/types": "0.2.1",
"@near-js/utils": "0.2.2"
"@near-js/providers": "0.3.0-next.0",
"@near-js/signers": "0.2.0-next.0",
"@near-js/crypto": "1.3.0-next.0",
"@near-js/transactions": "1.3.0-next.0",
"@near-js/types": "0.3.0-next.0",
"@near-js/utils": "0.3.0-next.0"
},
"devDependencies": {
"@types/node": "18.11.18",
"@jest/globals": "^29.7.0",
"@types/json-schema": "^7.0.15",
"@types/node": "20.0.0",
"bs58": "4.0.0",
"jest": "26.0.1",
"jest": "29.7.0",
"near-hello": "0.5.1",
"near-workspaces": "3.5.0",
"ts-jest": "26.5.6",
"typescript": "4.9.4",
"@near-js/keystores": "0.0.12"
"node-fetch": "2.6.7",
"semver": "7.1.1",
"ts-jest": "29.1.5",
"typescript": "5.4.5",
"@near-js/keystores": "0.1.0-next.0",
"tsconfig": "0.0.0"
},

@@ -43,8 +51,6 @@ "files": [

"compile": "tsc -p tsconfig.json",
"lint:js": "eslint -c ../../.eslintrc.js.yml test/**/*.js --no-eslintrc",
"lint:js:fix": "eslint -c ../../.eslintrc.js.yml test/**/*.js --no-eslintrc --fix",
"lint:ts": "eslint -c ../../.eslintrc.ts.yml src/**/*.ts --no-eslintrc",
"lint:ts:fix": "eslint -c ../../.eslintrc.ts.yml src/**/*.ts --no-eslintrc --fix",
"test": "jest test"
"lint": "eslint -c ../../.eslintrc.ts.yml src/**/*.ts test/**/*.ts --no-eslintrc",
"lint:fix": "eslint -c ../../.eslintrc.ts.yml src/**/*.ts test/**/*.ts --no-eslintrc --fix",
"test": "jest"
}
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc