@massalabs/wallet-provider 1.5.2-dev.20231220152928 → 1.5.2-dev.20231221133250
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cmd/bearbyWallet/BearbyAccount.d.ts.map +1 -1
- package/dist/cmd/bearbyWallet/BearbyAccount.js +9 -4
- package/dist/cmd/bearbyWallet/BearbyAccount.js.map +1 -1
- package/dist/cmd/massaStation/MassaStationAccount.js +1 -1
- package/dist/cmd/massaStation/MassaStationAccount.js.map +1 -1
- package/dist/esm/bearbyWallet/BearbyAccount.d.ts.map +1 -1
- package/dist/esm/bearbyWallet/BearbyAccount.js +9 -4
- package/dist/esm/bearbyWallet/BearbyAccount.js.map +1 -1
- package/dist/esm/massaStation/MassaStationAccount.js +1 -1
- package/dist/esm/massaStation/MassaStationAccount.js.map +1 -1
- package/package.json +2 -2
- package/dist/cmd/utils/typeCheck.d.ts +0 -2
- package/dist/cmd/utils/typeCheck.d.ts.map +0 -1
- package/dist/cmd/utils/typeCheck.js +0 -9
- package/dist/cmd/utils/typeCheck.js.map +0 -1
- package/dist/esm/utils/typeCheck.d.ts +0 -2
- package/dist/esm/utils/typeCheck.d.ts.map +0 -1
- package/dist/esm/utils/typeCheck.js +0 -5
- package/dist/esm/utils/typeCheck.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BearbyAccount.d.ts","sourceRoot":"","sources":["../../../src/bearbyWallet/BearbyAccount.ts"],"names":[],"mappings":";AAAA,OAAO,EACL,IAAI,EAEJ,8BAA8B,EAC/B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,mBAAmB,EAAE,MAAM,IAAI,CAAC;AACzC,OAAO,EAAE,uBAAuB,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AACtE,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAO/C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,O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,CAAC;IAyB3C,IAAI,CACf,IAAI,EAAE,MAAM,GAAG,UAAU,GAAG,MAAM,GACjC,OAAO,CAAC,kBAAkB,CAAC;IAkBjB,QAAQ,CACnB,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,GACV,OAAO,CAAC,mBAAmB,CAAC;IAUlB,SAAS,CACpB,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,GACV,OAAO,CAAC,mBAAmB,CAAC;IASlB,eAAe,CAC1B,MAAM,EAAE,MAAM,EACd,gBAAgB,EAAE,MAAM,EACxB,GAAG,EAAE,MAAM,GACV,OAAO,CAAC,mBAAmB,CAAC;IAalB,MAAM,CACjB,eAAe,EAAE,MAAM,EACvB,YAAY,EAAE,MAAM,EACpB,SAAS,EAAE,IAAI,GAAG,UAAU,EAC5B,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,MAAM,EACd,sBAAsB,UAAQ,GAC7B,OAAO,CAAC,mBAAmB,GAAG,8BAA8B,CAAC;IAgChE;;;;;;;;;;;OAWG;IACU,aAAa,IAAI,OAAO,CAAC,UAAU,CAAC;IAKjD;;;;;;;;;OASG;cACa,kBAAkB,CAAC,CAAC,EAClC,QAAQ,EAAE,uBAAuB,EACjC,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,CAAC,CAAC;IAYb;;;;;;;;;;;;OAYG;YACW,oBAAoB;IAwCrB,mBAAmB,CAC9B,eAAe,EAAE,MAAM,EACvB,YAAY,EAAE,MAAM,EACpB,SAAS,EAAE,UAAU,GAAG,IAAI,EAC5B,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,8BAA8B,CAAC;CAmE3C"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.BearbyAccount = exports.OperationTypeId = exports.OperationsType = exports.PUBLIC_NODE_RPC = void 0;
|
|
4
|
+
const web3_utils_1 = require("@massalabs/web3-utils");
|
|
4
5
|
const bearby_js_1 = require("@hicaru/bearby.js");
|
|
5
6
|
const RequestHandler_1 = require("../massaStation/RequestHandler");
|
|
6
7
|
const jsonRpcMethods_1 = require("./jsonRpcMethods");
|
|
7
8
|
const axios_1 = require("axios");
|
|
8
|
-
const typeCheck_1 = require("../utils/typeCheck");
|
|
9
9
|
/**
|
|
10
10
|
* The maximum allowed gas for a read operation
|
|
11
11
|
*/
|
|
@@ -124,15 +124,20 @@ class BearbyAccount {
|
|
|
124
124
|
if (nonPersistentExecution) {
|
|
125
125
|
return this.nonPersistentCallSC(contractAddress, functionName, parameter, amount, fee, maxGas);
|
|
126
126
|
}
|
|
127
|
+
let unsafeParameters = Uint8Array.from([]);
|
|
128
|
+
if (parameter instanceof web3_utils_1.Args) {
|
|
129
|
+
unsafeParameters = Uint8Array.from(parameter.serialize());
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
unsafeParameters = parameter;
|
|
133
|
+
}
|
|
127
134
|
const operationId = await bearby_js_1.web3.contract.call({
|
|
128
135
|
maxGas: Number(maxGas),
|
|
129
136
|
coins: Number(amount),
|
|
130
137
|
fee: Number(fee),
|
|
131
138
|
targetAddress: contractAddress,
|
|
132
139
|
functionName: functionName,
|
|
133
|
-
unsafeParameters
|
|
134
|
-
? parameter
|
|
135
|
-
: parameter.serialize(),
|
|
140
|
+
unsafeParameters,
|
|
136
141
|
});
|
|
137
142
|
return { operationId };
|
|
138
143
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BearbyAccount.js","sourceRoot":"","sources":["../../../src/bearbyWallet/BearbyAccount.ts"],"names":[],"mappings":";;;AAQA,iDAAyC;AACzC,mEAGwC;AAGxC,qDAA2D;AAC3D,iCAAkE;AAElE,kDAAsD;AACtD;;GAEG;AACH,MAAM,kBAAkB,GAAG,MAAM,CAAC,UAAa,CAAC,CAAC;AAEjD;;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AG,CAAC;SACjB,CAAC;QACF,MAAM,IAAI,GAAG;YACX;gBACE,OAAO,EAAE,KAAK;gBACd,MAAM,EAAE,wBAAwB;gBAChC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC;gBAChB,EAAE,EAAE,CAAC;aACN;SACF,CAAC;QACF,wBAAwB;QACxB,IAAI,iBAAiB,GAAsC,EAAE,CAAC;QAC9D,IAAI;YACF,IAAI,IAAI,GAAG,MAAM,IAAA,4BAAW,EAC1B,IAAI,EACJ,IAAI,CACL,CAAC;YACF,IAAI,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,KAAK,EAAE;gBAC9B,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC;aAC1B;YACD,iBAAiB,GAAG,IAAI,CAAC,MAAM,CAAC;SACjC;QAAC,OAAO,EAAE,EAAE;YACX,MAAM,IAAI,KAAK,CACb,sEAAsE,EAAE,EAAE,CAC3E,CAAC;SACH;QACD,IAAI,iBAAiB,CAAC,MAAM,IAAI,CAAC,EAAE;YACjC,MAAM,IAAI,KAAK,CACb,4FAA4F,CAC7F,CAAC;SACH;QACD,IAAI,iBAAiB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,EAAE;YACrC,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;SACpD;QACD,OAAO;YACL,WAAW,EAAE,IAAI,UAAU,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC;YACrE,IAAI,EAAE,iBAAiB,CAAC,CAAC,CAAC;SAC3B,CAAC;IACJ,CAAC;CACF;AApUD,sCAoUC","sourcesContent":["import {\n Args,\n IContractReadOperationData,\n IContractReadOperationResponse,\n} from '@massalabs/web3-utils';\nimport { ITransactionDetails } from '..';\nimport { IAccountBalanceResponse, IAccountDetails } from '../account';\nimport { IAccount } from '../account/IAccount';\nimport { web3 } from '@hicaru/bearby.js';\nimport {\n postRequest,\n JsonRpcResponseData,\n} from '../massaStation/RequestHandler';\nimport { BalanceResponse } from './BalanceResponse';\nimport { NodeStatus } from './NodeStatus';\nimport { JSON_RPC_REQUEST_METHOD } from './jsonRpcMethods';\nimport axios, { AxiosRequestHeaders, AxiosResponse } from 'axios';\nimport { IAccountSignOutput } from '../account/AccountSign';\nimport { isArrayOfNumbers } from '../utils/typeCheck';\n/**\n * The maximum allowed gas for a read operation\n */\nconst MAX_READ_BLOCK_GAS = BigInt(4_294_967_295);\n\n/**\n * The RPC we are using to query the node\n */\nexport const PUBLIC_NODE_RPC = 'https://buildnet.massa.net/api/v2';\n\nexport enum OperationsType {\n Payment,\n RollBuy,\n RollSell,\n ExecuteSC,\n CallSC,\n}\n\n/**\n * Associates an operation type with a number.\n */\nexport enum OperationTypeId {\n Transaction = 0,\n RollBuy = 1,\n RollSell = 2,\n ExecuteSC = 3,\n CallSC = 4,\n}\n\nconst requestHeaders = {\n Accept:\n 'application/json,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Content-Type': 'application/json',\n} as AxiosRequestHeaders;\n\nexport class BearbyAccount implements IAccount {\n private _providerName: string;\n private _address: string;\n private _name: string;\n private _nodeUrl = PUBLIC_NODE_RPC;\n\n public constructor({ address, name }: IAccountDetails, providerName: string) {\n this._address = address;\n this._name = name ?? 'Bearby_account';\n this._providerName = providerName;\n }\n\n public address(): string {\n return this._address;\n }\n\n public name(): string {\n return this._name;\n }\n\n public providerName(): string {\n return this._providerName;\n }\n\n public async connect() {\n try {\n await web3.wallet.connect();\n } catch (ex) {\n console.log('Bearby connection error: ', ex);\n }\n }\n\n // needs testing\n public async balance(): Promise<IAccountBalanceResponse> {\n await this.connect();\n // Not available on bearby. we have to manually call the api\n const body = {\n jsonrpc: '2.0',\n method: 'get_addresses',\n params: [[this._address]],\n id: 0,\n };\n\n const addressInfos = await postRequest<BalanceResponse>(\n PUBLIC_NODE_RPC,\n body,\n );\n\n if (addressInfos.isError || addressInfos.error) {\n throw addressInfos.error.message;\n }\n return {\n finalBalance: addressInfos.result.result[0].final_balance,\n candidateBalance: addressInfos.result.result[0].candidate_balance,\n } as IAccountBalanceResponse;\n }\n\n // need testing\n public async sign(\n data: Buffer | Uint8Array | string,\n ): Promise<IAccountSignOutput> {\n await this.connect();\n\n let strData: string;\n if (data instanceof Uint8Array) {\n strData = new TextDecoder().decode(data);\n }\n if (data instanceof Buffer) {\n strData = data.toString();\n }\n const signature = await web3.wallet.signMessage(strData);\n return {\n publicKey: signature.publicKey,\n base58Encoded: signature.signature,\n };\n }\n\n // need testing\n public async buyRolls(\n amount: bigint,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n await this.connect();\n const operationId = await web3.massa.buyRolls(amount.toString());\n\n return {\n operationId,\n } as ITransactionDetails;\n }\n\n // need testing\n public async sellRolls(\n amount: bigint,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n await this.connect();\n const operationId = await web3.massa.sellRolls(amount.toString());\n\n return {\n operationId,\n } as ITransactionDetails;\n }\n\n public async sendTransaction(\n amount: bigint,\n recipientAddress: string,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n await this.connect();\n\n const operationId = await web3.massa.payment(\n amount.toString(),\n recipientAddress,\n );\n\n return {\n operationId,\n } as ITransactionDetails;\n }\n\n public async callSC(\n contractAddress: string,\n functionName: string,\n parameter: Args | Uint8Array,\n amount: bigint,\n fee: bigint,\n maxGas: bigint,\n nonPersistentExecution = false,\n ): Promise<ITransactionDetails | IContractReadOperationResponse> {\n await this.connect();\n if (nonPersistentExecution) {\n return this.nonPersistentCallSC(\n contractAddress,\n functionName,\n parameter,\n amount,\n fee,\n maxGas,\n );\n }\n\n const operationId = await web3.contract.call({\n maxGas: Number(maxGas),\n coins: Number(amount),\n fee: Number(fee),\n targetAddress: contractAddress,\n functionName: functionName,\n unsafeParameters: isArrayOfNumbers(parameter)\n ? (parameter as Uint8Array)\n : ((parameter as Args).serialize() as unknown as Uint8Array),\n });\n\n return { operationId };\n }\n\n /**\n * Retrieves the node's status.\n *\n * @remarks\n * The returned information includes:\n * - Whether the node is reachable\n * - The number of connected peers\n * - The node's version\n * - The node's configuration parameters\n *\n * @returns A promise that resolves to the node's status information.\n */\n public async getNodeStatus(): Promise<NodeStatus> {\n const jsonRpcRequestMethod = JSON_RPC_REQUEST_METHOD.GET_STATUS;\n return await this.sendJsonRPCRequest<NodeStatus>(jsonRpcRequestMethod, []);\n }\n\n /**\n * Sends a post JSON rpc request to the node.\n *\n * @param resource - The rpc method to call.\n * @param params - The parameters to pass to the rpc method.\n *\n * @throws An error if the rpc method returns an error.\n *\n * @returns A promise that resolves as the result of the rpc method.\n */\n protected async sendJsonRPCRequest<T>(\n resource: JSON_RPC_REQUEST_METHOD,\n params: object,\n ): Promise<T> {\n let resp: JsonRpcResponseData<T> = null;\n resp = await this.promisifyJsonRpcCall(resource, params);\n\n // in case of rpc error, rethrow the error.\n if (resp.isError || resp.error) {\n throw resp.error;\n }\n\n return resp.result;\n }\n\n /**\n * Converts a json rpc call to a promise that resolves as a JsonRpcResponseData\n *\n * @privateRemarks\n * If there is an error while sending the request, the function catches the error, the isError\n * property is set to true, the result property set to null, and the error property set to a\n * new Error object with a message indicating that there was an error.\n *\n * @param resource - The rpc method to call.\n * @param params - The parameters to pass to the rpc method.\n *\n * @returns A promise that resolves as a JsonRpcResponseData.\n */\n private async promisifyJsonRpcCall<T>(\n resource: JSON_RPC_REQUEST_METHOD,\n params: object,\n ): Promise<JsonRpcResponseData<T>> {\n let resp: AxiosResponse<JsonRpcResponseData<T>> = null;\n\n const body = {\n jsonrpc: '2.0',\n method: resource,\n params: params,\n id: 0,\n };\n\n try {\n resp = await axios.post(this._nodeUrl, body, { headers: requestHeaders });\n } catch (ex) {\n return {\n isError: true,\n result: null,\n error: new Error('JSON.parse error: ' + String(ex)),\n } as JsonRpcResponseData<T>;\n }\n\n const responseData: JsonRpcResponseData<T> = resp.data;\n\n if (responseData.error) {\n return {\n isError: true,\n result: null,\n error: new Error(responseData.error.message),\n } as JsonRpcResponseData<T>;\n }\n\n return {\n isError: false,\n result: responseData.result as T,\n error: null,\n } as JsonRpcResponseData<T>;\n }\n\n public async nonPersistentCallSC(\n contractAddress: string,\n functionName: string,\n parameter: Uint8Array | Args,\n amount: bigint,\n fee: bigint,\n maxGas: bigint,\n ): Promise<IContractReadOperationResponse> {\n // not clean but bearby doesn't allow us to get its node urls\n const node = PUBLIC_NODE_RPC;\n // Gas amount check\n if (maxGas > MAX_READ_BLOCK_GAS) {\n throw new Error(\n `\n The gas submitted ${maxGas.toString()} exceeds the max. allowed block gas of \n ${MAX_READ_BLOCK_GAS.toString()}\n `,\n );\n }\n\n // convert parameter to an array of numbers\n let argumentArray = [];\n if (parameter instanceof Uint8Array) {\n argumentArray = Array.from(parameter);\n } else {\n argumentArray = Array.from(parameter.serialize());\n }\n // setup the request body\n const data = {\n max_gas: Number(maxGas),\n target_address: contractAddress,\n target_function: functionName,\n parameter: argumentArray,\n caller_address: this._address,\n coins: Number(amount),\n fee: Number(fee),\n };\n const body = [\n {\n jsonrpc: '2.0',\n method: 'execute_read_only_call',\n params: [[data]],\n id: 0,\n },\n ];\n // returns operation ids\n let jsonRpcCallResult: Array<IContractReadOperationData> = [];\n try {\n let resp = await postRequest<Array<IContractReadOperationData>>(\n node,\n body,\n );\n if (resp.isError || resp.error) {\n throw resp.error.message;\n }\n jsonRpcCallResult = resp.result;\n } catch (ex) {\n throw new Error(\n `MassaStation account: error while interacting with smart contract: ${ex}`,\n );\n }\n if (jsonRpcCallResult.length <= 0) {\n throw new Error(\n `Read operation bad response. No results array in json rpc response. Inspect smart contract`,\n );\n }\n if (jsonRpcCallResult[0].result.Error) {\n throw new Error(jsonRpcCallResult[0].result.Error);\n }\n return {\n returnValue: new Uint8Array(jsonRpcCallResult[0].result[0].result.Ok),\n info: jsonRpcCallResult[0],\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"Bearby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AE,IAAI,UAAU,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC;YACrE,IAAI,EAAE,iBAAiB,CAAC,CAAC,CAAC;SAC3B,CAAC;IACJ,CAAC;CACF;AAzUD,sCAyUC","sourcesContent":["import {\n Args,\n IContractReadOperationData,\n IContractReadOperationResponse,\n} from '@massalabs/web3-utils';\nimport { ITransactionDetails } from '..';\nimport { IAccountBalanceResponse, IAccountDetails } from '../account';\nimport { IAccount } from '../account/IAccount';\nimport { web3 } from '@hicaru/bearby.js';\nimport {\n postRequest,\n JsonRpcResponseData,\n} from '../massaStation/RequestHandler';\nimport { BalanceResponse } from './BalanceResponse';\nimport { NodeStatus } from './NodeStatus';\nimport { JSON_RPC_REQUEST_METHOD } from './jsonRpcMethods';\nimport axios, { AxiosRequestHeaders, AxiosResponse } from 'axios';\nimport { IAccountSignOutput } from '../account/AccountSign';\n/**\n * The maximum allowed gas for a read operation\n */\nconst MAX_READ_BLOCK_GAS = BigInt(4_294_967_295);\n\n/**\n * The RPC we are using to query the node\n */\nexport const PUBLIC_NODE_RPC = 'https://buildnet.massa.net/api/v2';\n\nexport enum OperationsType {\n Payment,\n RollBuy,\n RollSell,\n ExecuteSC,\n CallSC,\n}\n\n/**\n * Associates an operation type with a number.\n */\nexport enum OperationTypeId {\n Transaction = 0,\n RollBuy = 1,\n RollSell = 2,\n ExecuteSC = 3,\n CallSC = 4,\n}\n\nconst requestHeaders = {\n Accept:\n 'application/json,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Content-Type': 'application/json',\n} as AxiosRequestHeaders;\n\nexport class BearbyAccount implements IAccount {\n private _providerName: string;\n private _address: string;\n private _name: string;\n private _nodeUrl = PUBLIC_NODE_RPC;\n\n public constructor({ address, name }: IAccountDetails, providerName: string) {\n this._address = address;\n this._name = name ?? 'Bearby_account';\n this._providerName = providerName;\n }\n\n public address(): string {\n return this._address;\n }\n\n public name(): string {\n return this._name;\n }\n\n public providerName(): string {\n return this._providerName;\n }\n\n public async connect() {\n try {\n await web3.wallet.connect();\n } catch (ex) {\n console.log('Bearby connection error: ', ex);\n }\n }\n\n // needs testing\n public async balance(): Promise<IAccountBalanceResponse> {\n await this.connect();\n // Not available on bearby. we have to manually call the api\n const body = {\n jsonrpc: '2.0',\n method: 'get_addresses',\n params: [[this._address]],\n id: 0,\n };\n\n const addressInfos = await postRequest<BalanceResponse>(\n PUBLIC_NODE_RPC,\n body,\n );\n\n if (addressInfos.isError || addressInfos.error) {\n throw addressInfos.error.message;\n }\n return {\n finalBalance: addressInfos.result.result[0].final_balance,\n candidateBalance: addressInfos.result.result[0].candidate_balance,\n } as IAccountBalanceResponse;\n }\n\n // need testing\n public async sign(\n data: Buffer | Uint8Array | string,\n ): Promise<IAccountSignOutput> {\n await this.connect();\n\n let strData: string;\n if (data instanceof Uint8Array) {\n strData = new TextDecoder().decode(data);\n }\n if (data instanceof Buffer) {\n strData = data.toString();\n }\n const signature = await web3.wallet.signMessage(strData);\n return {\n publicKey: signature.publicKey,\n base58Encoded: signature.signature,\n };\n }\n\n // need testing\n public async buyRolls(\n amount: bigint,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n await this.connect();\n const operationId = await web3.massa.buyRolls(amount.toString());\n\n return {\n operationId,\n } as ITransactionDetails;\n }\n\n // need testing\n public async sellRolls(\n amount: bigint,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n await this.connect();\n const operationId = await web3.massa.sellRolls(amount.toString());\n\n return {\n operationId,\n } as ITransactionDetails;\n }\n\n public async sendTransaction(\n amount: bigint,\n recipientAddress: string,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n await this.connect();\n\n const operationId = await web3.massa.payment(\n amount.toString(),\n recipientAddress,\n );\n\n return {\n operationId,\n } as ITransactionDetails;\n }\n\n public async callSC(\n contractAddress: string,\n functionName: string,\n parameter: Args | Uint8Array,\n amount: bigint,\n fee: bigint,\n maxGas: bigint,\n nonPersistentExecution = false,\n ): Promise<ITransactionDetails | IContractReadOperationResponse> {\n await this.connect();\n if (nonPersistentExecution) {\n return this.nonPersistentCallSC(\n contractAddress,\n functionName,\n parameter,\n amount,\n fee,\n maxGas,\n );\n }\n\n let unsafeParameters = Uint8Array.from([]);\n if (parameter instanceof Args) {\n unsafeParameters = Uint8Array.from(parameter.serialize());\n } else {\n unsafeParameters = parameter;\n }\n\n const operationId = await web3.contract.call({\n maxGas: Number(maxGas),\n coins: Number(amount),\n fee: Number(fee),\n targetAddress: contractAddress,\n functionName: functionName,\n unsafeParameters,\n });\n\n return { operationId };\n }\n\n /**\n * Retrieves the node's status.\n *\n * @remarks\n * The returned information includes:\n * - Whether the node is reachable\n * - The number of connected peers\n * - The node's version\n * - The node's configuration parameters\n *\n * @returns A promise that resolves to the node's status information.\n */\n public async getNodeStatus(): Promise<NodeStatus> {\n const jsonRpcRequestMethod = JSON_RPC_REQUEST_METHOD.GET_STATUS;\n return await this.sendJsonRPCRequest<NodeStatus>(jsonRpcRequestMethod, []);\n }\n\n /**\n * Sends a post JSON rpc request to the node.\n *\n * @param resource - The rpc method to call.\n * @param params - The parameters to pass to the rpc method.\n *\n * @throws An error if the rpc method returns an error.\n *\n * @returns A promise that resolves as the result of the rpc method.\n */\n protected async sendJsonRPCRequest<T>(\n resource: JSON_RPC_REQUEST_METHOD,\n params: object,\n ): Promise<T> {\n let resp: JsonRpcResponseData<T> = null;\n resp = await this.promisifyJsonRpcCall(resource, params);\n\n // in case of rpc error, rethrow the error.\n if (resp.isError || resp.error) {\n throw resp.error;\n }\n\n return resp.result;\n }\n\n /**\n * Converts a json rpc call to a promise that resolves as a JsonRpcResponseData\n *\n * @privateRemarks\n * If there is an error while sending the request, the function catches the error, the isError\n * property is set to true, the result property set to null, and the error property set to a\n * new Error object with a message indicating that there was an error.\n *\n * @param resource - The rpc method to call.\n * @param params - The parameters to pass to the rpc method.\n *\n * @returns A promise that resolves as a JsonRpcResponseData.\n */\n private async promisifyJsonRpcCall<T>(\n resource: JSON_RPC_REQUEST_METHOD,\n params: object,\n ): Promise<JsonRpcResponseData<T>> {\n let resp: AxiosResponse<JsonRpcResponseData<T>> = null;\n\n const body = {\n jsonrpc: '2.0',\n method: resource,\n params: params,\n id: 0,\n };\n\n try {\n resp = await axios.post(this._nodeUrl, body, { headers: requestHeaders });\n } catch (ex) {\n return {\n isError: true,\n result: null,\n error: new Error('JSON.parse error: ' + String(ex)),\n } as JsonRpcResponseData<T>;\n }\n\n const responseData: JsonRpcResponseData<T> = resp.data;\n\n if (responseData.error) {\n return {\n isError: true,\n result: null,\n error: new Error(responseData.error.message),\n } as JsonRpcResponseData<T>;\n }\n\n return {\n isError: false,\n result: responseData.result as T,\n error: null,\n } as JsonRpcResponseData<T>;\n }\n\n public async nonPersistentCallSC(\n contractAddress: string,\n functionName: string,\n parameter: Uint8Array | Args,\n amount: bigint,\n fee: bigint,\n maxGas: bigint,\n ): Promise<IContractReadOperationResponse> {\n // not clean but bearby doesn't allow us to get its node urls\n const node = PUBLIC_NODE_RPC;\n // Gas amount check\n if (maxGas > MAX_READ_BLOCK_GAS) {\n throw new Error(\n `\n The gas submitted ${maxGas.toString()} exceeds the max. allowed block gas of \n ${MAX_READ_BLOCK_GAS.toString()}\n `,\n );\n }\n\n // convert parameter to an array of numbers\n let argumentArray = [];\n if (parameter instanceof Uint8Array) {\n argumentArray = Array.from(parameter);\n } else {\n argumentArray = Array.from(parameter.serialize());\n }\n // setup the request body\n const data = {\n max_gas: Number(maxGas),\n target_address: contractAddress,\n target_function: functionName,\n parameter: argumentArray,\n caller_address: this._address,\n coins: Number(amount),\n fee: Number(fee),\n };\n const body = [\n {\n jsonrpc: '2.0',\n method: 'execute_read_only_call',\n params: [[data]],\n id: 0,\n },\n ];\n // returns operation ids\n let jsonRpcCallResult: Array<IContractReadOperationData> = [];\n try {\n let resp = await postRequest<Array<IContractReadOperationData>>(\n node,\n body,\n );\n if (resp.isError || resp.error) {\n throw resp.error.message;\n }\n jsonRpcCallResult = resp.result;\n } catch (ex) {\n throw new Error(\n `MassaStation account: error while interacting with smart contract: ${ex}`,\n );\n }\n if (jsonRpcCallResult.length <= 0) {\n throw new Error(\n `Read operation bad response. No results array in json rpc response. Inspect smart contract`,\n );\n }\n if (jsonRpcCallResult[0].result.Error) {\n throw new Error(jsonRpcCallResult[0].result.Error);\n }\n return {\n returnValue: new Uint8Array(jsonRpcCallResult[0].result[0].result.Ok),\n info: jsonRpcCallResult[0],\n };\n }\n}\n"]}
|
|
@@ -224,7 +224,7 @@ class MassaStationAccount {
|
|
|
224
224
|
nickname: this._name,
|
|
225
225
|
name: functionName,
|
|
226
226
|
at: contractAddress,
|
|
227
|
-
args
|
|
227
|
+
args,
|
|
228
228
|
coins: Number(coins),
|
|
229
229
|
fee: fee ? fee.toString() : '0',
|
|
230
230
|
// If maxGas is not provided, estimation will be done by MS
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MassaStationAccount.js","sourceRoot":"","sources":["../../../src/massaStation/MassaStationAccount.ts"],"names":[],"mappings":";;;AAOA,qDAAgF;AAChF,iEAGgC;AAChC,sDAK+B;AAE/B,wDAAyE;AAEzE,yCAAmD;AAGnD;;GAEG;AACH,MAAM,kBAAkB,GAAG,MAAM,CAAC,UAAa,CAAC,CAAC;AA6BjD;;;;;;;GAOG;AACH,MAAa,mBAAmB;IAK9B;;;;;;;;;;;;OAYG;IACH,YAAmB,EAAE,OAAO,EAAE,IAAI,EAAmB,EAAE,YAAoB;QACzE,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC;IACpC,CAAC;IAED;;OAEG;IACI,OAAO;QACZ,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED;;OAEG;IACI,IAAI;QACT,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED;;OAEG;I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..';\nimport { IAccount } from '../account/IAccount';\nimport { JsonRpcResponseData, getRequest, postRequest } from './RequestHandler';\nimport {\n MASSA_STATION_URL,\n MASSA_STATION_ACCOUNTS_URL,\n} from './MassaStationProvider';\nimport {\n Args,\n IContractReadOperationData,\n IContractReadOperationResponse,\n MAX_GAS_CALL,\n} from '@massalabs/web3-utils';\n\nimport { argsToBase64, uint8ArrayToBase64 } from '../utils/argsToBase64';\nimport { IAccountSignOutput } from '../account/AccountSign';\nimport { encode as base58Encode } from 'bs58check';\nimport { ExecuteFunctionBody } from './types';\n\n/**\n * The maximum allowed gas for a read operation\n */\nconst MAX_READ_BLOCK_GAS = BigInt(4_294_967_295);\n\n/**\n * This interface represents the payload returned by making a call to MassaStation's sign\n * operation `/signOperation` url.\n */\ninterface ISignOperation {\n operation: string;\n batch?: boolean;\n correlationId?: string;\n}\n\n/**\n * This interface represents the the individual wallet's final and pending balances returned by MassaStation\n */\ninterface IBalance {\n final: string;\n pending: string;\n}\n\n/**\n * This interface represents the payload returned by making a call to MassaStation's get balances url.\n */\ninterface IAddressesBalances {\n addressesAttributes: {\n [key: string]: { balance: IBalance };\n };\n}\n\n/**\n * This module contains the MassaStationAccount class. It is responsible for representing an account in\n * the MassaStation wallet.\n *\n * @remarks\n * This class provides methods to interact with MassaStation account's {@link balance} and to {@link sign} messages.\n *\n */\nexport class MassaStationAccount implements IAccount {\n private _providerName: string;\n private _address: string;\n private _name: string;\n\n /**\n * This constructor takes an object of type IAccountDetails and a providerName string as its arguments.\n *\n * @param address - The address of the account.\n * @param name - The name of the account.\n * @param providerName - The name of the provider.\n * @returns An instance of the Account class.\n *\n * @remarks\n * - The Account constructor takes an object of type IAccountDetails and a providerName string as its arguments.\n * - The IAccountDetails object contains the account's address and name.\n * - The providerName string identifies the provider that is used to interact with the blockchain.\n */\n public constructor({ address, name }: IAccountDetails, providerName: string) {\n this._address = address;\n this._name = name;\n this._providerName = providerName;\n }\n\n /**\n * @returns The address of the account.\n */\n public address(): string {\n return this._address;\n }\n\n /**\n * @returns The name of the account.\n */\n public name(): string {\n return this._name;\n }\n\n /**\n * @returns The name of the provider.\n */\n public providerName(): string {\n return this._providerName;\n }\n\n /**\n * This method aims to retrieve the account's balance.\n *\n * @returns A promise that resolves to an object of type IAccountBalanceResponse. It contains the account's balance.\n */\n public async balance(): Promise<IAccountBalanceResponse> {\n let signOpResponse: JsonRpcResponseData<IAddressesBalances> = null;\n try {\n signOpResponse = await getRequest<IAddressesBalances>(\n `${MASSA_STATION_URL}massa/addresses?attributes=balance&addresses=${this._address}`,\n );\n } catch (ex) {\n console.error(`MassaStation account balance error`);\n throw ex;\n }\n if (signOpResponse.isError || signOpResponse.error) {\n throw signOpResponse.error;\n }\n const balance: IBalance =\n signOpResponse.result.addressesAttributes[this._address].balance;\n return {\n finalBalance: balance.final,\n candidateBalance: balance.pending,\n };\n }\n\n /**\n * This method aims to sign a message.\n *\n * @param data - The message to be signed.\n * @returns An IAccountSignResponse object. It contains the signature of the message.\n */\n public async sign(\n data: Buffer | Uint8Array | string,\n ): Promise<IAccountSignOutput> {\n let signOpResponse: JsonRpcResponseData<IAccountSignResponse> = null;\n\n try {\n signOpResponse = await postRequest<IAccountSignResponse>(\n `${MASSA_STATION_ACCOUNTS_URL}/${this._name}/sign`,\n {\n operation: Buffer.from(data).toString('base64'),\n batch: false,\n } as ISignOperation,\n );\n } catch (ex) {\n console.error(`MassaStation account signing error`);\n throw ex;\n }\n\n if (signOpResponse.isError || signOpResponse.error) {\n throw signOpResponse.error;\n }\n\n const signature = base58Encode(\n Buffer.from(signOpResponse.result.signature, 'base64'),\n );\n\n return {\n publicKey: signOpResponse.result.publicKey,\n base58Encoded: signature,\n };\n }\n\n /**\n * This method aims to buy rolls on behalf of the sender.\n *\n * @param amount - The amount of rolls to be bought.\n * @param fee - The fee to be paid for the transaction execution by the node.\n * @returns An ITransactionDetails object. It contains the operationId on the network.\n */\n public async buyRolls(\n amount: bigint,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n let buyRollsOpResponse: JsonRpcResponseData<ITransactionDetails> = null;\n const url = `${MASSA_STATION_ACCOUNTS_URL}/${this._name}/rolls`;\n const body = {\n fee: fee.toString(),\n amount: amount.toString(),\n side: 'buy',\n };\n try {\n buyRollsOpResponse = await postRequest<ITransactionDetails>(url, body);\n } catch (ex) {\n console.error(`MassaStation account: error while buying rolls: ${ex}`);\n throw ex;\n }\n if (buyRollsOpResponse.isError || buyRollsOpResponse.error) {\n throw buyRollsOpResponse.error;\n }\n return buyRollsOpResponse.result;\n }\n\n /**\n * This method aims to sell rolls on behalf of the sender.\n *\n * @param amount - The amount of rolls to be sold.\n * @param fee - The fee to be paid for the transaction execution by the node.\n * @returns An ITransactionDetails object. It contains the operationId on the network.\n */\n public async sellRolls(\n amount: bigint,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n let sellRollsOpResponse: JsonRpcResponseData<ITransactionDetails> = null;\n const url = `${MASSA_STATION_ACCOUNTS_URL}/${this._name}/rolls`;\n const body = {\n fee: fee.toString(),\n amount: amount.toString(),\n side: 'sell',\n };\n try {\n sellRollsOpResponse = await postRequest<ITransactionDetails>(url, body);\n } catch (ex) {\n console.error(`MassaStation account: error while selling rolls: ${ex}`);\n throw ex;\n }\n if (sellRollsOpResponse.isError || sellRollsOpResponse.error) {\n throw sellRollsOpResponse.error;\n }\n return sellRollsOpResponse.result;\n }\n\n /**\n * This method aims to transfer MAS on behalf of the sender to a recipient.\n *\n * @param amount - The amount of MAS (in the smallest unit) to be transferred.\n * @param fee - The fee to be paid for the transaction execution (in the smallest unit).\n * @returns An ITransactionDetails object. It contains the operationId on the network.\n */\n async sendTransaction(\n amount: bigint,\n recipientAddress: string,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n let sendTxOpResponse: JsonRpcResponseData<ITransactionDetails> = null;\n const url = `${MASSA_STATION_ACCOUNTS_URL}/${this._name}/transfer`;\n const body = {\n fee: fee.toString(),\n amount: amount.toString(),\n recipientAddress: recipientAddress,\n };\n\n try {\n sendTxOpResponse = await postRequest<ITransactionDetails>(url, body);\n } catch (ex) {\n console.error(\n `MassaStation account: error while sending transaction: ${ex}`,\n );\n throw ex;\n }\n if (sendTxOpResponse.isError || sendTxOpResponse.error) {\n throw sendTxOpResponse.error;\n }\n return sendTxOpResponse.result;\n }\n\n /**\n * This method aims to interact with a smart contract deployed on the MASSA blockchain.\n *\n * @remarks\n * If dryRun.dryRun is true, the method will dry run the smart contract call and return an\n * IContractReadOperationResponse object which contains all the information about the dry run\n * (state changes, gas used, etc.)\n *\n * @param contractAddress - The address of the smart contract.\n * @param functionName - The name of the function to be called.\n * @param parameter - The parameters as an Args object to be passed to the function.\n * @param amount - The amount of MASSA coins to be sent to the contract (in the smallest unit).\n * @param fee - The fee to be paid for the transaction execution (in the smallest unit).\n * @param maxGas - The maximum amount of gas to be used for the transaction execution.\n * @param nonPersistentExecution - The dryRun object to be passed to the function.\n *\n * @returns if 'nonPersistentExecution' is true, it returns an IContractReadOperationResponse object.\n * Otherwise, it returns an ITransactionDetails object which contains the operationId on the network.\n *\n */\n public async callSC(\n contractAddress: string,\n functionName: string,\n parameter: Uint8Array | Args,\n coins: bigint,\n fee?: bigint,\n maxGas?: bigint,\n nonPersistentExecution = false,\n ): Promise<ITransactionDetails | IContractReadOperationResponse> {\n if (nonPersistentExecution) {\n return this.nonPersistentCallSC(\n contractAddress,\n functionName,\n parameter,\n maxGas,\n );\n }\n // convert parameter to base64\n let args = '';\n if (parameter instanceof Uint8Array) {\n args = uint8ArrayToBase64(parameter);\n } else {\n args = argsToBase64(parameter);\n }\n let CallSCOpResponse: JsonRpcResponseData<ITransactionDetails> = null;\n const url = `${MASSA_STATION_URL}cmd/executeFunction`;\n const body: ExecuteFunctionBody = {\n nickname: this._name,\n name: functionName,\n at: contractAddress,\n args: args,\n coins: Number(coins),\n fee: fee ? fee.toString() : '0',\n // If maxGas is not provided, estimation will be done by MS\n maxGas: maxGas ? maxGas.toString() : '',\n async: true,\n };\n try {\n CallSCOpResponse = await postRequest<ITransactionDetails>(url, body);\n } catch (ex) {\n console.log(\n `MassaStation account: error while interacting with smart contract: ${ex}`,\n );\n throw ex;\n }\n if (CallSCOpResponse.isError || CallSCOpResponse.error) {\n throw CallSCOpResponse.error;\n }\n return CallSCOpResponse.result;\n }\n\n public async getNodeUrlFromMassaStation(): Promise<string> {\n // get the node url from MassaStation\n let nodesResponse: JsonRpcResponseData<unknown> = null;\n let node = '';\n try {\n nodesResponse = await getRequest<unknown>(\n `${MASSA_STATION_URL}massa/node`,\n );\n if (nodesResponse.isError || nodesResponse.error) {\n throw nodesResponse.error.message;\n }\n // transform nodesResponse.result to a json and then get the \"url\" property\n const nodes = nodesResponse.result as { url: string };\n node = nodes.url;\n } catch (ex) {\n throw new Error(`MassaStation nodes retrieval error: ${ex}`);\n }\n return node;\n }\n\n public async nonPersistentCallSC(\n contractAddress: string,\n functionName: string,\n parameter: Uint8Array | Args,\n maxGas?: bigint,\n ): Promise<IContractReadOperationResponse> {\n const node = await this.getNodeUrlFromMassaStation();\n // Gas amount check\n if (maxGas > MAX_READ_BLOCK_GAS) {\n throw new Error(\n `\n The gas submitted ${maxGas.toString()} exceeds the max. allowed block gas of \n ${MAX_READ_BLOCK_GAS.toString()}\n `,\n );\n }\n\n // convert parameter to an array of numbers\n let argumentArray = [];\n if (parameter instanceof Uint8Array) {\n argumentArray = Array.from(parameter);\n } else {\n argumentArray = Array.from(parameter.serialize());\n }\n // setup the request body\n const data = {\n max_gas: maxGas ? Number(maxGas) : MAX_GAS_CALL,\n target_address: contractAddress,\n target_function: functionName,\n parameter: argumentArray,\n caller_address: this._address,\n };\n const body = [\n {\n jsonrpc: '2.0',\n method: 'execute_read_only_call',\n params: [[data]],\n id: 0,\n },\n ];\n // returns operation ids\n let jsonRpcCallResult: Array<IContractReadOperationData> = [];\n try {\n let resp = await postRequest<Array<IContractReadOperationData>>(\n node,\n body,\n );\n if (resp.isError || resp.error) {\n throw resp.error.message;\n }\n jsonRpcCallResult = resp.result;\n } catch (ex) {\n throw new Error(\n `MassaStation account: error while interacting with smart contract: ${ex}`,\n );\n }\n if (jsonRpcCallResult.length <= 0) {\n throw new Error(\n `Read operation bad response. No results array in json rpc response. Inspect smart contract`,\n );\n }\n if (jsonRpcCallResult[0].result.Error) {\n throw new Error(jsonRpcCallResult[0].result.Error);\n }\n return {\n returnValue: new Uint8Array(jsonRpcCallResult[0].result[0].result.Ok),\n info: jsonRpcCallResult[0],\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"MassaStationAccount.js","sourceRoot":"","sources":["../../../src/massaStation/MassaStationAccount.ts"],"names":[],"mappings":";;;AAOA,qDAAgF;AAChF,iEAGgC;AAChC,sDAK+B;AAE/B,wDAAyE;AAEzE,yCAAmD;AAGnD;;GAEG;AACH,MAAM,kBAAkB,GAAG,MAAM,CAAC,UAAa,CAAC,CAAC;AA6BjD;;;;;;;GAOG;AACH,MAAa,mBAAmB;IAK9B;;;;;;;;;;;;OAYG;IACH,YAAmB,EAAE,OAAO,EAAE,IAAI,EAAmB,EAAE,YAAoB;QACzE,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC;IACpC,CAAC;IAED;;OAEG;IACI,OAAO;QACZ,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED;;OAEG;IACI,IAAI;QACT,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED;;OAEG;IACI,YAAY;QACjB,OAAO,IAAI,CAAC,aAAa,CAAC;IAC5B,CAAC;IAED;;;;OAIG;IACI,KAAK,CAAC,OAAO;QAClB,IAAI,cAAc,GAA4C,IAAI,CAAC;QACnE,IAAI;YACF,cAAc,GAAG,MAAM,IAAA,2BAAU,EAC/B,GAAG,wCAAiB,gDAAgD,IAAI,CAAC,QAAQ,EAAE,CACpF,CAAC;SACH;QAAC,OAAO,EAAE,EAAE;YAC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AAiB,GAAsC,EAAE,CAAC;QAC9D,IAAI;YACF,IAAI,IAAI,GAAG,MAAM,IAAA,4BAAW,EAC1B,IAAI,EACJ,IAAI,CACL,CAAC;YACF,IAAI,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,KAAK,EAAE;gBAC9B,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC;aAC1B;YACD,iBAAiB,GAAG,IAAI,CAAC,MAAM,CAAC;SACjC;QAAC,OAAO,EAAE,EAAE;YACX,MAAM,IAAI,KAAK,CACb,sEAAsE,EAAE,EAAE,CAC3E,CAAC;SACH;QACD,IAAI,iBAAiB,CAAC,MAAM,IAAI,CAAC,EAAE;YACjC,MAAM,IAAI,KAAK,CACb,4FAA4F,CAC7F,CAAC;SACH;QACD,IAAI,iBAAiB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,EAAE;YACrC,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;SACpD;QACD,OAAO;YACL,WAAW,EAAE,IAAI,UAAU,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC;YACrE,IAAI,EAAE,iBAAiB,CAAC,CAAC,CAAC;SAC3B,CAAC;IACJ,CAAC;CACF;AA3WD,kDA2WC","sourcesContent":["import {\n IAccountBalanceResponse,\n IAccountDetails,\n IAccountSignResponse,\n ITransactionDetails,\n} from '..';\nimport { IAccount } from '../account/IAccount';\nimport { JsonRpcResponseData, getRequest, postRequest } from './RequestHandler';\nimport {\n MASSA_STATION_URL,\n MASSA_STATION_ACCOUNTS_URL,\n} from './MassaStationProvider';\nimport {\n Args,\n IContractReadOperationData,\n IContractReadOperationResponse,\n MAX_GAS_CALL,\n} from '@massalabs/web3-utils';\n\nimport { argsToBase64, uint8ArrayToBase64 } from '../utils/argsToBase64';\nimport { IAccountSignOutput } from '../account/AccountSign';\nimport { encode as base58Encode } from 'bs58check';\nimport { ExecuteFunctionBody } from './types';\n\n/**\n * The maximum allowed gas for a read operation\n */\nconst MAX_READ_BLOCK_GAS = BigInt(4_294_967_295);\n\n/**\n * This interface represents the payload returned by making a call to MassaStation's sign\n * operation `/signOperation` url.\n */\ninterface ISignOperation {\n operation: string;\n batch?: boolean;\n correlationId?: string;\n}\n\n/**\n * This interface represents the the individual wallet's final and pending balances returned by MassaStation\n */\ninterface IBalance {\n final: string;\n pending: string;\n}\n\n/**\n * This interface represents the payload returned by making a call to MassaStation's get balances url.\n */\ninterface IAddressesBalances {\n addressesAttributes: {\n [key: string]: { balance: IBalance };\n };\n}\n\n/**\n * This module contains the MassaStationAccount class. It is responsible for representing an account in\n * the MassaStation wallet.\n *\n * @remarks\n * This class provides methods to interact with MassaStation account's {@link balance} and to {@link sign} messages.\n *\n */\nexport class MassaStationAccount implements IAccount {\n private _providerName: string;\n private _address: string;\n private _name: string;\n\n /**\n * This constructor takes an object of type IAccountDetails and a providerName string as its arguments.\n *\n * @param address - The address of the account.\n * @param name - The name of the account.\n * @param providerName - The name of the provider.\n * @returns An instance of the Account class.\n *\n * @remarks\n * - The Account constructor takes an object of type IAccountDetails and a providerName string as its arguments.\n * - The IAccountDetails object contains the account's address and name.\n * - The providerName string identifies the provider that is used to interact with the blockchain.\n */\n public constructor({ address, name }: IAccountDetails, providerName: string) {\n this._address = address;\n this._name = name;\n this._providerName = providerName;\n }\n\n /**\n * @returns The address of the account.\n */\n public address(): string {\n return this._address;\n }\n\n /**\n * @returns The name of the account.\n */\n public name(): string {\n return this._name;\n }\n\n /**\n * @returns The name of the provider.\n */\n public providerName(): string {\n return this._providerName;\n }\n\n /**\n * This method aims to retrieve the account's balance.\n *\n * @returns A promise that resolves to an object of type IAccountBalanceResponse. It contains the account's balance.\n */\n public async balance(): Promise<IAccountBalanceResponse> {\n let signOpResponse: JsonRpcResponseData<IAddressesBalances> = null;\n try {\n signOpResponse = await getRequest<IAddressesBalances>(\n `${MASSA_STATION_URL}massa/addresses?attributes=balance&addresses=${this._address}`,\n );\n } catch (ex) {\n console.error(`MassaStation account balance error`);\n throw ex;\n }\n if (signOpResponse.isError || signOpResponse.error) {\n throw signOpResponse.error;\n }\n const balance: IBalance =\n signOpResponse.result.addressesAttributes[this._address].balance;\n return {\n finalBalance: balance.final,\n candidateBalance: balance.pending,\n };\n }\n\n /**\n * This method aims to sign a message.\n *\n * @param data - The message to be signed.\n * @returns An IAccountSignResponse object. It contains the signature of the message.\n */\n public async sign(\n data: Buffer | Uint8Array | string,\n ): Promise<IAccountSignOutput> {\n let signOpResponse: JsonRpcResponseData<IAccountSignResponse> = null;\n\n try {\n signOpResponse = await postRequest<IAccountSignResponse>(\n `${MASSA_STATION_ACCOUNTS_URL}/${this._name}/sign`,\n {\n operation: Buffer.from(data).toString('base64'),\n batch: false,\n } as ISignOperation,\n );\n } catch (ex) {\n console.error(`MassaStation account signing error`);\n throw ex;\n }\n\n if (signOpResponse.isError || signOpResponse.error) {\n throw signOpResponse.error;\n }\n\n const signature = base58Encode(\n Buffer.from(signOpResponse.result.signature, 'base64'),\n );\n\n return {\n publicKey: signOpResponse.result.publicKey,\n base58Encoded: signature,\n };\n }\n\n /**\n * This method aims to buy rolls on behalf of the sender.\n *\n * @param amount - The amount of rolls to be bought.\n * @param fee - The fee to be paid for the transaction execution by the node.\n * @returns An ITransactionDetails object. It contains the operationId on the network.\n */\n public async buyRolls(\n amount: bigint,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n let buyRollsOpResponse: JsonRpcResponseData<ITransactionDetails> = null;\n const url = `${MASSA_STATION_ACCOUNTS_URL}/${this._name}/rolls`;\n const body = {\n fee: fee.toString(),\n amount: amount.toString(),\n side: 'buy',\n };\n try {\n buyRollsOpResponse = await postRequest<ITransactionDetails>(url, body);\n } catch (ex) {\n console.error(`MassaStation account: error while buying rolls: ${ex}`);\n throw ex;\n }\n if (buyRollsOpResponse.isError || buyRollsOpResponse.error) {\n throw buyRollsOpResponse.error;\n }\n return buyRollsOpResponse.result;\n }\n\n /**\n * This method aims to sell rolls on behalf of the sender.\n *\n * @param amount - The amount of rolls to be sold.\n * @param fee - The fee to be paid for the transaction execution by the node.\n * @returns An ITransactionDetails object. It contains the operationId on the network.\n */\n public async sellRolls(\n amount: bigint,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n let sellRollsOpResponse: JsonRpcResponseData<ITransactionDetails> = null;\n const url = `${MASSA_STATION_ACCOUNTS_URL}/${this._name}/rolls`;\n const body = {\n fee: fee.toString(),\n amount: amount.toString(),\n side: 'sell',\n };\n try {\n sellRollsOpResponse = await postRequest<ITransactionDetails>(url, body);\n } catch (ex) {\n console.error(`MassaStation account: error while selling rolls: ${ex}`);\n throw ex;\n }\n if (sellRollsOpResponse.isError || sellRollsOpResponse.error) {\n throw sellRollsOpResponse.error;\n }\n return sellRollsOpResponse.result;\n }\n\n /**\n * This method aims to transfer MAS on behalf of the sender to a recipient.\n *\n * @param amount - The amount of MAS (in the smallest unit) to be transferred.\n * @param fee - The fee to be paid for the transaction execution (in the smallest unit).\n * @returns An ITransactionDetails object. It contains the operationId on the network.\n */\n async sendTransaction(\n amount: bigint,\n recipientAddress: string,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n let sendTxOpResponse: JsonRpcResponseData<ITransactionDetails> = null;\n const url = `${MASSA_STATION_ACCOUNTS_URL}/${this._name}/transfer`;\n const body = {\n fee: fee.toString(),\n amount: amount.toString(),\n recipientAddress: recipientAddress,\n };\n\n try {\n sendTxOpResponse = await postRequest<ITransactionDetails>(url, body);\n } catch (ex) {\n console.error(\n `MassaStation account: error while sending transaction: ${ex}`,\n );\n throw ex;\n }\n if (sendTxOpResponse.isError || sendTxOpResponse.error) {\n throw sendTxOpResponse.error;\n }\n return sendTxOpResponse.result;\n }\n\n /**\n * This method aims to interact with a smart contract deployed on the MASSA blockchain.\n *\n * @remarks\n * If dryRun.dryRun is true, the method will dry run the smart contract call and return an\n * IContractReadOperationResponse object which contains all the information about the dry run\n * (state changes, gas used, etc.)\n *\n * @param contractAddress - The address of the smart contract.\n * @param functionName - The name of the function to be called.\n * @param parameter - The parameters as an Args object to be passed to the function.\n * @param amount - The amount of MASSA coins to be sent to the contract (in the smallest unit).\n * @param fee - The fee to be paid for the transaction execution (in the smallest unit).\n * @param maxGas - The maximum amount of gas to be used for the transaction execution.\n * @param nonPersistentExecution - The dryRun object to be passed to the function.\n *\n * @returns if 'nonPersistentExecution' is true, it returns an IContractReadOperationResponse object.\n * Otherwise, it returns an ITransactionDetails object which contains the operationId on the network.\n *\n */\n public async callSC(\n contractAddress: string,\n functionName: string,\n parameter: Uint8Array | Args,\n coins: bigint,\n fee?: bigint,\n maxGas?: bigint,\n nonPersistentExecution = false,\n ): Promise<ITransactionDetails | IContractReadOperationResponse> {\n if (nonPersistentExecution) {\n return this.nonPersistentCallSC(\n contractAddress,\n functionName,\n parameter,\n maxGas,\n );\n }\n // convert parameter to base64\n let args = '';\n if (parameter instanceof Uint8Array) {\n args = uint8ArrayToBase64(parameter);\n } else {\n args = argsToBase64(parameter);\n }\n let CallSCOpResponse: JsonRpcResponseData<ITransactionDetails> = null;\n const url = `${MASSA_STATION_URL}cmd/executeFunction`;\n const body: ExecuteFunctionBody = {\n nickname: this._name,\n name: functionName,\n at: contractAddress,\n args,\n coins: Number(coins),\n fee: fee ? fee.toString() : '0',\n // If maxGas is not provided, estimation will be done by MS\n maxGas: maxGas ? maxGas.toString() : '',\n async: true,\n };\n try {\n CallSCOpResponse = await postRequest<ITransactionDetails>(url, body);\n } catch (ex) {\n console.log(\n `MassaStation account: error while interacting with smart contract: ${ex}`,\n );\n throw ex;\n }\n if (CallSCOpResponse.isError || CallSCOpResponse.error) {\n throw CallSCOpResponse.error;\n }\n return CallSCOpResponse.result;\n }\n\n public async getNodeUrlFromMassaStation(): Promise<string> {\n // get the node url from MassaStation\n let nodesResponse: JsonRpcResponseData<unknown> = null;\n let node = '';\n try {\n nodesResponse = await getRequest<unknown>(\n `${MASSA_STATION_URL}massa/node`,\n );\n if (nodesResponse.isError || nodesResponse.error) {\n throw nodesResponse.error.message;\n }\n // transform nodesResponse.result to a json and then get the \"url\" property\n const nodes = nodesResponse.result as { url: string };\n node = nodes.url;\n } catch (ex) {\n throw new Error(`MassaStation nodes retrieval error: ${ex}`);\n }\n return node;\n }\n\n public async nonPersistentCallSC(\n contractAddress: string,\n functionName: string,\n parameter: Uint8Array | Args,\n maxGas?: bigint,\n ): Promise<IContractReadOperationResponse> {\n const node = await this.getNodeUrlFromMassaStation();\n // Gas amount check\n if (maxGas > MAX_READ_BLOCK_GAS) {\n throw new Error(\n `\n The gas submitted ${maxGas.toString()} exceeds the max. allowed block gas of \n ${MAX_READ_BLOCK_GAS.toString()}\n `,\n );\n }\n\n // convert parameter to an array of numbers\n let argumentArray = [];\n if (parameter instanceof Uint8Array) {\n argumentArray = Array.from(parameter);\n } else {\n argumentArray = Array.from(parameter.serialize());\n }\n // setup the request body\n const data = {\n max_gas: maxGas ? Number(maxGas) : MAX_GAS_CALL,\n target_address: contractAddress,\n target_function: functionName,\n parameter: argumentArray,\n caller_address: this._address,\n };\n const body = [\n {\n jsonrpc: '2.0',\n method: 'execute_read_only_call',\n params: [[data]],\n id: 0,\n },\n ];\n // returns operation ids\n let jsonRpcCallResult: Array<IContractReadOperationData> = [];\n try {\n let resp = await postRequest<Array<IContractReadOperationData>>(\n node,\n body,\n );\n if (resp.isError || resp.error) {\n throw resp.error.message;\n }\n jsonRpcCallResult = resp.result;\n } catch (ex) {\n throw new Error(\n `MassaStation account: error while interacting with smart contract: ${ex}`,\n );\n }\n if (jsonRpcCallResult.length <= 0) {\n throw new Error(\n `Read operation bad response. No results array in json rpc response. Inspect smart contract`,\n );\n }\n if (jsonRpcCallResult[0].result.Error) {\n throw new Error(jsonRpcCallResult[0].result.Error);\n }\n return {\n returnValue: new Uint8Array(jsonRpcCallResult[0].result[0].result.Ok),\n info: jsonRpcCallResult[0],\n };\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BearbyAccount.d.ts","sourceRoot":"","sources":["../../../src/bearbyWallet/BearbyAccount.ts"],"names":[],"mappings":";AAAA,OAAO,EACL,IAAI,EAEJ,8BAA8B,EAC/B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,mBAAmB,EAAE,MAAM,IAAI,CAAC;AACzC,OAAO,EAAE,uBAAuB,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AACtE,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAO/C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAE3D,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;
|
|
1
|
+
{"version":3,"file":"BearbyAccount.d.ts","sourceRoot":"","sources":["../../../src/bearbyWallet/BearbyAccount.ts"],"names":[],"mappings":";AAAA,OAAO,EACL,IAAI,EAEJ,8BAA8B,EAC/B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,mBAAmB,EAAE,MAAM,IAAI,CAAC;AACzC,OAAO,EAAE,uBAAuB,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AACtE,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAO/C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAE3D,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAM5D;;GAEG;AACH,eAAO,MAAM,eAAe,sCAAsC,CAAC;AAEnE,oBAAY,cAAc;IACxB,OAAO,IAAA;IACP,OAAO,IAAA;IACP,QAAQ,IAAA;IACR,SAAS,IAAA;IACT,MAAM,IAAA;CACP;AAED;;GAEG;AACH,oBAAY,eAAe;IACzB,WAAW,IAAI;IACf,OAAO,IAAI;IACX,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AAC,CAAC;IAYb;;;;;;;;;;;;OAYG;YACW,oBAAoB;IAwCrB,mBAAmB,CAC9B,eAAe,EAAE,MAAM,EACvB,YAAY,EAAE,MAAM,EACpB,SAAS,EAAE,UAAU,GAAG,IAAI,EAC5B,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,8BAA8B,CAAC;CAmE3C"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
+
import { Args, } from '@massalabs/web3-utils';
|
|
1
2
|
import { web3 } from '@hicaru/bearby.js';
|
|
2
3
|
import { postRequest, } from '../massaStation/RequestHandler';
|
|
3
4
|
import { JSON_RPC_REQUEST_METHOD } from './jsonRpcMethods';
|
|
4
5
|
import axios from 'axios';
|
|
5
|
-
import { isArrayOfNumbers } from '../utils/typeCheck';
|
|
6
6
|
/**
|
|
7
7
|
* The maximum allowed gas for a read operation
|
|
8
8
|
*/
|
|
@@ -124,15 +124,20 @@ export class BearbyAccount {
|
|
|
124
124
|
if (nonPersistentExecution) {
|
|
125
125
|
return this.nonPersistentCallSC(contractAddress, functionName, parameter, amount, fee, maxGas);
|
|
126
126
|
}
|
|
127
|
+
let unsafeParameters = Uint8Array.from([]);
|
|
128
|
+
if (parameter instanceof Args) {
|
|
129
|
+
unsafeParameters = Uint8Array.from(parameter.serialize());
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
unsafeParameters = parameter;
|
|
133
|
+
}
|
|
127
134
|
const operationId = await web3.contract.call({
|
|
128
135
|
maxGas: Number(maxGas),
|
|
129
136
|
coins: Number(amount),
|
|
130
137
|
fee: Number(fee),
|
|
131
138
|
targetAddress: contractAddress,
|
|
132
139
|
functionName: functionName,
|
|
133
|
-
unsafeParameters
|
|
134
|
-
? parameter
|
|
135
|
-
: parameter.serialize(),
|
|
140
|
+
unsafeParameters,
|
|
136
141
|
});
|
|
137
142
|
return { operationId };
|
|
138
143
|
}
|
|
@@ -1 +1 @@
|
|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KAAK,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;SACpD;QACD,OAAO;YACL,WAAW,EAAE,IAAI,UAAU,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC;YACrE,IAAI,EAAE,iBAAiB,CAAC,CAAC,CAAC;SAC3B,CAAC;IACJ,CAAC;CACF","sourcesContent":["import {\n Args,\n IContractReadOperationData,\n IContractReadOperationResponse,\n} from '@massalabs/web3-utils';\nimport { ITransactionDetails } from '..';\nimport { IAccountBalanceResponse, IAccountDetails } from '../account';\nimport { IAccount } from '../account/IAccount';\nimport { web3 } from '@hicaru/bearby.js';\nimport {\n postRequest,\n JsonRpcResponseData,\n} from '../massaStation/RequestHandler';\nimport { BalanceResponse } from './BalanceResponse';\nimport { NodeStatus } from './NodeStatus';\nimport { JSON_RPC_REQUEST_METHOD } from './jsonRpcMethods';\nimport axios, { AxiosRequestHeaders, AxiosResponse } from 'axios';\nimport { IAccountSignOutput } from '../account/AccountSign';\nimport { isArrayOfNumbers } from '../utils/typeCheck';\n/**\n * The maximum allowed gas for a read operation\n */\nconst MAX_READ_BLOCK_GAS = BigInt(4_294_967_295);\n\n/**\n * The RPC we are using to query the node\n */\nexport const PUBLIC_NODE_RPC = 'https://buildnet.massa.net/api/v2';\n\nexport enum OperationsType {\n Payment,\n RollBuy,\n RollSell,\n ExecuteSC,\n CallSC,\n}\n\n/**\n * Associates an operation type with a number.\n */\nexport enum OperationTypeId {\n Transaction = 0,\n RollBuy = 1,\n RollSell = 2,\n ExecuteSC = 3,\n CallSC = 4,\n}\n\nconst requestHeaders = {\n Accept:\n 'application/json,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Content-Type': 'application/json',\n} as AxiosRequestHeaders;\n\nexport class BearbyAccount implements IAccount {\n private _providerName: string;\n private _address: string;\n private _name: string;\n private _nodeUrl = PUBLIC_NODE_RPC;\n\n public constructor({ address, name }: IAccountDetails, providerName: string) {\n this._address = address;\n this._name = name ?? 'Bearby_account';\n this._providerName = providerName;\n }\n\n public address(): string {\n return this._address;\n }\n\n public name(): string {\n return this._name;\n }\n\n public providerName(): string {\n return this._providerName;\n }\n\n public async connect() {\n try {\n await web3.wallet.connect();\n } catch (ex) {\n console.log('Bearby connection error: ', ex);\n }\n }\n\n // needs testing\n public async balance(): Promise<IAccountBalanceResponse> {\n await this.connect();\n // Not available on bearby. we have to manually call the api\n const body = {\n jsonrpc: '2.0',\n method: 'get_addresses',\n params: [[this._address]],\n id: 0,\n };\n\n const addressInfos = await postRequest<BalanceResponse>(\n PUBLIC_NODE_RPC,\n body,\n );\n\n if (addressInfos.isError || addressInfos.error) {\n throw addressInfos.error.message;\n }\n return {\n finalBalance: addressInfos.result.result[0].final_balance,\n candidateBalance: addressInfos.result.result[0].candidate_balance,\n } as IAccountBalanceResponse;\n }\n\n // need testing\n public async sign(\n data: Buffer | Uint8Array | string,\n ): Promise<IAccountSignOutput> {\n await this.connect();\n\n let strData: string;\n if (data instanceof Uint8Array) {\n strData = new TextDecoder().decode(data);\n }\n if (data instanceof Buffer) {\n strData = data.toString();\n }\n const signature = await web3.wallet.signMessage(strData);\n return {\n publicKey: signature.publicKey,\n base58Encoded: signature.signature,\n };\n }\n\n // need testing\n public async buyRolls(\n amount: bigint,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n await this.connect();\n const operationId = await web3.massa.buyRolls(amount.toString());\n\n return {\n operationId,\n } as ITransactionDetails;\n }\n\n // need testing\n public async sellRolls(\n amount: bigint,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n await this.connect();\n const operationId = await web3.massa.sellRolls(amount.toString());\n\n return {\n operationId,\n } as ITransactionDetails;\n }\n\n public async sendTransaction(\n amount: bigint,\n recipientAddress: string,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n await this.connect();\n\n const operationId = await web3.massa.payment(\n amount.toString(),\n recipientAddress,\n );\n\n return {\n operationId,\n } as ITransactionDetails;\n }\n\n public async callSC(\n contractAddress: string,\n functionName: string,\n parameter: Args | Uint8Array,\n amount: bigint,\n fee: bigint,\n maxGas: bigint,\n nonPersistentExecution = false,\n ): Promise<ITransactionDetails | IContractReadOperationResponse> {\n await this.connect();\n if (nonPersistentExecution) {\n return this.nonPersistentCallSC(\n contractAddress,\n functionName,\n parameter,\n amount,\n fee,\n maxGas,\n );\n }\n\n const operationId = await web3.contract.call({\n maxGas: Number(maxGas),\n coins: Number(amount),\n fee: Number(fee),\n targetAddress: contractAddress,\n functionName: functionName,\n unsafeParameters: isArrayOfNumbers(parameter)\n ? (parameter as Uint8Array)\n : ((parameter as Args).serialize() as unknown as Uint8Array),\n });\n\n return { operationId };\n }\n\n /**\n * Retrieves the node's status.\n *\n * @remarks\n * The returned information includes:\n * - Whether the node is reachable\n * - The number of connected peers\n * - The node's version\n * - The node's configuration parameters\n *\n * @returns A promise that resolves to the node's status information.\n */\n public async getNodeStatus(): Promise<NodeStatus> {\n const jsonRpcRequestMethod = JSON_RPC_REQUEST_METHOD.GET_STATUS;\n return await this.sendJsonRPCRequest<NodeStatus>(jsonRpcRequestMethod, []);\n }\n\n /**\n * Sends a post JSON rpc request to the node.\n *\n * @param resource - The rpc method to call.\n * @param params - The parameters to pass to the rpc method.\n *\n * @throws An error if the rpc method returns an error.\n *\n * @returns A promise that resolves as the result of the rpc method.\n */\n protected async sendJsonRPCRequest<T>(\n resource: JSON_RPC_REQUEST_METHOD,\n params: object,\n ): Promise<T> {\n let resp: JsonRpcResponseData<T> = null;\n resp = await this.promisifyJsonRpcCall(resource, params);\n\n // in case of rpc error, rethrow the error.\n if (resp.isError || resp.error) {\n throw resp.error;\n }\n\n return resp.result;\n }\n\n /**\n * Converts a json rpc call to a promise that resolves as a JsonRpcResponseData\n *\n * @privateRemarks\n * If there is an error while sending the request, the function catches the error, the isError\n * property is set to true, the result property set to null, and the error property set to a\n * new Error object with a message indicating that there was an error.\n *\n * @param resource - The rpc method to call.\n * @param params - The parameters to pass to the rpc method.\n *\n * @returns A promise that resolves as a JsonRpcResponseData.\n */\n private async promisifyJsonRpcCall<T>(\n resource: JSON_RPC_REQUEST_METHOD,\n params: object,\n ): Promise<JsonRpcResponseData<T>> {\n let resp: AxiosResponse<JsonRpcResponseData<T>> = null;\n\n const body = {\n jsonrpc: '2.0',\n method: resource,\n params: params,\n id: 0,\n };\n\n try {\n resp = await axios.post(this._nodeUrl, body, { headers: requestHeaders });\n } catch (ex) {\n return {\n isError: true,\n result: null,\n error: new Error('JSON.parse error: ' + String(ex)),\n } as JsonRpcResponseData<T>;\n }\n\n const responseData: JsonRpcResponseData<T> = resp.data;\n\n if (responseData.error) {\n return {\n isError: true,\n result: null,\n error: new Error(responseData.error.message),\n } as JsonRpcResponseData<T>;\n }\n\n return {\n isError: false,\n result: responseData.result as T,\n error: null,\n } as JsonRpcResponseData<T>;\n }\n\n public async nonPersistentCallSC(\n contractAddress: string,\n functionName: string,\n parameter: Uint8Array | Args,\n amount: bigint,\n fee: bigint,\n maxGas: bigint,\n ): Promise<IContractReadOperationResponse> {\n // not clean but bearby doesn't allow us to get its node urls\n const node = PUBLIC_NODE_RPC;\n // Gas amount check\n if (maxGas > MAX_READ_BLOCK_GAS) {\n throw new Error(\n `\n The gas submitted ${maxGas.toString()} exceeds the max. allowed block gas of \n ${MAX_READ_BLOCK_GAS.toString()}\n `,\n );\n }\n\n // convert parameter to an array of numbers\n let argumentArray = [];\n if (parameter instanceof Uint8Array) {\n argumentArray = Array.from(parameter);\n } else {\n argumentArray = Array.from(parameter.serialize());\n }\n // setup the request body\n const data = {\n max_gas: Number(maxGas),\n target_address: contractAddress,\n target_function: functionName,\n parameter: argumentArray,\n caller_address: this._address,\n coins: Number(amount),\n fee: Number(fee),\n };\n const body = [\n {\n jsonrpc: '2.0',\n method: 'execute_read_only_call',\n params: [[data]],\n id: 0,\n },\n ];\n // returns operation ids\n let jsonRpcCallResult: Array<IContractReadOperationData> = [];\n try {\n let resp = await postRequest<Array<IContractReadOperationData>>(\n node,\n body,\n );\n if (resp.isError || resp.error) {\n throw resp.error.message;\n }\n jsonRpcCallResult = resp.result;\n } catch (ex) {\n throw new Error(\n `MassaStation account: error while interacting with smart contract: ${ex}`,\n );\n }\n if (jsonRpcCallResult.length <= 0) {\n throw new Error(\n `Read operation bad response. No results array in json rpc response. Inspect smart contract`,\n );\n }\n if (jsonRpcCallResult[0].result.Error) {\n throw new Error(jsonRpcCallResult[0].result.Error);\n }\n return {\n returnValue: new Uint8Array(jsonRpcCallResult[0].result[0].result.Ok),\n info: jsonRpcCallResult[0],\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"BearbyAccount.js","sourceRoot":"","sources":["../../../src/bearbyWallet/BearbyAccount.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,IAAI,GAGL,MAAM,uBAAuB,CAAC;AAI/B,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACzC,OAAO,EACL,WAAW,GAEZ,MAAM,gCAAgC,CAAC;AAGxC,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,KAA6C,MAAM,OAAO,CAAC;AAElE;;GAEG;AACH,MAAM,kBAAkB,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAEjD;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,mCAAmC,CAAC;AAEnE,MAAM,CAAN,IAAY,cAMX;AAND,WAAY,cAAc;IACxB,yDAAO,CAAA;IACP,yDAAO,CAAA;IACP,2DAAQ,CAAA;IACR,6DAAS,CAAA;IACT,uDAAM,CAAA;AACR,CAAC,EANW,cAAc,KAAd,cAAc,QAMzB;AAED;;GAEG;AACH,MAAM,CAAN,IAAY,eAMX;AAND,WAAY,eAAe;IACzB,mEAAe,CAAA;IACf,2DAAW,CAAA;IACX,6DAAY,CAAA;IACZ,+DAAa,CAAA;IACb,yDAAU,CAAA;AACZ,CAAC,EANW,eAA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CAAC;QAC9D,IAAI;YACF,IAAI,IAAI,GAAG,MAAM,WAAW,CAC1B,IAAI,EACJ,IAAI,CACL,CAAC;YACF,IAAI,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,KAAK,EAAE;gBAC9B,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC;aAC1B;YACD,iBAAiB,GAAG,IAAI,CAAC,MAAM,CAAC;SACjC;QAAC,OAAO,EAAE,EAAE;YACX,MAAM,IAAI,KAAK,CACb,sEAAsE,EAAE,EAAE,CAC3E,CAAC;SACH;QACD,IAAI,iBAAiB,CAAC,MAAM,IAAI,CAAC,EAAE;YACjC,MAAM,IAAI,KAAK,CACb,4FAA4F,CAC7F,CAAC;SACH;QACD,IAAI,iBAAiB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,EAAE;YACrC,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;SACpD;QACD,OAAO;YACL,WAAW,EAAE,IAAI,UAAU,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC;YACrE,IAAI,EAAE,iBAAiB,CAAC,CAAC,CAAC;SAC3B,CAAC;IACJ,CAAC;CACF","sourcesContent":["import {\n Args,\n IContractReadOperationData,\n IContractReadOperationResponse,\n} from '@massalabs/web3-utils';\nimport { ITransactionDetails } from '..';\nimport { IAccountBalanceResponse, IAccountDetails } from '../account';\nimport { IAccount } from '../account/IAccount';\nimport { web3 } from '@hicaru/bearby.js';\nimport {\n postRequest,\n JsonRpcResponseData,\n} from '../massaStation/RequestHandler';\nimport { BalanceResponse } from './BalanceResponse';\nimport { NodeStatus } from './NodeStatus';\nimport { JSON_RPC_REQUEST_METHOD } from './jsonRpcMethods';\nimport axios, { AxiosRequestHeaders, AxiosResponse } from 'axios';\nimport { IAccountSignOutput } from '../account/AccountSign';\n/**\n * The maximum allowed gas for a read operation\n */\nconst MAX_READ_BLOCK_GAS = BigInt(4_294_967_295);\n\n/**\n * The RPC we are using to query the node\n */\nexport const PUBLIC_NODE_RPC = 'https://buildnet.massa.net/api/v2';\n\nexport enum OperationsType {\n Payment,\n RollBuy,\n RollSell,\n ExecuteSC,\n CallSC,\n}\n\n/**\n * Associates an operation type with a number.\n */\nexport enum OperationTypeId {\n Transaction = 0,\n RollBuy = 1,\n RollSell = 2,\n ExecuteSC = 3,\n CallSC = 4,\n}\n\nconst requestHeaders = {\n Accept:\n 'application/json,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Content-Type': 'application/json',\n} as AxiosRequestHeaders;\n\nexport class BearbyAccount implements IAccount {\n private _providerName: string;\n private _address: string;\n private _name: string;\n private _nodeUrl = PUBLIC_NODE_RPC;\n\n public constructor({ address, name }: IAccountDetails, providerName: string) {\n this._address = address;\n this._name = name ?? 'Bearby_account';\n this._providerName = providerName;\n }\n\n public address(): string {\n return this._address;\n }\n\n public name(): string {\n return this._name;\n }\n\n public providerName(): string {\n return this._providerName;\n }\n\n public async connect() {\n try {\n await web3.wallet.connect();\n } catch (ex) {\n console.log('Bearby connection error: ', ex);\n }\n }\n\n // needs testing\n public async balance(): Promise<IAccountBalanceResponse> {\n await this.connect();\n // Not available on bearby. we have to manually call the api\n const body = {\n jsonrpc: '2.0',\n method: 'get_addresses',\n params: [[this._address]],\n id: 0,\n };\n\n const addressInfos = await postRequest<BalanceResponse>(\n PUBLIC_NODE_RPC,\n body,\n );\n\n if (addressInfos.isError || addressInfos.error) {\n throw addressInfos.error.message;\n }\n return {\n finalBalance: addressInfos.result.result[0].final_balance,\n candidateBalance: addressInfos.result.result[0].candidate_balance,\n } as IAccountBalanceResponse;\n }\n\n // need testing\n public async sign(\n data: Buffer | Uint8Array | string,\n ): Promise<IAccountSignOutput> {\n await this.connect();\n\n let strData: string;\n if (data instanceof Uint8Array) {\n strData = new TextDecoder().decode(data);\n }\n if (data instanceof Buffer) {\n strData = data.toString();\n }\n const signature = await web3.wallet.signMessage(strData);\n return {\n publicKey: signature.publicKey,\n base58Encoded: signature.signature,\n };\n }\n\n // need testing\n public async buyRolls(\n amount: bigint,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n await this.connect();\n const operationId = await web3.massa.buyRolls(amount.toString());\n\n return {\n operationId,\n } as ITransactionDetails;\n }\n\n // need testing\n public async sellRolls(\n amount: bigint,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n await this.connect();\n const operationId = await web3.massa.sellRolls(amount.toString());\n\n return {\n operationId,\n } as ITransactionDetails;\n }\n\n public async sendTransaction(\n amount: bigint,\n recipientAddress: string,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n await this.connect();\n\n const operationId = await web3.massa.payment(\n amount.toString(),\n recipientAddress,\n );\n\n return {\n operationId,\n } as ITransactionDetails;\n }\n\n public async callSC(\n contractAddress: string,\n functionName: string,\n parameter: Args | Uint8Array,\n amount: bigint,\n fee: bigint,\n maxGas: bigint,\n nonPersistentExecution = false,\n ): Promise<ITransactionDetails | IContractReadOperationResponse> {\n await this.connect();\n if (nonPersistentExecution) {\n return this.nonPersistentCallSC(\n contractAddress,\n functionName,\n parameter,\n amount,\n fee,\n maxGas,\n );\n }\n\n let unsafeParameters = Uint8Array.from([]);\n if (parameter instanceof Args) {\n unsafeParameters = Uint8Array.from(parameter.serialize());\n } else {\n unsafeParameters = parameter;\n }\n\n const operationId = await web3.contract.call({\n maxGas: Number(maxGas),\n coins: Number(amount),\n fee: Number(fee),\n targetAddress: contractAddress,\n functionName: functionName,\n unsafeParameters,\n });\n\n return { operationId };\n }\n\n /**\n * Retrieves the node's status.\n *\n * @remarks\n * The returned information includes:\n * - Whether the node is reachable\n * - The number of connected peers\n * - The node's version\n * - The node's configuration parameters\n *\n * @returns A promise that resolves to the node's status information.\n */\n public async getNodeStatus(): Promise<NodeStatus> {\n const jsonRpcRequestMethod = JSON_RPC_REQUEST_METHOD.GET_STATUS;\n return await this.sendJsonRPCRequest<NodeStatus>(jsonRpcRequestMethod, []);\n }\n\n /**\n * Sends a post JSON rpc request to the node.\n *\n * @param resource - The rpc method to call.\n * @param params - The parameters to pass to the rpc method.\n *\n * @throws An error if the rpc method returns an error.\n *\n * @returns A promise that resolves as the result of the rpc method.\n */\n protected async sendJsonRPCRequest<T>(\n resource: JSON_RPC_REQUEST_METHOD,\n params: object,\n ): Promise<T> {\n let resp: JsonRpcResponseData<T> = null;\n resp = await this.promisifyJsonRpcCall(resource, params);\n\n // in case of rpc error, rethrow the error.\n if (resp.isError || resp.error) {\n throw resp.error;\n }\n\n return resp.result;\n }\n\n /**\n * Converts a json rpc call to a promise that resolves as a JsonRpcResponseData\n *\n * @privateRemarks\n * If there is an error while sending the request, the function catches the error, the isError\n * property is set to true, the result property set to null, and the error property set to a\n * new Error object with a message indicating that there was an error.\n *\n * @param resource - The rpc method to call.\n * @param params - The parameters to pass to the rpc method.\n *\n * @returns A promise that resolves as a JsonRpcResponseData.\n */\n private async promisifyJsonRpcCall<T>(\n resource: JSON_RPC_REQUEST_METHOD,\n params: object,\n ): Promise<JsonRpcResponseData<T>> {\n let resp: AxiosResponse<JsonRpcResponseData<T>> = null;\n\n const body = {\n jsonrpc: '2.0',\n method: resource,\n params: params,\n id: 0,\n };\n\n try {\n resp = await axios.post(this._nodeUrl, body, { headers: requestHeaders });\n } catch (ex) {\n return {\n isError: true,\n result: null,\n error: new Error('JSON.parse error: ' + String(ex)),\n } as JsonRpcResponseData<T>;\n }\n\n const responseData: JsonRpcResponseData<T> = resp.data;\n\n if (responseData.error) {\n return {\n isError: true,\n result: null,\n error: new Error(responseData.error.message),\n } as JsonRpcResponseData<T>;\n }\n\n return {\n isError: false,\n result: responseData.result as T,\n error: null,\n } as JsonRpcResponseData<T>;\n }\n\n public async nonPersistentCallSC(\n contractAddress: string,\n functionName: string,\n parameter: Uint8Array | Args,\n amount: bigint,\n fee: bigint,\n maxGas: bigint,\n ): Promise<IContractReadOperationResponse> {\n // not clean but bearby doesn't allow us to get its node urls\n const node = PUBLIC_NODE_RPC;\n // Gas amount check\n if (maxGas > MAX_READ_BLOCK_GAS) {\n throw new Error(\n `\n The gas submitted ${maxGas.toString()} exceeds the max. allowed block gas of \n ${MAX_READ_BLOCK_GAS.toString()}\n `,\n );\n }\n\n // convert parameter to an array of numbers\n let argumentArray = [];\n if (parameter instanceof Uint8Array) {\n argumentArray = Array.from(parameter);\n } else {\n argumentArray = Array.from(parameter.serialize());\n }\n // setup the request body\n const data = {\n max_gas: Number(maxGas),\n target_address: contractAddress,\n target_function: functionName,\n parameter: argumentArray,\n caller_address: this._address,\n coins: Number(amount),\n fee: Number(fee),\n };\n const body = [\n {\n jsonrpc: '2.0',\n method: 'execute_read_only_call',\n params: [[data]],\n id: 0,\n },\n ];\n // returns operation ids\n let jsonRpcCallResult: Array<IContractReadOperationData> = [];\n try {\n let resp = await postRequest<Array<IContractReadOperationData>>(\n node,\n body,\n );\n if (resp.isError || resp.error) {\n throw resp.error.message;\n }\n jsonRpcCallResult = resp.result;\n } catch (ex) {\n throw new Error(\n `MassaStation account: error while interacting with smart contract: ${ex}`,\n );\n }\n if (jsonRpcCallResult.length <= 0) {\n throw new Error(\n `Read operation bad response. No results array in json rpc response. Inspect smart contract`,\n );\n }\n if (jsonRpcCallResult[0].result.Error) {\n throw new Error(jsonRpcCallResult[0].result.Error);\n }\n return {\n returnValue: new Uint8Array(jsonRpcCallResult[0].result[0].result.Ok),\n info: jsonRpcCallResult[0],\n };\n }\n}\n"]}
|
|
@@ -224,7 +224,7 @@ export class MassaStationAccount {
|
|
|
224
224
|
nickname: this._name,
|
|
225
225
|
name: functionName,
|
|
226
226
|
at: contractAddress,
|
|
227
|
-
args
|
|
227
|
+
args,
|
|
228
228
|
coins: Number(coins),
|
|
229
229
|
fee: fee ? fee.toString() : '0',
|
|
230
230
|
// If maxGas is not provided, estimation will be done by MS
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MassaStationAcc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AAI,CACL,CAAC;YACF,IAAI,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,KAAK,EAAE;gBAC9B,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC;aAC1B;YACD,iBAAiB,GAAG,IAAI,CAAC,MAAM,CAAC;SACjC;QAAC,OAAO,EAAE,EAAE;YACX,MAAM,IAAI,KAAK,CACb,sEAAsE,EAAE,EAAE,CAC3E,CAAC;SACH;QACD,IAAI,iBAAiB,CAAC,MAAM,IAAI,CAAC,EAAE;YACjC,MAAM,IAAI,KAAK,CACb,4FAA4F,CAC7F,CAAC;SACH;QACD,IAAI,iBAAiB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,EAAE;YACrC,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;SACpD;QACD,OAAO;YACL,WAAW,EAAE,IAAI,UAAU,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC;YACrE,IAAI,EAAE,iBAAiB,CAAC,CAAC,CAAC;SAC3B,CAAC;IACJ,CAAC;CACF","sourcesContent":["import {\n IAccountBalanceResponse,\n IAccountDetails,\n IAccountSignResponse,\n ITransactionDetails,\n} from '..';\nimport { IAccount } from '../account/IAccount';\nimport { JsonRpcResponseData, getRequest, postRequest } from './RequestHandler';\nimport {\n MASSA_STATION_URL,\n MASSA_STATION_ACCOUNTS_URL,\n} from './MassaStationProvider';\nimport {\n Args,\n IContractReadOperationData,\n IContractReadOperationResponse,\n MAX_GAS_CALL,\n} from '@massalabs/web3-utils';\n\nimport { argsToBase64, uint8ArrayToBase64 } from '../utils/argsToBase64';\nimport { IAccountSignOutput } from '../account/AccountSign';\nimport { encode as base58Encode } from 'bs58check';\nimport { ExecuteFunctionBody } from './types';\n\n/**\n * The maximum allowed gas for a read operation\n */\nconst MAX_READ_BLOCK_GAS = BigInt(4_294_967_295);\n\n/**\n * This interface represents the payload returned by making a call to MassaStation's sign\n * operation `/signOperation` url.\n */\ninterface ISignOperation {\n operation: string;\n batch?: boolean;\n correlationId?: string;\n}\n\n/**\n * This interface represents the the individual wallet's final and pending balances returned by MassaStation\n */\ninterface IBalance {\n final: string;\n pending: string;\n}\n\n/**\n * This interface represents the payload returned by making a call to MassaStation's get balances url.\n */\ninterface IAddressesBalances {\n addressesAttributes: {\n [key: string]: { balance: IBalance };\n };\n}\n\n/**\n * This module contains the MassaStationAccount class. It is responsible for representing an account in\n * the MassaStation wallet.\n *\n * @remarks\n * This class provides methods to interact with MassaStation account's {@link balance} and to {@link sign} messages.\n *\n */\nexport class MassaStationAccount implements IAccount {\n private _providerName: string;\n private _address: string;\n private _name: string;\n\n /**\n * This constructor takes an object of type IAccountDetails and a providerName string as its arguments.\n *\n * @param address - The address of the account.\n * @param name - The name of the account.\n * @param providerName - The name of the provider.\n * @returns An instance of the Account class.\n *\n * @remarks\n * - The Account constructor takes an object of type IAccountDetails and a providerName string as its arguments.\n * - The IAccountDetails object contains the account's address and name.\n * - The providerName string identifies the provider that is used to interact with the blockchain.\n */\n public constructor({ address, name }: IAccountDetails, providerName: string) {\n this._address = address;\n this._name = name;\n this._providerName = providerName;\n }\n\n /**\n * @returns The address of the account.\n */\n public address(): string {\n return this._address;\n }\n\n /**\n * @returns The name of the account.\n */\n public name(): string {\n return this._name;\n }\n\n /**\n * @returns The name of the provider.\n */\n public providerName(): string {\n return this._providerName;\n }\n\n /**\n * This method aims to retrieve the account's balance.\n *\n * @returns A promise that resolves to an object of type IAccountBalanceResponse. It contains the account's balance.\n */\n public async balance(): Promise<IAccountBalanceResponse> {\n let signOpResponse: JsonRpcResponseData<IAddressesBalances> = null;\n try {\n signOpResponse = await getRequest<IAddressesBalances>(\n `${MASSA_STATION_URL}massa/addresses?attributes=balance&addresses=${this._address}`,\n );\n } catch (ex) {\n console.error(`MassaStation account balance error`);\n throw ex;\n }\n if (signOpResponse.isError || signOpResponse.error) {\n throw signOpResponse.error;\n }\n const balance: IBalance =\n signOpResponse.result.addressesAttributes[this._address].balance;\n return {\n finalBalance: balance.final,\n candidateBalance: balance.pending,\n };\n }\n\n /**\n * This method aims to sign a message.\n *\n * @param data - The message to be signed.\n * @returns An IAccountSignResponse object. It contains the signature of the message.\n */\n public async sign(\n data: Buffer | Uint8Array | string,\n ): Promise<IAccountSignOutput> {\n let signOpResponse: JsonRpcResponseData<IAccountSignResponse> = null;\n\n try {\n signOpResponse = await postRequest<IAccountSignResponse>(\n `${MASSA_STATION_ACCOUNTS_URL}/${this._name}/sign`,\n {\n operation: Buffer.from(data).toString('base64'),\n batch: false,\n } as ISignOperation,\n );\n } catch (ex) {\n console.error(`MassaStation account signing error`);\n throw ex;\n }\n\n if (signOpResponse.isError || signOpResponse.error) {\n throw signOpResponse.error;\n }\n\n const signature = base58Encode(\n Buffer.from(signOpResponse.result.signature, 'base64'),\n );\n\n return {\n publicKey: signOpResponse.result.publicKey,\n base58Encoded: signature,\n };\n }\n\n /**\n * This method aims to buy rolls on behalf of the sender.\n *\n * @param amount - The amount of rolls to be bought.\n * @param fee - The fee to be paid for the transaction execution by the node.\n * @returns An ITransactionDetails object. It contains the operationId on the network.\n */\n public async buyRolls(\n amount: bigint,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n let buyRollsOpResponse: JsonRpcResponseData<ITransactionDetails> = null;\n const url = `${MASSA_STATION_ACCOUNTS_URL}/${this._name}/rolls`;\n const body = {\n fee: fee.toString(),\n amount: amount.toString(),\n side: 'buy',\n };\n try {\n buyRollsOpResponse = await postRequest<ITransactionDetails>(url, body);\n } catch (ex) {\n console.error(`MassaStation account: error while buying rolls: ${ex}`);\n throw ex;\n }\n if (buyRollsOpResponse.isError || buyRollsOpResponse.error) {\n throw buyRollsOpResponse.error;\n }\n return buyRollsOpResponse.result;\n }\n\n /**\n * This method aims to sell rolls on behalf of the sender.\n *\n * @param amount - The amount of rolls to be sold.\n * @param fee - The fee to be paid for the transaction execution by the node.\n * @returns An ITransactionDetails object. It contains the operationId on the network.\n */\n public async sellRolls(\n amount: bigint,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n let sellRollsOpResponse: JsonRpcResponseData<ITransactionDetails> = null;\n const url = `${MASSA_STATION_ACCOUNTS_URL}/${this._name}/rolls`;\n const body = {\n fee: fee.toString(),\n amount: amount.toString(),\n side: 'sell',\n };\n try {\n sellRollsOpResponse = await postRequest<ITransactionDetails>(url, body);\n } catch (ex) {\n console.error(`MassaStation account: error while selling rolls: ${ex}`);\n throw ex;\n }\n if (sellRollsOpResponse.isError || sellRollsOpResponse.error) {\n throw sellRollsOpResponse.error;\n }\n return sellRollsOpResponse.result;\n }\n\n /**\n * This method aims to transfer MAS on behalf of the sender to a recipient.\n *\n * @param amount - The amount of MAS (in the smallest unit) to be transferred.\n * @param fee - The fee to be paid for the transaction execution (in the smallest unit).\n * @returns An ITransactionDetails object. It contains the operationId on the network.\n */\n async sendTransaction(\n amount: bigint,\n recipientAddress: string,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n let sendTxOpResponse: JsonRpcResponseData<ITransactionDetails> = null;\n const url = `${MASSA_STATION_ACCOUNTS_URL}/${this._name}/transfer`;\n const body = {\n fee: fee.toString(),\n amount: amount.toString(),\n recipientAddress: recipientAddress,\n };\n\n try {\n sendTxOpResponse = await postRequest<ITransactionDetails>(url, body);\n } catch (ex) {\n console.error(\n `MassaStation account: error while sending transaction: ${ex}`,\n );\n throw ex;\n }\n if (sendTxOpResponse.isError || sendTxOpResponse.error) {\n throw sendTxOpResponse.error;\n }\n return sendTxOpResponse.result;\n }\n\n /**\n * This method aims to interact with a smart contract deployed on the MASSA blockchain.\n *\n * @remarks\n * If dryRun.dryRun is true, the method will dry run the smart contract call and return an\n * IContractReadOperationResponse object which contains all the information about the dry run\n * (state changes, gas used, etc.)\n *\n * @param contractAddress - The address of the smart contract.\n * @param functionName - The name of the function to be called.\n * @param parameter - The parameters as an Args object to be passed to the function.\n * @param amount - The amount of MASSA coins to be sent to the contract (in the smallest unit).\n * @param fee - The fee to be paid for the transaction execution (in the smallest unit).\n * @param maxGas - The maximum amount of gas to be used for the transaction execution.\n * @param nonPersistentExecution - The dryRun object to be passed to the function.\n *\n * @returns if 'nonPersistentExecution' is true, it returns an IContractReadOperationResponse object.\n * Otherwise, it returns an ITransactionDetails object which contains the operationId on the network.\n *\n */\n public async callSC(\n contractAddress: string,\n functionName: string,\n parameter: Uint8Array | Args,\n coins: bigint,\n fee?: bigint,\n maxGas?: bigint,\n nonPersistentExecution = false,\n ): Promise<ITransactionDetails | IContractReadOperationResponse> {\n if (nonPersistentExecution) {\n return this.nonPersistentCallSC(\n contractAddress,\n functionName,\n parameter,\n maxGas,\n );\n }\n // convert parameter to base64\n let args = '';\n if (parameter instanceof Uint8Array) {\n args = uint8ArrayToBase64(parameter);\n } else {\n args = argsToBase64(parameter);\n }\n let CallSCOpResponse: JsonRpcResponseData<ITransactionDetails> = null;\n const url = `${MASSA_STATION_URL}cmd/executeFunction`;\n const body: ExecuteFunctionBody = {\n nickname: this._name,\n name: functionName,\n at: contractAddress,\n args: args,\n coins: Number(coins),\n fee: fee ? fee.toString() : '0',\n // If maxGas is not provided, estimation will be done by MS\n maxGas: maxGas ? maxGas.toString() : '',\n async: true,\n };\n try {\n CallSCOpResponse = await postRequest<ITransactionDetails>(url, body);\n } catch (ex) {\n console.log(\n `MassaStation account: error while interacting with smart contract: ${ex}`,\n );\n throw ex;\n }\n if (CallSCOpResponse.isError || CallSCOpResponse.error) {\n throw CallSCOpResponse.error;\n }\n return CallSCOpResponse.result;\n }\n\n public async getNodeUrlFromMassaStation(): Promise<string> {\n // get the node url from MassaStation\n let nodesResponse: JsonRpcResponseData<unknown> = null;\n let node = '';\n try {\n nodesResponse = await getRequest<unknown>(\n `${MASSA_STATION_URL}massa/node`,\n );\n if (nodesResponse.isError || nodesResponse.error) {\n throw nodesResponse.error.message;\n }\n // transform nodesResponse.result to a json and then get the \"url\" property\n const nodes = nodesResponse.result as { url: string };\n node = nodes.url;\n } catch (ex) {\n throw new Error(`MassaStation nodes retrieval error: ${ex}`);\n }\n return node;\n }\n\n public async nonPersistentCallSC(\n contractAddress: string,\n functionName: string,\n parameter: Uint8Array | Args,\n maxGas?: bigint,\n ): Promise<IContractReadOperationResponse> {\n const node = await this.getNodeUrlFromMassaStation();\n // Gas amount check\n if (maxGas > MAX_READ_BLOCK_GAS) {\n throw new Error(\n `\n The gas submitted ${maxGas.toString()} exceeds the max. allowed block gas of \n ${MAX_READ_BLOCK_GAS.toString()}\n `,\n );\n }\n\n // convert parameter to an array of numbers\n let argumentArray = [];\n if (parameter instanceof Uint8Array) {\n argumentArray = Array.from(parameter);\n } else {\n argumentArray = Array.from(parameter.serialize());\n }\n // setup the request body\n const data = {\n max_gas: maxGas ? Number(maxGas) : MAX_GAS_CALL,\n target_address: contractAddress,\n target_function: functionName,\n parameter: argumentArray,\n caller_address: this._address,\n };\n const body = [\n {\n jsonrpc: '2.0',\n method: 'execute_read_only_call',\n params: [[data]],\n id: 0,\n },\n ];\n // returns operation ids\n let jsonRpcCallResult: Array<IContractReadOperationData> = [];\n try {\n let resp = await postRequest<Array<IContractReadOperationData>>(\n node,\n body,\n );\n if (resp.isError || resp.error) {\n throw resp.error.message;\n }\n jsonRpcCallResult = resp.result;\n } catch (ex) {\n throw new Error(\n `MassaStation account: error while interacting with smart contract: ${ex}`,\n );\n }\n if (jsonRpcCallResult.length <= 0) {\n throw new Error(\n `Read operation bad response. No results array in json rpc response. Inspect smart contract`,\n );\n }\n if (jsonRpcCallResult[0].result.Error) {\n throw new Error(jsonRpcCallResult[0].result.Error);\n }\n return {\n returnValue: new Uint8Array(jsonRpcCallResult[0].result[0].result.Ok),\n info: jsonRpcCallResult[0],\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"MassaStationAccount.js","sourceRoot":"","sources":["../../../src/massaStation/MassaStationAccount.ts"],"names":[],"mappings":"AAOA,OAAO,EAAuB,UA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,CAAC,KAAK,CAAC,OAAO,CAAC;aAC1B;YACD,iBAAiB,GAAG,IAAI,CAAC,MAAM,CAAC;SACjC;QAAC,OAAO,EAAE,EAAE;YACX,MAAM,IAAI,KAAK,CACb,sEAAsE,EAAE,EAAE,CAC3E,CAAC;SACH;QACD,IAAI,iBAAiB,CAAC,MAAM,IAAI,CAAC,EAAE;YACjC,MAAM,IAAI,KAAK,CACb,4FAA4F,CAC7F,CAAC;SACH;QACD,IAAI,iBAAiB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,EAAE;YACrC,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;SACpD;QACD,OAAO;YACL,WAAW,EAAE,IAAI,UAAU,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC;YACrE,IAAI,EAAE,iBAAiB,CAAC,CAAC,CAAC;SAC3B,CAAC;IACJ,CAAC;CACF","sourcesContent":["import {\n IAccountBalanceResponse,\n IAccountDetails,\n IAccountSignResponse,\n ITransactionDetails,\n} from '..';\nimport { IAccount } from '../account/IAccount';\nimport { JsonRpcResponseData, getRequest, postRequest } from './RequestHandler';\nimport {\n MASSA_STATION_URL,\n MASSA_STATION_ACCOUNTS_URL,\n} from './MassaStationProvider';\nimport {\n Args,\n IContractReadOperationData,\n IContractReadOperationResponse,\n MAX_GAS_CALL,\n} from '@massalabs/web3-utils';\n\nimport { argsToBase64, uint8ArrayToBase64 } from '../utils/argsToBase64';\nimport { IAccountSignOutput } from '../account/AccountSign';\nimport { encode as base58Encode } from 'bs58check';\nimport { ExecuteFunctionBody } from './types';\n\n/**\n * The maximum allowed gas for a read operation\n */\nconst MAX_READ_BLOCK_GAS = BigInt(4_294_967_295);\n\n/**\n * This interface represents the payload returned by making a call to MassaStation's sign\n * operation `/signOperation` url.\n */\ninterface ISignOperation {\n operation: string;\n batch?: boolean;\n correlationId?: string;\n}\n\n/**\n * This interface represents the the individual wallet's final and pending balances returned by MassaStation\n */\ninterface IBalance {\n final: string;\n pending: string;\n}\n\n/**\n * This interface represents the payload returned by making a call to MassaStation's get balances url.\n */\ninterface IAddressesBalances {\n addressesAttributes: {\n [key: string]: { balance: IBalance };\n };\n}\n\n/**\n * This module contains the MassaStationAccount class. It is responsible for representing an account in\n * the MassaStation wallet.\n *\n * @remarks\n * This class provides methods to interact with MassaStation account's {@link balance} and to {@link sign} messages.\n *\n */\nexport class MassaStationAccount implements IAccount {\n private _providerName: string;\n private _address: string;\n private _name: string;\n\n /**\n * This constructor takes an object of type IAccountDetails and a providerName string as its arguments.\n *\n * @param address - The address of the account.\n * @param name - The name of the account.\n * @param providerName - The name of the provider.\n * @returns An instance of the Account class.\n *\n * @remarks\n * - The Account constructor takes an object of type IAccountDetails and a providerName string as its arguments.\n * - The IAccountDetails object contains the account's address and name.\n * - The providerName string identifies the provider that is used to interact with the blockchain.\n */\n public constructor({ address, name }: IAccountDetails, providerName: string) {\n this._address = address;\n this._name = name;\n this._providerName = providerName;\n }\n\n /**\n * @returns The address of the account.\n */\n public address(): string {\n return this._address;\n }\n\n /**\n * @returns The name of the account.\n */\n public name(): string {\n return this._name;\n }\n\n /**\n * @returns The name of the provider.\n */\n public providerName(): string {\n return this._providerName;\n }\n\n /**\n * This method aims to retrieve the account's balance.\n *\n * @returns A promise that resolves to an object of type IAccountBalanceResponse. It contains the account's balance.\n */\n public async balance(): Promise<IAccountBalanceResponse> {\n let signOpResponse: JsonRpcResponseData<IAddressesBalances> = null;\n try {\n signOpResponse = await getRequest<IAddressesBalances>(\n `${MASSA_STATION_URL}massa/addresses?attributes=balance&addresses=${this._address}`,\n );\n } catch (ex) {\n console.error(`MassaStation account balance error`);\n throw ex;\n }\n if (signOpResponse.isError || signOpResponse.error) {\n throw signOpResponse.error;\n }\n const balance: IBalance =\n signOpResponse.result.addressesAttributes[this._address].balance;\n return {\n finalBalance: balance.final,\n candidateBalance: balance.pending,\n };\n }\n\n /**\n * This method aims to sign a message.\n *\n * @param data - The message to be signed.\n * @returns An IAccountSignResponse object. It contains the signature of the message.\n */\n public async sign(\n data: Buffer | Uint8Array | string,\n ): Promise<IAccountSignOutput> {\n let signOpResponse: JsonRpcResponseData<IAccountSignResponse> = null;\n\n try {\n signOpResponse = await postRequest<IAccountSignResponse>(\n `${MASSA_STATION_ACCOUNTS_URL}/${this._name}/sign`,\n {\n operation: Buffer.from(data).toString('base64'),\n batch: false,\n } as ISignOperation,\n );\n } catch (ex) {\n console.error(`MassaStation account signing error`);\n throw ex;\n }\n\n if (signOpResponse.isError || signOpResponse.error) {\n throw signOpResponse.error;\n }\n\n const signature = base58Encode(\n Buffer.from(signOpResponse.result.signature, 'base64'),\n );\n\n return {\n publicKey: signOpResponse.result.publicKey,\n base58Encoded: signature,\n };\n }\n\n /**\n * This method aims to buy rolls on behalf of the sender.\n *\n * @param amount - The amount of rolls to be bought.\n * @param fee - The fee to be paid for the transaction execution by the node.\n * @returns An ITransactionDetails object. It contains the operationId on the network.\n */\n public async buyRolls(\n amount: bigint,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n let buyRollsOpResponse: JsonRpcResponseData<ITransactionDetails> = null;\n const url = `${MASSA_STATION_ACCOUNTS_URL}/${this._name}/rolls`;\n const body = {\n fee: fee.toString(),\n amount: amount.toString(),\n side: 'buy',\n };\n try {\n buyRollsOpResponse = await postRequest<ITransactionDetails>(url, body);\n } catch (ex) {\n console.error(`MassaStation account: error while buying rolls: ${ex}`);\n throw ex;\n }\n if (buyRollsOpResponse.isError || buyRollsOpResponse.error) {\n throw buyRollsOpResponse.error;\n }\n return buyRollsOpResponse.result;\n }\n\n /**\n * This method aims to sell rolls on behalf of the sender.\n *\n * @param amount - The amount of rolls to be sold.\n * @param fee - The fee to be paid for the transaction execution by the node.\n * @returns An ITransactionDetails object. It contains the operationId on the network.\n */\n public async sellRolls(\n amount: bigint,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n let sellRollsOpResponse: JsonRpcResponseData<ITransactionDetails> = null;\n const url = `${MASSA_STATION_ACCOUNTS_URL}/${this._name}/rolls`;\n const body = {\n fee: fee.toString(),\n amount: amount.toString(),\n side: 'sell',\n };\n try {\n sellRollsOpResponse = await postRequest<ITransactionDetails>(url, body);\n } catch (ex) {\n console.error(`MassaStation account: error while selling rolls: ${ex}`);\n throw ex;\n }\n if (sellRollsOpResponse.isError || sellRollsOpResponse.error) {\n throw sellRollsOpResponse.error;\n }\n return sellRollsOpResponse.result;\n }\n\n /**\n * This method aims to transfer MAS on behalf of the sender to a recipient.\n *\n * @param amount - The amount of MAS (in the smallest unit) to be transferred.\n * @param fee - The fee to be paid for the transaction execution (in the smallest unit).\n * @returns An ITransactionDetails object. It contains the operationId on the network.\n */\n async sendTransaction(\n amount: bigint,\n recipientAddress: string,\n fee: bigint,\n ): Promise<ITransactionDetails> {\n let sendTxOpResponse: JsonRpcResponseData<ITransactionDetails> = null;\n const url = `${MASSA_STATION_ACCOUNTS_URL}/${this._name}/transfer`;\n const body = {\n fee: fee.toString(),\n amount: amount.toString(),\n recipientAddress: recipientAddress,\n };\n\n try {\n sendTxOpResponse = await postRequest<ITransactionDetails>(url, body);\n } catch (ex) {\n console.error(\n `MassaStation account: error while sending transaction: ${ex}`,\n );\n throw ex;\n }\n if (sendTxOpResponse.isError || sendTxOpResponse.error) {\n throw sendTxOpResponse.error;\n }\n return sendTxOpResponse.result;\n }\n\n /**\n * This method aims to interact with a smart contract deployed on the MASSA blockchain.\n *\n * @remarks\n * If dryRun.dryRun is true, the method will dry run the smart contract call and return an\n * IContractReadOperationResponse object which contains all the information about the dry run\n * (state changes, gas used, etc.)\n *\n * @param contractAddress - The address of the smart contract.\n * @param functionName - The name of the function to be called.\n * @param parameter - The parameters as an Args object to be passed to the function.\n * @param amount - The amount of MASSA coins to be sent to the contract (in the smallest unit).\n * @param fee - The fee to be paid for the transaction execution (in the smallest unit).\n * @param maxGas - The maximum amount of gas to be used for the transaction execution.\n * @param nonPersistentExecution - The dryRun object to be passed to the function.\n *\n * @returns if 'nonPersistentExecution' is true, it returns an IContractReadOperationResponse object.\n * Otherwise, it returns an ITransactionDetails object which contains the operationId on the network.\n *\n */\n public async callSC(\n contractAddress: string,\n functionName: string,\n parameter: Uint8Array | Args,\n coins: bigint,\n fee?: bigint,\n maxGas?: bigint,\n nonPersistentExecution = false,\n ): Promise<ITransactionDetails | IContractReadOperationResponse> {\n if (nonPersistentExecution) {\n return this.nonPersistentCallSC(\n contractAddress,\n functionName,\n parameter,\n maxGas,\n );\n }\n // convert parameter to base64\n let args = '';\n if (parameter instanceof Uint8Array) {\n args = uint8ArrayToBase64(parameter);\n } else {\n args = argsToBase64(parameter);\n }\n let CallSCOpResponse: JsonRpcResponseData<ITransactionDetails> = null;\n const url = `${MASSA_STATION_URL}cmd/executeFunction`;\n const body: ExecuteFunctionBody = {\n nickname: this._name,\n name: functionName,\n at: contractAddress,\n args,\n coins: Number(coins),\n fee: fee ? fee.toString() : '0',\n // If maxGas is not provided, estimation will be done by MS\n maxGas: maxGas ? maxGas.toString() : '',\n async: true,\n };\n try {\n CallSCOpResponse = await postRequest<ITransactionDetails>(url, body);\n } catch (ex) {\n console.log(\n `MassaStation account: error while interacting with smart contract: ${ex}`,\n );\n throw ex;\n }\n if (CallSCOpResponse.isError || CallSCOpResponse.error) {\n throw CallSCOpResponse.error;\n }\n return CallSCOpResponse.result;\n }\n\n public async getNodeUrlFromMassaStation(): Promise<string> {\n // get the node url from MassaStation\n let nodesResponse: JsonRpcResponseData<unknown> = null;\n let node = '';\n try {\n nodesResponse = await getRequest<unknown>(\n `${MASSA_STATION_URL}massa/node`,\n );\n if (nodesResponse.isError || nodesResponse.error) {\n throw nodesResponse.error.message;\n }\n // transform nodesResponse.result to a json and then get the \"url\" property\n const nodes = nodesResponse.result as { url: string };\n node = nodes.url;\n } catch (ex) {\n throw new Error(`MassaStation nodes retrieval error: ${ex}`);\n }\n return node;\n }\n\n public async nonPersistentCallSC(\n contractAddress: string,\n functionName: string,\n parameter: Uint8Array | Args,\n maxGas?: bigint,\n ): Promise<IContractReadOperationResponse> {\n const node = await this.getNodeUrlFromMassaStation();\n // Gas amount check\n if (maxGas > MAX_READ_BLOCK_GAS) {\n throw new Error(\n `\n The gas submitted ${maxGas.toString()} exceeds the max. allowed block gas of \n ${MAX_READ_BLOCK_GAS.toString()}\n `,\n );\n }\n\n // convert parameter to an array of numbers\n let argumentArray = [];\n if (parameter instanceof Uint8Array) {\n argumentArray = Array.from(parameter);\n } else {\n argumentArray = Array.from(parameter.serialize());\n }\n // setup the request body\n const data = {\n max_gas: maxGas ? Number(maxGas) : MAX_GAS_CALL,\n target_address: contractAddress,\n target_function: functionName,\n parameter: argumentArray,\n caller_address: this._address,\n };\n const body = [\n {\n jsonrpc: '2.0',\n method: 'execute_read_only_call',\n params: [[data]],\n id: 0,\n },\n ];\n // returns operation ids\n let jsonRpcCallResult: Array<IContractReadOperationData> = [];\n try {\n let resp = await postRequest<Array<IContractReadOperationData>>(\n node,\n body,\n );\n if (resp.isError || resp.error) {\n throw resp.error.message;\n }\n jsonRpcCallResult = resp.result;\n } catch (ex) {\n throw new Error(\n `MassaStation account: error while interacting with smart contract: ${ex}`,\n );\n }\n if (jsonRpcCallResult.length <= 0) {\n throw new Error(\n `Read operation bad response. No results array in json rpc response. Inspect smart contract`,\n );\n }\n if (jsonRpcCallResult[0].result.Error) {\n throw new Error(jsonRpcCallResult[0].result.Error);\n }\n return {\n returnValue: new Uint8Array(jsonRpcCallResult[0].result[0].result.Ok),\n info: jsonRpcCallResult[0],\n };\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@massalabs/wallet-provider",
|
|
3
|
-
"version": "1.5.2-dev.
|
|
3
|
+
"version": "1.5.2-dev.20231221133250",
|
|
4
4
|
"description": "massa's wallet provider",
|
|
5
5
|
"main": "dist/esm/index.js",
|
|
6
6
|
"module": "dist/esm/index.js",
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
"clean-dist": "rimraf dist/*",
|
|
13
13
|
"build-esm": "tsc --project tsconfig.esm.json",
|
|
14
14
|
"build-commonjs": "tsc --project tsconfig.commonjs.json",
|
|
15
|
-
"build": "npm
|
|
15
|
+
"build": "npm-run-all clean-dist build-*",
|
|
16
16
|
"test-extension:serve-dapp": "cd test-extension/dapp-vite && npm run preview",
|
|
17
17
|
"test-extension": "cd ./test-extension && npx playwright test",
|
|
18
18
|
"unit-test-commonjs": "jest --config ./jest.config.commonjs.js",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"typeCheck.d.ts","sourceRoot":"","sources":["../../../src/utils/typeCheck.ts"],"names":[],"mappings":"AACA,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,GAAG,GAAG,KAAK,IAAI,MAAM,EAAE,CAI9D"}
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.isArrayOfNumbers = void 0;
|
|
4
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
5
|
-
function isArrayOfNumbers(input) {
|
|
6
|
-
return (Array.isArray(input) && input.every((item) => typeof item === 'number'));
|
|
7
|
-
}
|
|
8
|
-
exports.isArrayOfNumbers = isArrayOfNumbers;
|
|
9
|
-
//# sourceMappingURL=typeCheck.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"typeCheck.js","sourceRoot":"","sources":["../../../src/utils/typeCheck.ts"],"names":[],"mappings":";;;AAAA,8DAA8D;AAC9D,SAAgB,gBAAgB,CAAC,KAAU;IACzC,OAAO,CACL,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,IAAI,KAAK,QAAQ,CAAC,CACxE,CAAC;AACJ,CAAC;AAJD,4CAIC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function isArrayOfNumbers(input: any): input is number[] {\n return (\n Array.isArray(input) && input.every((item) => typeof item === 'number')\n );\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"typeCheck.d.ts","sourceRoot":"","sources":["../../../src/utils/typeCheck.ts"],"names":[],"mappings":"AACA,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,GAAG,GAAG,KAAK,IAAI,MAAM,EAAE,CAI9D"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"typeCheck.js","sourceRoot":"","sources":["../../../src/utils/typeCheck.ts"],"names":[],"mappings":"AAAA,8DAA8D;AAC9D,MAAM,UAAU,gBAAgB,CAAC,KAAU;IACzC,OAAO,CACL,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,IAAI,KAAK,QAAQ,CAAC,CACxE,CAAC;AACJ,CAAC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function isArrayOfNumbers(input: any): input is number[] {\n return (\n Array.isArray(input) && input.every((item) => typeof item === 'number')\n );\n}\n"]}
|