moralisweb3 / moralis-js-sdk Goto Github PK
View Code? Open in Web Editor NEWMoralis Official Javascript SDK
Home Page: https://docs.moralis.io
License: Other
Moralis Official Javascript SDK
Home Page: https://docs.moralis.io
License: Other
Events with arguments of type indexed address[]
cannot be properly synced. The table is created but never populated.
I've worked quite a bit on the issue, making sure I've got everything set up properly.
Given the code below, after setting up Event Sync I get DB table entries for all events but the ones that have an indexed address[]
argument
0.0.347
I try to create new sell order in React app, but I get "Your wallet failed to sign your order correctly. Try a different wallet!".
const createSellOrder = async () => {
const expirationTime = Math.round(Date.now() / 1000 + 60 * 60 * 24);
const startAmount = 1000;
const endAmount = 100;
await Moralis.Plugins.opensea.createSellOrder({
network: "testnet",
tokenAddress: "0xeBc81Ad820D43611E4BF4B03bE07E30ea1CB8224",
tokenId: "1",
tokenType: "ERC721",
userAddress: "0x0f40f1f61C234e4Be3e14021c4EE77B76Da19580",
startAmount,
endAmount,
expirationTime: startAmount > endAmount && expirationTime, // Only set if you startAmount > endAmount
});
console.log("Create Sell Order Successful");
};
I get a request to subscribe, then subscribe it and after that I have error: "Your wallet failed to sign your order correctly. Try a different wallet!".
"Create Sell Order Successful" in the console without errors.
Server
0.0.369
Client
0.0.104
MacOS Monterey
Chrome version 100.0.4896.127
Material Design:
"Material is a design system โ backed by open-source code โ that helps teams build high-quality digital experiences."
https://material.io/
In my experience basing the UI on Material allows you to quickly come up with solutions without needing to reinvent the wheel each time you need a button, etc. It avoids discussions in the team like "I like that better, I like the other one better". It's like a lot of decissions get delegated to a system which is made by UI/UX experts, studied, tested, proven, et.c.
I came up with this after seeing this part of the server:
Knowing about Material Design I would say for example that the Material Solution for such an element is more intuitive:
Depending on what tech you are using there is Material for Angular, React etc.
Also the empty state of the servers list is a typical scenario which could be easily improved applying the Material Principles for Empty States
webpack-bundle-analyzer
to webpack configClient
1.2.3
Brave
Some fields such as owner_of or token_hash can be seen in the response of getTokenIdMetadata, but do not appear in the type definition.
const nft = await Moralis.Web3API.token.getTokenIdMetadata({
address: '0x32895105b3a65da694c63a3f5f7347d5ebf07f07',
token_id: '6363',
})
const owner = nft.owner_of // Typescript error: Property 'owner_of' does not exist on type ...
const tokenHash = nft.token_hash // Typescript error: Property 'token_hash' does not exist on type ...
The code still works, but Typescript complains about the types.
The code should not raise Typescript errors.
Server
Client
N/A
hi first at all congratulate you for this amazing lib.
i'm trying to use rarible plugin and this error occurs Cannot read properties of undefined (reading 'lazyMint')
With the current web3 version (1.6.0) used in moralis we are not getting success callback/ receipt with walletconnect
The web3 version in moralis should be updated to 1.6.1
const sellNftContract = new web3.eth.Contract(NFT_CONTRACT.abi, address)
try{
let res = await sellNftContract.methods.testmethod(userAddress, 'test').send({ from: userAddress,price:10})
.on('transactionHash', function(hash){
console.log(hash)
}).on('receipt', function(receipt){
console.log(transactionHash)
})
} catch (e) {
console.log(e);
}
If walletconnect is being used reciept wont be retrieved. How ever this has been fixed in web3 1.6.1 version
The type for BscTestChain
gives one option as " 0x61"
rather than "0x61"
.
See current code on main
:
Moralis-JS-SDK/types/index.d.ts
Line 397 in 1a39b11
I can't combine types as expected, eg Moralis.Chains.BSC_TESTNET
with Moralis.Chain
.
Everything should use "0x61"
not the incorrect string with a rogue space character.
Server
Client
1.5.9
n/a
User signs up with username/password account. Then at a later time tries to link the wallet but that operation fails.
<script src="https://unpkg.com/moralis/dist/moralis.js"></script>
<script>
const serverUrl = "<server>";
const appId = "<id>";
Moralis.start({ serverUrl, appId });
const user = new Moralis.User()
user.set("username", "t2-linked")
user.set("password", "t2-linked")
await user.signUp();
const web3 = await Moralis.enableWeb3()
console.log(`eth address: ${web3.provider.selectedAddress}`)
await Moralis.link(web3.provider.selectedAddress)
moralis.js:30643 Uncaught Error: this auth is already used
at handleError (moralis.js:26207:17)
I've also tried creating a new account in metamask and have the same issues.
No error, should link accounts
Chrome Browser
Server
0.0.349?
Client
https://unpkg.com/moralis/dist/moralis.js
Windows 11
Chrome
Install "moralis": "0.0.183" in Angular 11 application. Try to execute await Moralis.authenticate() and type error appears in Terminal.
Install "moralis": "0.0.183" in Angular 11 application. Try to execute await Moralis.authenticate() and NO type error appears in Terminal.
Server
FILL_THIS_OUT
Client
0.0.183
MAC OS MOnteray
Chrome
The core purpose of v2.0 of the SDK will be to modernize the current tech setup. Currently, it has been built by using a fork of the Parse SDK. In order to modernize the setup, we will be moving away from this fork and setup our own architecture. Below is a list of key features that we plan to implement:
Of course, the current functionality of the SDK remain the same or will be improved, including
Please, leave suggestions and requests in the comments
NPM Error: Refusing to install package with name "moralis" under a package also called "moralis"
npm i moralis
npm i moralis
npm ERR! code ENOSELF
npm ERR! Refusing to install package with name "moralis" under a package
npm ERR! also called "moralis". Did you name your project the same
npm ERR! as the dependency you're installing?
npm ERR!
npm ERR! For more information, see:
npm ERR! https://docs.npmjs.com/cli/install#limitations-of-npms-install-algorithm
Installation done.
NodeJS v.12.18.0 on MacOS Catalina 10.15.7
Server
Client
Moralis-JS-SDK/src/MoralisWeb3.js
Line 388 in 8df9484
Due to this condition the application throws an error whenever there is web3Sign trigger in the api response. It was changed with this commit: 7874c77
This issue seems related to Moralis SDK itself.
However, I'm using react-moralis: ^1.3.1.
My react code is inside a Vite App and written in typescript.
I'm opening an issue with the Vite developer, too, but please take a look guys.
You may recognize the potential source of the issue, or at least quickly exclude that it's from Moralis, I'll know where to tackle it best.
The cloud function call works in local development.
const safes = await Moralis.Cloud.run('MultiSigSafes', {
owner,
});
But in a production bundle it throws the following exception
Here is the stack trace
This is in Cloud.js line 98:
This is also Cloud.js line 171:
This is encode.js line 149:
This is encode.js line 65:
This is my vite.config.ts:
import { resolve } from 'path';
import reactPlugin from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
// import reactRefresh from '@vitejs/plugin-react-refresh';
import macrosPlugin from 'vite-plugin-babel-macros';
import { viteExternalsPlugin } from 'vite-plugin-externals';
import tsconfigPaths from 'vite-tsconfig-paths';
const isDev = process.env.ENVIRONMENT === 'DEVELOPMENT';
console.log('env.dev:', process.env.ENVIRONMENT, ' isDev:', isDev);
/**
* browserify for web3 components
*/
const externals = {
http: 'http-browserify',
https: 'http-browserify',
timers: 'timers-browserify',
electron: 'electron',
'electron-fetch': 'electron-fetch',
};
const nodeShims = {
util: 'util',
};
/**
* Externals:
* - node externals are required because web3 are terribly bundled and some of them use commonjs libraries. modern libs like ethers help with this.
* - electron: added due to ipfs-http-client. it has very poor esm compatibility and a ton of dependency bugs. see: https://github.com/ipfs/js-ipfs/issues/3452
*/
const externalPlugin = viteExternalsPlugin({
...externals,
...(isDev ? { ...nodeShims } : {}),
});
/**
* These libraries should not be egarly bundled by vite. They have strange dependencies and are not needed for the app.
*/
const excludeDeps = ['@apollo/client', `graphql`];
export default defineConfig({
plugins: [reactPlugin(), macrosPlugin(), tsconfigPaths(), externalPlugin],
build: {
sourcemap: true,
commonjsOptions: {
include: /node_modules/,
transformMixedEsModules: true,
},
rollupOptions: {
input: {
main: resolve(__dirname, 'index.html'),
},
},
},
esbuild: {
jsxFactory: 'jsx',
jsxInject: `import {jsx, css} from '@emotion/react'`,
},
define: {},
optimizeDeps: {
exclude: excludeDeps,
},
resolve: {
preserveSymlinks: true,
mainFields: ['module', 'main', 'browser'],
alias: {
'~~': resolve(__dirname, 'src'),
...externals,
...nodeShims,
process: 'process',
stream: 'stream-browserify',
},
},
server: {
watch: {
followSymlinks: true,
},
fs: {
// compatability for yarn workspaces
allow: ['../../'],
},
},
css: {
preprocessorOptions: {
less: {
javascriptEnabled: true,
},
},
},
});
Server
0.0.347
Client
Since v0.0.156 we get typescript errors while building.
Build using typescript.
node_modules/moralis/types/generated/web3Api.d.ts:1970:194 - error TS2339: Property '200' does not exist on type '{ 201: unknown; }'.
1970 syncNFTContract: (options: operations["syncNFTContract"]["parameters"]["query"] & operations["syncNFTContract"]["parameters"]["path"]) => Promise<operations["syncNFTContract"]["responses"]["200"]["content"]["application/json"]>;
The types for the response code are matching. So it should be 201 here.
^v0.0.157
Server
not needed
Client
^v0.0.157
mac
see outcome
enableWeb3() stuck async was never completed nor give error when user click back and after that enableWeb3() cant be used again and its always throw error Cannot execute Moralis.enableWeb3(), as Moralis Moralis.enableWeb3() already has been called
its also effect authenticate function if enableWeb3 stuck user cant authenticate unless they reload the page
Moralis enableWeb3() stuck authenticate function not working
Moralis try to connect and can authenticate
Server
FILL_THIS_OUT
Client
FILL_THIS_OUT
Android
Trust Wallet
I've come across a couple of seemingly related cases where the result type goes against what would be expected.
The first case is where a contract is returning multiple anonymous values. One would expect an array of indexed values, but instead an object with index names is returned.
The second case is when a contract is returning a structure with multiple values. One would expect to receive an object with properties having the corresponding names as defined in the ABI, but instead an array is returned. This carries forward to when an array of structs is returned, the SDK is producing an array of arrays, instead of an array of objects.
When a contract function is called that returns multiple values the SDK converts this into an object
with numbered parameters. This should be more correctly returned as an array
, as the parameters are anonymous and only defined by their order.
Below are some example constructions in solidity and the resultant ABI along with their returned outputs from within the Moralis SDK.
This is the call that was used to test
echo: async function(selector) {
const result = await contract.__call("echo", {_selected: selector});
console.log("echo() returned: ", typeof result, result);
},
__call: async function(name, params = undefined) {
const ctx = {
chain: contract.network,
address: contract.address[contract.network],
abi: contract.abi,
function_name: name
};
if(typeof params !== 'undefined') {
ctx.params = params;
}
result = await Moralis.Web3API.native.runContractFunction(ctx).then(function(result) {
return result;
}).catch(function(error) {
console.log('contract.' + name + '():' + error.error);
result = undefined;
return;
});
return result;
}
####Contract function:
This is the contract function that was created for testing purposes while debugging this and other issues
function echo(uint256 _selected) public view returns (address, uint256, bool) {
return (msg.sender, _selected, active);
}
####Resultant ABI:
This is the relevant ABI snippet passed in the abi
option
{
"inputs": [
{
"internalType": "uint256",
"name": "_selected",
"type": "uint256"
}
],
"name": "echo",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
},
{
"internalType": "uint256",
"name": "",
"type": "uint256"
},
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "view",
"type": "function"
}
####Received Result
Result Type: *Object*
{
0: "0x0000000000000000000000000000000000000000"
1: "1"
2: true
}
While this is technically okay, it would be more sensible if returned as an array, as access is via index, and not name. Couple this with the result from a when a Struct is returned, it's as if the relationships are reversed.
#####Expected/Preferred Result
Result Type: *Array* of Length 3
[
0: "0x0000000000000000000000000000000000000000"
1: "1"
2: true
]
This way we can test for the number of returned elements with result.length
, as well as iterate through with foreach
When a contract function is called that returns multiple values the SDK converts this into an object
with numbered parameters. This should be more correctly returned as an array
, as the parameters are anonymous and only defined by their order.
####Contract function:
struct MyStruct {
address add;
uint256 selected;
bool active;
}
function echo(uint256 _selected) public view returns (MyStruct memory) {
MyStruct memory _toSend = MyStruct(msg.sender, _selected, active);
return _toSend;
}
####Resultant ABI:
{
"inputs": [
{
"internalType": "uint256",
"name": "_selected",
"type": "uint256"
}
],
"name": "echo",
"outputs": [
{
"components": [
{
"internalType": "address",
"name": "add",
"type": "address"
},
{
"internalType": "uint256",
"name": "selected",
"type": "uint256"
},
{
"internalType": "bool",
"name": "active",
"type": "bool"
}
],
"internalType": "struct IntroStake.MyStruct",
"name": "",
"type": "tuple"
}
####Received Result
Result Type: *Array* of Length 3
[
0: "0x0000000000000000000000000000000000000000"
1: "1"
2: true
]
This is a larger problem than the first case, as the names of the elements of the results have effectively been stripped away, making any code using it prone to breaking if the Contract/ABI was updated re-ordering the parameters.
#####Expected/Preferred Result
Result Type: *Object*
{
"add": "0x0000000000000000000000000000000000000000"
"selected": "1"
"active": true
}
This would be the correct and expected result, and we can access the parameters based on their proper names as opposed to relying on their order within the struct. This is more sensible as an object with named parameters, and would be immune to problems associated with re-ordering.
This last case is compounded when an array of struct is returned. In that case an array of arrays is returned, having lost all contextual information.
Hosted webpage. Following scripts are loaded on the page
<!-- jQuery js -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<!-- web3 js -->
<script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
<!-- WalletConnect js -->
<script type="text/javascript"
src="https://unpkg.com/@walletconnect/[email protected]/dist/umd/index.min.js"></script>
<!-- moralis js -->
<script src="https://unpkg.com/moralis/dist/moralis.js"></script>
Server
Client
The JS-SDK is switching to using ethers.js instead of web3.js.
This is a change that will affect current builds, and that's why we make it only accessible in beta releases for now.
The main changes are
Install the sdk via
npm install moralis@next
Or install moralis by specifying a beta release. (see all releases here)
For the CDN script version, you can use:
https://unpkg.com/[email protected].<VERSION>/dist/moralis.js
And replace <VERSION>
the beta release version to the latest release (see all releases here)
Note: if you use react-moralis, then make sure to also install the latest beta release of react-moralis
See: MoralisWeb3/react-moralis#144
Note: if you want to switch back to a non-beta build, then install a moralis via
npm install moralis@latest
(or specify a release) or use a non-beta CDN script.
the Moralis SDK will use Ethers.js instead of Web3.js as internal library. This means:
enableWeb3()
or authenticate()
then Moralis.web3
will be an instance of Ethers.js instead of Web3.js.If you want to use a Web3.js
instance when calling Moralis.authenticate()
or Moralis.enableWeb3()
, then you need to specify the library constructor when you call Moralis.start
.:
Example where web3 is an instance of Ethers.js
await Moralis.start({
serverUrl: "YOUR_SERVER_URL",
appId: "YOUR_APP_ID",
});
// Get the initialized web3 instance from Ethers.js
await Moralis.enableWeb3();
const web3 = Moralis.web3;
Example where web3 is an instance of Web3.js
import Web3 from "web3";
await Moralis.start({
serverUrl: "YOUR_SERVER_URL",
appId: "YOUR_APP_ID",
web3Library: Web3,
});
// Get the initialized web3 instance from Web3.js
await Moralis.enableWeb3();
const web3 = Moralis.web3;
PromiEvent
, where you could subscribe to events, for callbacks. The responses from Ethers.js do not have this functionality. Instead, you get more information in the receipt, and can wait for the result (after confirmation) via response.wait()
(see docs).This has effect on:
Moralis.transfer()
Moralis.executeFunction()
Previously, it was possible to overwrite the enableWeb3()
function. This allowed for custom implementation to connect wallets that are not supported by Moralis out-of-the-box.
This approach is not possible anymore, to allow for better scaling and more consistent behavior.
Instead, now you can implement your own connector
, which extends the AbstractConnector class.
This class should implement
activate()
function that resolves to an object with:
this.subscribeToEvents(provider)
in the activate
function.type
field to indicate a name for the connectordeactivate
function that extends the default deactivate function. Implement this when you need to cleanup data/subscriptions upon ending/switching the connection.Then you can include this CustomConnector
in the authenticate/enableWeb3 call as option:
Moralis.authenticate({ connector: CustomConnector })
See for example implementations:
provider: "walletconnect"
.Please provide any feedback in our forum:
https://forum.moralis.io/t/moralis-js-sdk-v1-0-0-beta-ethers-js-support/7182
and the minified production version is at ...
Cannot find "/dist/moralis.min.js" in [email protected]
According to the docs there is a wait
method in response to Moralis.executeFunction
and it indeed present in runtime, all good.
However TypeScript complains this method does not exist even if response type is asserted to as Moralis.ExecuteFunctionSendResult
Digging a bit into Moralis typings I found that
type EthersTransaction = import('ethers').Transaction;
which looks wrong to me. I think it should be changed to
type EthersTransaction = import('ethers').providers.TransactionResponse;
which type is correct. btw, even Moralis docs insists that "You will get back a transaction response from Ethers.js, ..."
declare const tx: Moralis.ExecuteFunctionSendResult;
tx.wait(); // Property 'wait' does not exist on type 'Transaction'.
Unable to see autocompletion work for moralis/node
.
npm init && npm install moralis
tsconfig.json
with contents:{
"compilerOptions": {
"target": "es2020",
"module": "commonjs",
"lib": [
"es5",
"es6",
"dom"
],
"removeComments": true,
"rootDir": "./src",
"outDir": "./dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
global.d.ts
with the following contents:declare const { Moralis }: typeof import('moralis/node');
.ts
extension and try to trigger autocomplete by typing Moralis.
(Assumption) may also be reproducible with JS.
No autocompletion works unless the import is for 'moralis'
.
Autocomplete works and I live a better day!
Server
0.0.326
Client
0.0.183
Windows 11 Home 21H2 (build 22000.376)
Brave 1.34.80 Chromium: 97.0.4692.71
None.
When I use the typescript version of the Moralis SDK, I find that the type definition of Moralis.Units.Token
is
class Units {
static ETH: (value: number | string) => string;
static Token: (value: number | string, decimals: number) => string;
static FromWei: (value: number | string, decimals: number) => number;
}
Whereas it should be
class Units {
// ...
static Token: (value: number | string, decimals: number) => BigNumber;
// ...
}
npm install moralis
Moralis.Units.Token()
.The IDE thinks it's a string.
The IDE should tell me it's a BigNumber
.
Server
0.0.326
(irrelevant)Client
0.0.183
Windows 11 Home 21H2 (build 22000.434)
Brave 1.34.80 Chromium: 97.0.4692.71 (Official Build) (64-bit)
None.
Hi, I want to use this package in my Cocos creator game. We use javascript in Cocos creator too.
As the document said the Prerequisites:
So my question is, if I export my game to Android (APK file): can moralis connect to Metamask app in my phone. And perform other action via deep link?
I'll be using nftOwners method as an example for this feature request. The response content in nftOwnerCollection does not include the cursor property in the web3Api.d.ts file which is needed to fetch the next page. So if I try to destruct the response, TypeScript will throw a type error on cursor since it isn't part of the response type. However, if you log the response, cursor exists.
const { result, total, cursor } = await Moralis.Web3API.token.getNFTOwners(options);
The web3Api.d.ts should include cursor in the response type for all methods that use paging (i.e. getNFTs and getNFTOwners).
I can create an interface and cast the SDK response such as the following so that typescript knows that cursor exists.
interface MoralisApiResponse {
result: MoralisNftResponse[]
total: number
cursor: string
}
const { result, total, cursor } = (await Moralis.Web3API.token.getNFTOwners(options)) as MoralisApiResponse
When trying to update the signingMessage
property in the options
argument of theMoralis.Web3.authenticate()
function, I get the following typescript error:
TS2345: Argument of type '{ signingMessage: string; }' is not assignable to parameter of type 'AuthenticationOptions'.
Object literal may only specify known properties, and 'signingMessage' does not exist in type 'AuthenticationOptions'.
This is how my imports are implemented on the vue app in question (based off of the vue3-boilerplate project:
const user: UserModel = await $moralis.Web3.authenticate({
signingMessage: "sign test",
});
When I run the above snippet with the $moralis object typed as any
the code compiles and runs as expected.
import moralis and instantiate it in a typescript project. Attempt to authenticate with custom signing message.
I get a message that says 'signingMessage' does not exist in type 'AuthenticationOptions'.
The code compiles without errors and displays the custom message during authentication.
Moralis v0.0.140
Client
v0.0.140
macOS catalina 10.15.7
brave
morallis
on a typecript vue repo,"moralis": "0.0.90",
Error in /node_modules/moralis/types/generated/web3Api.d.ts(1714,56): TS2339: Property 'parameters' does not exist on type '{ responses: { 200: { content: { "application/json": { path: string; }[]; }; }; }; requestBody: { content: { "application/json": { path: string; content: string; }[]; }; }; }'.
import Moralis from 'moralis'
Moralis.initialize("API key");
Moralis.serverURL = "server url";
const user = await Moralis.Web3.authenticate({provider:"walletconnect", chainId:137 })
I added that in my typescript config :
"exclude": [
"node_modules/*"
]
Morallis
method well im getting that errorServer
FILL_THIS_OUT
Client
FILL_THIS_OUT
FILL_THIS_OUT
FILL_THIS_OUT
For me it was strange that the add new server window remembers its state, if you close it and the select add new server again you get the same state as before leaving that window.
The Select All Chains UI element is shown despite the chains are not listed yet, also pressing this ui element leads to the chains being shown but not selection occurs, this is misleading:
I would recommend to making the Select All Chains element something like a toggle so you can unselect all again pressing on the same element.
The Select Network section is not prefilled at first, once you type the name of the server it gets prefilled, it should be already prefilled before I suppose?
The import of Moralis in a NodeJS Typescript project does not work as expected.
There seems to be a object / types error.
In the following scenarios:
A: The object is there and does call the Moralis functions, but there is no Types assistance in the code.
B: I have types assistance when I write the code but when I compile the object is undefined.
C: A dirty hack that seems to work for now, but not sure if it's the right thing
A:
// eslint-disable-next-line @typescript-eslint/no-var-requires
const Moralis = require('moralis/node');
console.log(Moralis);
B:
import Moralis from 'moralis/node';
console.log(Moralis);
C:
import * as Moralis_ from 'moralis/node';
import { Moralis as MoralisTypesHack } from 'moralis';
const Moralis: MoralisTypesHack = Moralis_ as any;
A:
logs the the Moralis object but does not assist in the code
B:
logs undefined
but provides assistance when writing code
C:
logs Moralis object and also assists with the code
I would expect import Moralis from 'moralis/node';
or import {Moralis} from 'moralis/node';
to work out of the box.
An NX workspace with a bunch of apps including the nodeJS one I'm playing with
"@angular/animations": "13.1.1",
"@angular/common": "13.1.1",
"@angular/compiler": "13.1.1",
"@angular/core": "13.1.1",
"@angular/forms": "13.1.1",
"@angular/platform-browser": "13.1.1",
"@angular/platform-browser-dynamic": "13.1.1",
"@angular/router": "13.1.1",
"@capacitor/core": "^3.3.4",
"@feathers-plus/cache": "^1.4.0",
"@feathersjs/authentication": "^4.5.12",
"@feathersjs/authentication-client": "^4.5.13",
"@feathersjs/authentication-local": "^4.5.12",
"@feathersjs/authentication-oauth": "^4.5.12",
"@feathersjs/configuration": "^4.5.12",
"@feathersjs/errors": "^4.5.12",
"@feathersjs/express": "^4.5.12",
"@feathersjs/feathers": "^4.5.12",
"@feathersjs/socketio": "^4.5.13",
"@feathersjs/socketio-client": "^4.5.13",
"@feathersjs/transport-commons": "^4.5.12",
"@ionic/angular": "^5.8.3",
"@nrwl/angular": "13.4.3",
"@pm2/io": "^5.0.0",
"bignumber.js": "^9.0.2",
"bson": "^4.6.1",
"compression": "^1.7.4",
"cors": "^2.8.5",
"echarts": "^5.2.2",
"ethers": "^5.5.3",
"feathers-hooks-common": "^5.0.6",
"feathers-memory": "^4.1.0",
"feathers-mongodb": "^6.4.1",
"feathers-mongoose": "^8.5.1",
"feathers-profiler": "^0.1.5",
"feathers-reactive": "^0.8.2",
"feathers-shallow-populate": "^2.5.1",
"helmet": "^4.6.0",
"immer": "^9.0.7",
"lodash": "^4.17.21",
"luxon": "^2.3.0",
"matomo-tracker": "^2.2.4",
"mongodb": "^3.7.3",
"mongodb-core": "^3.2.7",
"mongoose": "^6.1.6",
"moralis": "^1.2.4",
"nedb": "^1.8.0",
"ngx-echarts": "^8.0.1",
"node-schedule": "^2.1.0",
"path": "^0.12.7",
"puppeteer": "^11.0.0",
"rss-parser": "^3.12.0",
"rxjs": "~6.6.0",
"serialize-error": "^8.1.0",
"tslib": "^2.0.0",
"winston": "^3.4.0",
"winston-daily-rotate-file": "^4.5.5",
"zone.js": "0.11.4"
Server
0.0.340
Client
^1.2.4
Linux
Not applicable
Properties are deleted from the options object passed by the client in the Web3API
Pass required options to a call to the Web3API
call such as:
const options = { address: '0x1a92f7381b9f03921564a437210bb9396471050c', chain: '0x1' };
const metaData = await Moralis.Web3API.token.getNFTMetadata(options);
After the call, the address (and other required properties) are deleted from the options object passed by the client.
// options is now { chain: '0x1' }
I expect the options object not to be modified so it can be passed in subsequent calls.
const options = { address: '0x1a92f7381b9f03921564a437210bb9396471050c', chain: '0x1' };
const metaData = await Moralis.Web3API.token.getNFTMetadata(options);
/**
* options should still have an address property so the next line
* won't throw an error due to the address not being provided
*/
const tokenIds = await Moralis.Web3API.token.getAllTokenIds(options);
Server
0.0.345
Client
1.3.2
MacOS Monterey
Chrome
When using the Moralis.transfer(options) command in NodeJS SDK it appears to map the option parameters incorrectly.
Here is an example endpoint in the latest stable version of NodeJS and Latest version of Moralis (1.5.9)
app.post('/transfer-test', async(req, res) => {
const Moralis = require('moralis/node');
console.log(Moralis.CoreManager.get("VERSION"))
await Moralis.start({ serverUrl, appId, masterKey, moralisSecret: process.env.moralis_secret });
await Moralis.enableWeb3({privateKey: process.env.metamask_private_key});
const options = {
type: "erc1155",
receiver: "receiverWalletAddress",
contractAddress: process.env.contract_address,
tokenId: 1,
amount: 1,
};
let transaction = await Moralis.transfer(options);
console.log(transaction, 'transaction details');
const receipt = await transaction.wait();
console.log(receipt, 'transaction finished');
})
If you look at the log output for transaction
and receipt
you'll notice that the to
field in both of them is the contractAddress
instead of the receiver
.
You'll also notice in the receipt
log that the contractAddress
comes through as null.
The transaction get's a transaction hash and appears to go through, but never actually goes through.
Expected the to
field to be mapped to the reciever
field and that the transaction would finish.
NodeJS 16.14.2
Moralis 1.5.9
Windows 10
Rinkeby Test Network
Server
0.0.359
Client
Windows 10
Terminal CMDER
See code to reproduce above.
I currently reference the Moralis type definitions like so:
/// <reference types="moralis" />
in a global declaration file (*.d.ts
).
This only seems to be possible if I reference v0.0.35 or earlier of the Moralis SDK.
I have noted that the way in which the Moralis
namespace is exported was changed in v0.0.36. In v0.0.35, this was exported like so:
export = Moralis
but it is now exported using:
export default Moralis
export type Moralis = typeof Moralis
The reason why I wish to reference the Moralis SDK type definitions, without importing the Moralis SDK directly, is because I am currently referencing the Moralis SDK via a CDN, but still wish to benefit from type completions. This makes front-end projects, using Vite, somewhat easier to bundle (without battling against the need for numerous polyfills).
The uploadFolder function set body, but AxiosRequestConfig "body" parameter does not exist;
So get the exception "Missing files from body"
need update the code ,set body change to set data.
And the doc should be update, because of was wrong๏ผthe source code bodyParams type is "data".
Server
0.0.369
Client
1.5.9"
Window 10
Chrome
When running in a svelte kit vitejs environment, moralis depends on process.env which is undefined client side. This causes the instanciation of the library to not function properly when the svelte code is compiled and served to the client
npm init svelte@next my-app
cd my-app
npm install
npm install moralis --save
npm run dev
touch moralisProvider.js
add the following code to the file, pass your own server keys instead of the env vars. (They are properly defined in my server, this is not the issue)
import Moralis from 'moralis';
export const moralisProvider = async () => {
const serverUrl = import.meta.env.VITE_MORALIS_SERVER_URL;
const appId = import.meta.env.VITE_MORALIS_APP_ID;
if (typeof serverUrl !== 'string' || typeof appId !== 'string') {
throw new Error('Missing Moralis server url or app id');
}
await Moralis.start({ serverUrl, appId });
};
in src/routes/index.svelte
call the function.
if (typeof window !== 'undefined') {
moralisProvider()
}
svelte-kit is an isomorphic rendering engine for svelte that can render html on the server, ensure you are not in the server environment with the if condition otherwise this will fail and cause another unrelated issue that is not of concern to this one.
Real life example is in this PR https://github.com/gamblefi/gamble/pull/14/files#diff-e659bdba229a88ffb053961749788c7fea8180d342ca946ab36de7145aa865e6R75
The call to Moralis.Start runs into an inappropriate check for process.env instead of using optional chaining.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
client is instanciated regularly
svelte kit on latest environment and latest moralis npm version
Server
latest
Client
latest
util.js:109 Uncaught (in promise) ReferenceError: process is not defined
at ../../node_modules/util/util.js (util.js:109:1)
at __require2 (chunk-ENMAWK7U.js?v=d2085534:36:44)
at ../../node_modules/moralis/node_modules/web3-core-requestmanager/lib/index.js (index.js:20:25)
at __require2 (chunk-ENMAWK7U.js?v=d2085534:36:44)
at ../../node_modules/moralis/node_modules/web3-core/lib/index.js (index.js:22:24)
at __require2 (chunk-ENMAWK7U.js?v=d2085534:36:44)
at ../../node_modules/moralis/node_modules/web3/lib/index.js (index.js:29:12)
at __require2 (chunk-ENMAWK7U.js?v=d2085534:36:44)
at ../../node_modules/moralis/lib/browser/MoralisWeb3.js (MoralisWeb3.js:57:35)
at __require2 (chunk-ENMAWK7U.js?v=d2085534:36:44)
../../node_modules/util/util.js @ util.js:109
__require2 @ chunk-ENMAWK7U.js?v=d2085534:36
../../node_modules/moralis/node_modules/web3-core-requestmanager/lib/index.js @ index.js:20
__require2 @ chunk-ENMAWK7U.js?v=d2085534:36
../../node_modules/moralis/node_modules/web3-core/lib/index.js @ index.js:22
__require2 @ chunk-ENMAWK7U.js?v=d2085534:36
../../node_modules/moralis/node_modules/web3/lib/index.js @ index.js:29
__require2 @ chunk-ENMAWK7U.js?v=d2085534:36
../../node_modules/moralis/lib/browser/MoralisWeb3.js @ MoralisWeb3.js:57
__require2 @ chunk-ENMAWK7U.js?v=d2085534:36
../../node_modules/moralis/lib/browser/ParseUser.js @ ParseUser.js:51
__require2 @ chunk-ENMAWK7U.js?v=d2085534:36
../../node_modules/moralis/lib/browser/ParseACL.js @ ParseACL.js:25
__require2 @ chunk-ENMAWK7U.js?v=d2085534:36
../../node_modules/moralis/lib/browser/decode.js @ decode.js:19
__require2 @ chunk-ENMAWK7U.js?v=d2085534:36
../../node_modules/moralis/lib/browser/Parse.js @ Parse.js:31
__require2 @ chunk-ENMAWK7U.js?v=d2085534:36
../../node_modules/moralis/index.js @ index.js:1
__require2 @ chunk-ENMAWK7U.js?v=d2085534:36
(anonymous) @ dep:moralis:1
await in (anonymous) (async)
Unable to open Metamask or WalletConnect after Moralis.setEnableWeb3
. This is a problem because user might cancel connecting with custom provider and instead choose Matamask/WalletConnect to connect to the dApp instead. Based on the code src/MoralisWeb3.js
, seems like it will store the custom enable web3 function in this.customEnableWeb3
here:
static setEnableWeb3(fn) {
this.customEnableWeb3 = fn;
}
which then when trying to Moralis.authenticate
or Moralis.enableWeb3
, will first check whether there is this.customEnableWeb3
first in the if-else logic as the code showed below.
static async enableWeb3(options) {
let web3;
if (this.customEnableWeb3) {
web3 = await this.customEnableWeb3(options);
} else {
if (this.speedyNodeApiKey) {
options.speedyNodeApiKey = this.speedyNodeApiKey;
options.provider = 'custom';
}
const Web3Provider = MoralisWeb3.getWeb3Provider(options);
const web3Provider = new Web3Provider();
this.activeWeb3Provider = web3Provider;
web3 = await web3Provider.activate(options);
}
this.web3 = web3;
return web3;
}
Since this.customEnableWeb3
persisted, whenever the user try to run Moralis.authenticate
or Moralis.enableWeb3` it will instead call the custom wallet provider instead of Metamask/WalletConnect.
moralis
+ react-moralis
to create-react-app<App />
component with MoralisProvider
and add appId
and serverUrl
/**
* @description Handle Wallet authentication
*
* @param {AuthenticationType} type - Wallet type (Metamask, WalletConnect, etc.)
*/
const onAuthentication = async (type: AuthenticationType) => {
switch (type) {
case AuthenticationType.WALLETCONNECT:
authenticate({
provider: "walletconnect",
onSuccess: () => navigate("/"),
onError: () =>
enqueueSnackbar("Failed to connect with WalletConnect", {
variant: "error",
}),
});
break;
case AuthenticationType.COINBASE:
try {
// @ts-ignore
await Moralis.setEnableWeb3(async () => {
const walletLink = new WalletLink({
appName: "xxx",
appLogoUrl: "xxx",
darkMode: false,
});
const ethereum = walletLink.makeWeb3Provider(
`https://speedy-nodes-nyc.moralis.io/${process.env.REACT_APP_MORALIS_SPEEDY_NODES_KEY}/eth/mainnet`,
1
);
// Show Coinbase Wallet popup
await ethereum.enable();
const web3 = new Web3(ethereum);
return web3;
});
await authenticate({
onSuccess: () => navigate("/"),
onError: () =>
enqueueSnackbar("Failed to connect with Coinbase wallet", {
variant: "error",
}),
});
} catch (e) {
enqueueSnackbar("Failed to connect with Coinbase wallet", {
variant: "error",
});
}
break;
case AuthenticationType.METAMASK:
default:
authenticate({
onSuccess: () => navigate("/"),
onError: () =>
enqueueSnackbar("Failed to connect with Metamask", {
variant: "error",
}),
});
break;
}
};
onAuthentication
in the Connect Wallet
button onClick
propsHere is a sample from one of my dApp:
https://user-images.githubusercontent.com/48710170/147804678-4902646f-4010-4d6e-b6af-64bb6e3759b5.mp4
Can't open Metamask/WalletConnect anymore after setting custom enable web3 function and as a consequence will just call Custom Wallet Provider when trying to authenticate with Metamask/WalletConnect.
Able to connect with Metamask/WalletConnect after cancel connecting with Custom Wallet Provider, or in terms of code after calling Moralis.setEnableWeb3
.
Server
Client
None, no error just unexpected behavior.
For typescript, Moralis.User.me is missing from the definition and is thus not useable in typescript unless the object is converted to an any type.
Setup typescript and try to call Moralis.User.me, which results in the compile error "Property 'me' does not exist on type 'UserConstructor'"
method description for me
Add me to the type definition
Node JS Typescript
Server
0.0.176
saveIPFS()
function is not saving file correctly to IPFS and since this is an issue on production I would like to fix this issue as soon as possible. thanks in advance.
const res = await file.saveIPFS()
console.log(await res.ipfs(), await res.hash())
res.ipfs()
returns link to the image - i.e: https://ipfs.moralis.io:2053/ipfs/QmXs57mbGbhZiEGv3DqAJKwemi36C1TFrqyFzQd6C44B1L
instead of JSON as in this document result - https://ipfs.moralis.io:2053/ipfs/QmUfpsyqc4hwozotRo4woyi5fJqvfcej5GcFvKiWoY6xr6
const file = new Moralis.File(media[0].name, media[0])
const res = await file.saveIPFS()
Getting ipfs link just returns the image instead JSON.
Get JSON object from saveIPFS()
method.
Server
0.0.345
Client
1.3.1
MacOS Monterey
Chrome
Right now, the development world is migrating to an ethers/hardhat world. Having ethers supported would make it easier to jump into these projects with hardhat implementations.
TYPO in MoralisWeb3Api.js getTokenAdressTransfers should be getTokenAddressTransfers
I want to send requests to Moralis Web3Api from my nodejs application. For doing this, I use Moralis.Web3API
.
First, I call Moralis.Web3API.initialize
and then what I want to call from the API. It works but there is a type incompatibility for initialize
method of Web3Api
class.
import Moralis from 'moralis/node';
Moralis.Web3API.initialize({
serverUrl: 'https://ve...xm.usemoralis.com:2053/server',
apiKey: 'dU...dr',
});
Moralis.Web3API.account.getNFTTransfers({
chain: 'eth',
address: '0xeC1...Aa8',
order: 'desc',
}).then(console.log);
In the source code, the method expects an object with serverUrl
and apiKey
props.
https://github.com/MoralisWeb3/Moralis-JS-SDK/blob/main/src/MoralisWeb3Api.js#L13
But in the generated type, the method expects only a string that will be used as server URL.
https://github.com/MoralisWeb3/Moralis-JS-SDK/blob/main/types/generated/web3Api.d.ts#L1869
Moralis.Web3API.initialize('https://ve...xm.usemoralis.com:2053/server');
If I want to call the method as above as declared in the type file, naturally, I get this error:
/Users/me/my_project/node_modules/moralis/lib/node/MoralisWeb3Api.js:37
throw new Error('Web3Api.initialize failed: initialize with apiKey or serverUrl');
^
Error: Web3Api.initialize failed: initialize with apiKey or serverUrl
at Function.initialize (/Users/me/my_project/node_modules/moralis/lib/node/MoralisWeb3Api.js:37:13)
at Object.<anonymous> (/Users/me/my_project/my_file.js:3:17)
Actually, I haven't seen anything about initializing Moralis and sending API calls through the SDK with nodejs in documentations. So I tried to use SDK in this way. Am I using SDK in the wrong way? So what should I do? How can I use the SDK in nodejs properly?
Thank you all!
Assuming this
get moralis(): Moralis {
if (this._moralis != null) {
return this._moralis;
}
this._moralis = moralis;
this._moralis.initialize(processEnvironmentVariables.MORALIS_APPLICATION_ID, null, processEnvironmentVariables.MORALIS_MASTER_KEY); // javaScriptKey is null because moralis server
this._moralis.serverURL = processEnvironmentVariables.MORALIS_SERVER_URL;
logger.debug("Moralis has been set and initialized");
return this._moralis;
}
and this
const page_size = 500;
let page = 0;
var result = await this.context.moralis.Web3API.token.getNFTOwners({
chain: "bsc",
address: this.market.nftAddress,
format: "hex",
order: "owner_of.ASC",
limit: page_size,
offset: page * page_size
});
I get an exception:
TypeError: Cannot read property 'length' of undefined
at Object.request (C:\Users\<repo>\node_modules\moralis\lib\node\RESTController.js:311:17)
at Object.run (C:\Users\<repo>\node_modules\moralis\lib\node\Cloud.js:167:36)
at run (C:\Users\<repo>\node_modules\moralis\lib\node\Cloud.js:93:52)
at Object.wrappers.<computed>.<computed> [as getNFTOwners] (C:\Users\<repo>\node_modules\moralis\lib\node\MoralisWeb3Api.js:169:29)
at <user-code>
What am I doing wrong?
I use it on vue.
Example:
import Moralis from 'moralis/dist/moralis.min.js';
if you use api: Moralis.authenticate()
errmsg is : Uncaught (in promise) TypeError: t2 is not a constructor
So.I tryit
import Moralis from 'moralis/dist/moralis.js'
use api:Moralis.authenticate()
errmsg is : Uncaught (in promise) TypeError: MWeb3 is not a constructor
I don't know why.But I want to get help with feedback.
Thanks.
user = await Moralis.authenticate({"provider: "walletconnect"})
is giving an error : Cannot enable WalletConnect: dependency "@walletconnect/web3-provider" is missing
SDK has been added
NB: 3 or 2 days ago walletconnect auth is working fine
When console.logging user.attributes.accounts
the outputted accounts are not mixed case in sync with EIP 55
This causes issues when checking to see if accounts are the same.
// moralis setup
console.log(user.attributes.accounts)
Then compare that with the mixed cased address of another account.
0x874437b5a42aa6e6419ec2447c9e36c278c46532
(old console.log)
0x874437B5a42aA6E6419eC2447C9e36c278c46532
(new console.log)
moralis version 0.0.92
react-moralis version 0.2.6
0.0.279
Client
0.0.92
MacOS 11.6
brave
static async unlink(account) {
const accountsLower = account.toLowerCase();
const ErdAddress = ParseObject.extend('_EthAddress');
I suppose _EthAddress is wrong here?
Server
FILL_THIS_OUT
Client
FILL_THIS_OUT
FILL_THIS_OUT
FILL_THIS_OUT
It seems unexpected that properties are deleted from the options object passed by the client.
For example:
const options = { address: '0x1a92f7381b9f03921564a437210bb9396471050c', chain: '0x1' };
const metaData = await Moralis.Web3API.token.getNFTMetadata(options);
// options is now { chain: '0x1' }
This makes it difficult to use the same options object for calls to additional endpoints as the required properties are no longer defined, resulting in the error Error: required param address not provided
.
Expected functionality:
const options = { address: '0x1a92f7381b9f03921564a437210bb9396471050c', chain: '0x1' };
const metaData = await Moralis.Web3API.token.getNFTMetadata(options);
/**
* options should still have an address property so the next line
* won't throw an error due to the address not being provided
*/
const tokenIds = await Moralis.Web3API.token.getAllTokenIds(options);
Relevant Function:
Moralis-JS-SDK/src/MoralisWeb3Api.js
Line 41 in f27230d
MoralisSolanaApi
It looks like that the API Endpoint Moralis.Web3API.storage.uploadFolder(options)
is broken, or the documentation is outdated.
The parameter options
doesn't exists anymore (i use typescript). It was removed here: 8522e78
Can't use storage endpoint because i cant set the parameter
Can set the parameter to upload my files
Client
"moralis": "^1.5.9"
Windows 11
Chrome Version 100.0.4896.60 (Official Build) (64-bit)
createBuyOrder is not working so I tried to look into node_modules, and I get to see that in file MoralisWeb3.js at line 1063
if (!(!triggersArray[i].signer || triggersArray[i].signer)) { _context13.next = 22; break; }
That is a falsey statement and it will never go inside the if block
after fixing that I get new error -
_reponse.wait() is not a function in MoralisWeb3.js at line -1082
` case 24:
_response = _context13.sent;
if (!((_triggersArray$i9 = triggersArray[i]) !== null && _triggersArray$i9 !== void 0 && _triggersArray$i9.shouldAwait)) {
_context13.next = 29;
break;
}
_context13.next = 28;
return _response.wait();`
Please help me with this
Server
FILL_THIS_OUT
Client
FILL_THIS_OUT
FILL_THIS_OUT
FILL_THIS_OUT
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.