Giter Site home page Giter Site logo

moralisweb3 / moralis-js-sdk Goto Github PK

View Code? Open in Web Editor NEW
363.0 363.0 256.0 2.13 GB

Moralis Official Javascript SDK

Home Page: https://docs.moralis.io

License: Other

JavaScript 1.50% TypeScript 98.35% Handlebars 0.15% Shell 0.01%
avalanche binance blockchain contracts crypto dapps eth ethereum evm fantom moralis nft smart-contracts solana web3 web3js

moralis-js-sdk's People

Contributors

3scava1i3r avatar alexjorgef avatar andrew-huang avatar ayorcodes avatar b4rtaz avatar blockframeio avatar capplequoppe avatar dani69654 avatar dependabot[bot] avatar dpradell-dev avatar ernow avatar federicoamura avatar gerardo15 avatar github-actions[bot] avatar golden-c avatar ivan-liljeqvist avatar kayconfig avatar meseta avatar microhoffman avatar mobilekosmos avatar omahs avatar ome-ananenu avatar rayyan224 avatar rphansen91 avatar semantic-release-bot avatar sogunshola avatar thomasansems avatar vincenthoong avatar y0moo avatar yosephks avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

moralis-js-sdk's Issues

event sync broken for events with indexed address[] argument

Events with arguments of type indexed address[] cannot be properly synced. The table is created but never populated.

Issue Description

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

Steps + code to reproduce

Screenshot 2022-03-01 at 21 27 57

Environment

  • Moralis server version: 0.0.347

Can't create sell order

New Bug Report

Checklist

Issue Description

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!".

Steps + code to reproduce

        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");
};

Actual Outcome

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!".

image

image

Expected Outcome

"Create Sell Order Successful" in the console without errors.

Environment

Server

  • Moralis server version: 0.0.369

Client

  • Moralis SDK version: 0.0.104
  • Operating system: MacOS Monterey
  • Browser: Chrome version 100.0.4896.127

Logs

[Recommendation] Base Server UI on Material Design

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:
image

Knowing about Material Design I would say for example that the Material Solution for such an element is more intuitive:
image

image

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

Bundle size since version 1 is quite massive

New Bug Report

Checklist

Issue Description

4A5561B5-5A35-4AC0-BC87-69BE98DBF30D

Steps + code to reproduce

  • Create a basic webpack setup
  • import Moralis to the application
  • Add webpack-bundle-analyzer to webpack config
  • observe bundle size is very large

Actual Outcome

  • Bundle size > 1.5mbs

Expected Outcome

  • Bundle size <= 100kb

Environment

  • esnext

Client

  • Moralis SDK version: 1.2.3
  • Operating system: `OSX
  • Browser: Brave

Logs

Typescript: some fields are missing in the return type of getTokenIdMetadata

New Bug Report

Checklist

Issue Description

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.

Steps + code to reproduce

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 ...

Actual Outcome

The code still works, but Typescript complains about the types.

Expected Outcome

The code should not raise Typescript errors.

Environment

Server

  • Moralis server version: 0.0.374

Client

  • Moralis SDK version: 1.6.0
  • Operating system: Windows
  • Browser: N/A, ran in Node.js 16.15.0

Logs

N/A

New web3 version 1.6.1 to be updated in Moralis

New Feature Request

Checklist

Current Limitation

With the current web3 version (1.6.0) used in moralis we are not getting success callback/ receipt with walletconnect

Feature / Enhancement Description

The web3 version in moralis should be updated to 1.6.1

Example Use Case

 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

Alternatives / Workarounds

3rd Party References

BscTestChain type has rogue space character

New Bug Report

Checklist

Issue Description

The type for BscTestChain gives one option as " 0x61" rather than "0x61".

Steps + code to reproduce

See current code on main:

type BscTestChain = 'bsc testnet' | 'binance testnet' | 'binance smart chain testnet' | ' 0x61';

Actual Outcome

I can't combine types as expected, eg Moralis.Chains.BSC_TESTNET with Moralis.Chain.

Expected Outcome

Everything should use "0x61" not the incorrect string with a rogue space character.

Environment

Server

  • Moralis server version: n/a

Client

  • Moralis SDK version: 1.5.9
  • Operating system: n/a
  • Browser: n/a

Logs

n/a

Unable to link username/password account with wallet

New Bug Report

Checklist

Issue Description

User signs up with username/password account. Then at a later time tries to link the wallet but that operation fails.

Steps + code to reproduce

<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)

Actual Outcome

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.

Expected Outcome

No error, should link accounts

Environment

Chrome Browser

Server

  • Moralis server version: 0.0.349?

Client

  • Moralis SDK version: https://unpkg.com/moralis/dist/moralis.js
  • Operating system: Windows 11
  • Browser: Chrome

Logs

Property 'authenticate' does not exist on type 'typeof Moralis'

New Bug Report

Checklist

Issue Description

Steps + code to reproduce

Install "moralis": "0.0.183" in Angular 11 application. Try to execute await Moralis.authenticate() and type error appears in Terminal.

Actual Outcome

Expected Outcome

Install "moralis": "0.0.183" in Angular 11 application. Try to execute await Moralis.authenticate() and NO type error appears in Terminal.

Environment

Server

  • Moralis server version: FILL_THIS_OUT

Client

  • Moralis SDK version: 0.0.183
  • Operating system: MAC OS MOnteray
  • Browser: Chrome

Logs

Screenshot 2022-01-07 at 16 36 49

Roadmap for SDK v2.0 (Modernize SDK)

Roadmap for SDK v2.0 (Modernize SDK)

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:

  • Use modular setup by implementing a mono-repo and sub-packages for optional functionalities. This way a developer can use certain functionalities without having to deal with dependencies of other sub packages. An umbrella package will also be exposed that includes all subpackages.
  • Use rollup or webpack as bundling tool to allow for tree-shaking
  • Natively written in Typescript for more security about correct Typings
  • Better written tests and code-coverage
  • Better cross-chain compatibilities, and connections to chains (connect to multiple networks, eager connections to chains if possible)

Of course, the current functionality of the SDK remain the same or will be improved, including

  • builds for browser, react-native and nodejs
  • Interaction with the moralis-server, chains/web3, webAPI/solanaApi

Please, leave suggestions and requests in the comments

NPM Error: Refusing to install package with name "moralis" under a package also called "moralis"

New Bug Report

Checklist

Issue Description

NPM Error: Refusing to install package with name "moralis" under a package also called "moralis"

Steps + code to reproduce

npm i moralis

npm i moralis

Actual Outcome

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

Expected Outcome

Installation done.

Environment

NodeJS v.12.18.0 on MacOS Catalina 10.15.7

Server

  • Moralis server version: 0.0.345

Client

  • Moralis SDK version: v.1.3.2
  • Operating system: MacOS Catalina 10.15.7
  • Browser: Brave

Logs

2022-02-16T12_54_02_273Z-debug.log

production-bundled code in Vite app breaks when calling Moralis.Cloud.run

New Bug Report

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.

Issue Description

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

Screenshot 2022-02-25 at 18 29 47

Here is the stack trace

This is in Cloud.js line 98:

Screenshot 2022-02-25 at 18 41 29

This is also Cloud.js line 171:

Screenshot 2022-02-25 at 18 42 17

This is encode.js line 149:

Screenshot 2022-02-25 at 18 44 35

This is encode.js line 65:

Screenshot 2022-02-25 at 18 47 09

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

  • Moralis server version: 0.0.347

Client

  • Moralis SDK version: "react-moralis": "1.3.1", which in turn uses "moralis": "1.1.0"
  • Operating system: MacOs BigSur 11.2 (20D64)
  • Browser: Version 98.0.4758.80 (Official Build) (arm64)

Response types are not correct since v0.0.157

New Bug Report

Checklist

Issue Description

Since v0.0.156 we get typescript errors while building.

Steps + code to reproduce

Build using typescript.

Actual Outcome

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"]>;

Expected Outcome

The types for the response code are matching. So it should be 201 here.

Environment

^v0.0.157

Server
not needed

Client

  • Moralis SDK version: ^v0.0.157
  • Operating system: mac

Logs

see outcome

enableWeb3() stuck on trust wallet if user click back

New Bug Report

Checklist

Issue Description

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

Steps + code to reproduce

  1. Open Trust Wallet
  2. go to your dapp or https://moralis-trust-issue.surge.sh/
  3. click enable web3
  4. when popup occur click back
  5. click again enable web3

Actual Outcome

Moralis enableWeb3() stuck authenticate function not working

Expected Outcome

Moralis try to connect and can authenticate

Environment

Server

  • Moralis server version: FILL_THIS_OUT

Client

  • Moralis SDK version: FILL_THIS_OUT
  • Operating system: Android
  • Browser: Trust Wallet

Logs

Contract multi-value result and struct returns incorrect

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.

Contract Returning Multiple Values

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.

Example constructions

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

Contract Returning Stuct

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.

Example constructions

####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.

Checklist

Environment

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

  • Moralis server version: Not sure, Assuming 0.0.303 is the version number displayed on the dashboard

Client

  • Moralis SDK version: Loaded live from https://unpkg.com/moralis/dist/moralis.js Currently: "Moralis JavaScript SDK v0.0.176"
  • Operating system: MacOS v12.1
  • Browser: Chrome Version 96.0.4664.110 (Official Build) (arm64) and Metamask 10.8.0

JS-SDK v1 [Beta]

JS-SDK v1 Beta (Ethers.js support)

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

  • Ethers.js is used as internal web3-library
  • Support Web3.js for Moralis.web3 calls
  • Changed responses of on-chain functions
  • Custom authentication / enableWeb3 (previously overwriting enableWeb3)

How to use

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.

Breaking Changes

Ethers.js as internal web3-library

the Moralis SDK will use Ethers.js instead of Web3.js as internal library. This means:

  • When you call enableWeb3() or authenticate() then Moralis.web3 will be an instance of Ethers.js instead of Web3.js.
  • Smaller bundle size
  • The responses of on-chain functionalities (Moralis.transfer, Moralis.executeFunction and some plugins) are different

Support Web3.js for Moralis.web3 calls

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;

Changed responses

  • Responses for on-chain calls are different, as Ethers.js is used for these calls. The main difference is that Web3.js returned a 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).
  • Data might be different formatted. For example Ethers.js includes numbers as a BigNumber object in the response.

This has effect on:

  • Moralis.transfer()
  • Moralis.executeFunction()
  • Some plugins

Custom authentication / enableWeb3 (previously overwriting enableWeb3)

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

  • An activate() function that resolves to an object with:
    • provider: A valid EIP-1193 provider
    • chainId (optional): the chain that is being connected to (in hex)
    • account (optional): the account of the user that is being connected
  • Subscribes to the EIP-1193 events. This should be mostly done automatically by calling this.subscribeToEvents(provider) in the activate function.
  • the type field to indicate a name for the connector
  • (optionally) a deactivate 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:

Feedback

Please provide any feedback in our forum:
https://forum.moralis.io/t/moralis-js-sdk-v1-0-0-beta-ethers-js-support/7182

Types: Missing .wait() method in ExecuteFunctionSendResult

New Bug Report

Checklist

Issue Description

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, ..."

Steps + code to reproduce

declare const tx: Moralis.ExecuteFunctionSendResult;
tx.wait(); // Property 'wait' does not exist on type 'Transaction'.

Can't autocomplete SDK code when using moralis/node in VS Code

New Bug Report

Checklist

Issue Description

Unable to see autocompletion work for moralis/node.

Steps + code to reproduce

  1. Use VS Code + Powershell 7.2.1
  2. npm init && npm install moralis
  3. Create 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
    }
}
  1. Create global.d.ts with the following contents:
declare const { Moralis }: typeof import('moralis/node');
  1. Create a file with .ts extension and try to trigger autocomplete by typing Moralis.

(Assumption) may also be reproducible with JS.

Actual Outcome

No autocompletion works unless the import is for 'moralis'.

Expected Outcome

Autocomplete works and I live a better day!

Environment

Server

  • Moralis server version: 0.0.326

Client

  • Moralis SDK version: 0.0.183
  • Operating system: Windows 11 Home 21H2 (build 22000.376)
  • Browser: Brave 1.34.80 Chromium: 97.0.4692.71

Logs

None.

Type returned by Moralis.Units.Token should be BigNumber, not string

New Bug Report

Checklist

Issue Description

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;
    // ...
}

Steps + code to reproduce

  1. npm install moralis
  2. Create a typescript file with some bare code using Moralis.Units.Token().

Actual Outcome

The IDE thinks it's a string.

Expected Outcome

The IDE should tell me it's a BigNumber.

Environment

Server

  • Moralis server version: 0.0.326 (irrelevant)

Client

  • Moralis SDK version: 0.0.183
  • Operating system: Windows 11 Home 21H2 (build 22000.434)
  • Browser: Brave 1.34.80 Chromium: 97.0.4692.71 (Official Build) (64-bit)

Logs

None.

Cocos creator(Android, IOS) support

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:

  • You have used MetaMask in your browser. MetaMask is not only a wallet, it allows websites to interact with your wallet, and sign to verify that you are the owner of that wallet.

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?

TypeScript - Missing cursor property in response content

New Feature Request

Checklist

Current Limitation

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);

Feature / Enhancement Description

The web3Api.d.ts should include cursor in the response type for all methods that use paging (i.e. getNFTs and getNFTOwners).

Alternatives / Workarounds

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

Typescript Bindings for AuthenticationOptions type is missing the signingMessage option

New Bug Report

Checklist

Issue Description

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.

Steps + code to reproduce

import moralis and instantiate it in a typescript project. Attempt to authenticate with custom signing message.

Actual Outcome

I get a message that says 'signingMessage' does not exist in type 'AuthenticationOptions'.

Expected Outcome

The code compiles without errors and displays the custom message during authentication.

Environment

Moralis v0.0.140

Client

  • Moralis SDK version: v0.0.140
  • Operating system: macOS catalina 10.15.7
  • Browser: brave

Logs

Property 'parameters' does not exist on type '{ responses: { 200

New Bug Report

Checklist

  • Im using morallis on a typecript vue repo,
  • "moralis": "0.0.90",
    
  • I keep getting this error 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; }[]; }; }; }'.
  • My implementation
 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/*"
  ]
  • now the projects starts, however when using anything related Morallis method well im getting that error
  • It works using a vue 3 project without typescript
    Thanks

Issue Description

Steps + code to reproduce

Actual Outcome

Expected Outcome

Environment

Server

  • Moralis server version: FILL_THIS_OUT

Client

  • Moralis SDK version: FILL_THIS_OUT
  • Operating system: FILL_THIS_OUT
  • Browser: FILL_THIS_OUT

Logs

[SERVER - IMPROVEMENT] Add new server dialog

  1. 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.

  2. 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:
    image

  3. 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.

  4. 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?

NodeJS Typescript Moralis is undefined

New Bug Report

Checklist

Issue Description

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

Steps + code to reproduce

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;

Actual Outcome

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

Expected Outcome

I would expect import Moralis from 'moralis/node'; or import {Moralis} from 'moralis/node'; to work out of the box.

Environment

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

  • Moralis server version: 0.0.340

Client

  • Moralis SDK version: ^1.2.4
  • Operating system: Linux
  • Browser: Not applicable

Logs

Properties are deleted from options passed by client in MoralisWeb3Api and MoralisSolanaApi

New Bug Report

Checklist

Issue Description

Properties are deleted from the options object passed by the client in the Web3API

Steps + code to reproduce

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);

Actual Outcome

After the call, the address (and other required properties) are deleted from the options object passed by the client.

// options is now { chain: '0x1' }

Expected Outcome

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);

Environment

Server

  • Moralis server version: 0.0.345

Client

  • Moralis SDK version: 1.3.2
  • Operating system: MacOS Monterey
  • Browser: Chrome

Logs

Moralis Transfer in NodeJS SDK not mapping parameters correctly.

New Bug Report

Checklist

Issue Description

When using the Moralis.transfer(options) command in NodeJS SDK it appears to map the option parameters incorrectly.

Steps + code to reproduce

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');
  })

Actual Outcome

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 Outcome

Expected the to field to be mapped to the reciever field and that the transaction would finish.

Environment

NodeJS 16.14.2
Moralis 1.5.9
Windows 10
Rinkeby Test Network

Server

  • Moralis server version: 0.0.359

Client

  • Moralis SDK version: `1.5.9
  • Operating system: Windows 10
  • Browser: Terminal CMDER

Logs

See code to reproduce above.

Type Definitions | Unable to Reference from Global Declaration File

Problem Specification

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.

Technical Details

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

Additional Context

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).

Moralis.Web3API.storage.uploadFolder not set data in the axios

New Bug Report

Checklist

Issue Description

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".

image

image

Steps + code to reproduce

Actual Outcome

Expected Outcome

Environment

Server

  • Moralis server version: 0.0.369

Client

  • Moralis SDK version: 1.5.9"
  • Operating system: Window 10
  • Browser: Chrome

Logs

Moralis depends on the process object when imported

New Bug Report

Checklist

Issue Description

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

Steps + code to reproduce

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

Actual Outcome

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

Screen Shot 2021-12-19 at 8 01 21 PM

Expected Outcome

client is instanciated regularly

Environment

svelte kit on latest environment and latest moralis npm version

Server

  • Moralis server version: latest

Client

  • Moralis SDK version: latest
  • Operating system: mac osx m1
  • Browser: chromium

Logs

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)

[Bug] Custom Enable Web3 Persistence (Can't Open Metamask or WalletConnect after setEnableWeb3)

New Bug Report

Checklist

Issue Description

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.

Steps + code to reproduce

  1. Add moralis + react-moralis to create-react-app
  2. Wrap the <App /> component with MoralisProvider and add appId and serverUrl
  3. Add multiple options for logging in with Moralis Authentication, like this
/**
   * @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;
    }
  };
  1. add onAuthentication in the Connect Wallet button onClick props
  2. Try first click on Connect Metamask/Wallet connect, which will work fine. Then, click on Connect to Coinbase/Custom wallet provider, and once we cancel and come back to connect back to Metamask/WalletConnect. It just keeps prompting for authentication with the Coinbase/Custom Wallet.

Here is a sample from one of my dApp:
https://user-images.githubusercontent.com/48710170/147804678-4902646f-4010-4d6e-b6af-64bb6e3759b5.mp4

Actual Outcome

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.

Expected Outcome

Able to connect with Metamask/WalletConnect after cancel connecting with Custom Wallet Provider, or in terms of code after calling Moralis.setEnableWeb3.

Environment

Server

  • Moralis server version: 0.0.317

Client

  • Moralis SDK version: 0.0.176
  • Operating system: Pop!_OS 21.10 (Ubuntu Linux Distro)
  • Browser: Brave Browser

Logs

None, no error just unexpected behavior.

Moralis.User.me is missing from types definition

New Bug Report

Checklist

Issue Description

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.

Steps + code to reproduce

Setup typescript and try to call Moralis.User.me, which results in the compile error "Property 'me' does not exist on type 'UserConstructor'"

Actual Outcome

method description for me

Expected Outcome

Add me to the type definition

Environment

Node JS Typescript

Server

  • Moralis server version: 0.0.176

saveIPFS() function is not working as expected

New Bug Report

Checklist

Issue Description

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

Steps + code to reproduce

const file = new Moralis.File(media[0].name, media[0])
const res = await file.saveIPFS()

Actual Outcome

Getting ipfs link just returns the image instead JSON.

Expected Outcome

Get JSON object from saveIPFS() method.

Environment

Server

  • Moralis server version: 0.0.345

Client

  • Moralis SDK version: 1.3.1
  • Operating system: MacOS Monterey
  • Browser: Chrome

Logs

Add ethers support

New Feature Request

Checklist

Current Limitation

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.

Moralis.Web3API type incompatibility

Issue Description

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.

Code

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
CleanShot 2021-11-12 at 13 40 11@2x

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
CleanShot 2021-11-12 at 13 36 47@2x

Result

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!

TypeError: Cannot read property 'length' of undefined

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?

Moralis.authenticate() is error

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.

Cannot enable WalletConnect: dependency "@walletconnect/web3-provider" is missing

user = await Moralis.authenticate({"provider: "walletconnect"})

is giving an error : Cannot enable WalletConnect: dependency "@walletconnect/web3-provider" is missing

SDK has been added

  • <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
  • <script src="https://unpkg.com/moralis/dist/moralis.js"></script>
  • <script src="https://github.com/WalletConnect/walletconnect-monorepo/releases/download/1.6.2/web3-provider.min.js"></script>

NB: 3 or 2 days ago walletconnect auth is working fine

Account are not EIP-55'd

New Bug Report

Checklist

Issue Description

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.

Steps + code to reproduce

// moralis setup
console.log(user.attributes.accounts)

Then compare that with the mixed cased address of another account.

Actual Outcome

Expected Outcome

0x874437b5a42aa6e6419ec2447c9e36c278c46532 (old console.log)
0x874437B5a42aA6E6419eC2447C9e36c278c46532 (new console.log)

Environment

moralis version 0.0.92
react-moralis version 0.2.6

  • Moralis server version: 0.0.279

Client

  • Moralis SDK version: 0.0.92
  • Operating system: MacOS 11.6
  • Browser: brave

_EthAddress being used in Elrond unlink

New Bug Report

Checklist

Issue Description

static async unlink(account) {
const accountsLower = account.toLowerCase();
const ErdAddress = ParseObject.extend('_EthAddress');

I suppose _EthAddress is wrong here?

Steps + code to reproduce

Actual Outcome

Expected Outcome

Environment

Server

  • Moralis server version: FILL_THIS_OUT

Client

  • Moralis SDK version: FILL_THIS_OUT
  • Operating system: FILL_THIS_OUT
  • Browser: FILL_THIS_OUT

Logs

Properties are deleted from options passed by client

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:

static getParameterizedUrl(url, params) {

it looks like this is also an issue in MoralisSolanaApi

Moralis.Web3API.storage.uploadFolder missing parameter options.

New Bug Report

Checklist

Issue Description

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

Actual Outcome

Can't use storage endpoint because i cant set the parameter

Expected Outcome

Can set the parameter to upload my files

Environment

Client

  • Moralis SDK version: "moralis": "^1.5.9"
  • Operating system: Windows 11
  • Browser: Chrome Version 100.0.4896.60 (Official Build) (64-bit)

Moralis.Plugins.opensea.createBuyOrder({....}) have issue with trigger signer is missing or undefined

New Bug Report

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

Checklist

Issue Description

Steps + code to reproduce

Actual Outcome

Expected Outcome

Environment

Server

  • Moralis server version: FILL_THIS_OUT

Client

  • Moralis SDK version: FILL_THIS_OUT
  • Operating system: FILL_THIS_OUT
  • Browser: FILL_THIS_OUT

Logs

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.