Tuesday, March 28, 2023
No Result
View All Result
Blockchain Daily Report
Advertisement
  • HOME
  • BITCOIN
  • CRYPTO UPDATES
    • GENERAL
    • ALTCOINS
    • ETHEREUM
    • CRYPTO EXCHANGES
    • CRYPTO MINING
  • BLOCKCHAIN
  • NFT
  • DEFI
  • METAVERSE
  • WEB3
  • SCAM ALERT
  • REGULATIONS
  • ANALYSIS
Crypto Marketcap
  • HOME
  • BITCOIN
  • CRYPTO UPDATES
    • GENERAL
    • ALTCOINS
    • ETHEREUM
    • CRYPTO EXCHANGES
    • CRYPTO MINING
  • BLOCKCHAIN
  • NFT
  • DEFI
  • METAVERSE
  • WEB3
  • SCAM ALERT
  • REGULATIONS
  • ANALYSIS
Crypto Marketcap
Logo
No Result
View All Result
Home Web3

How to Call a Smart Contract Function from JavaScript

by Blockchain Daily Report
December 16, 2022
in Web3
Reading Time: 12 mins read
A A
0
How to Call a Smart Contract Function from JavaScript
Share on FacebookShare on Twitter


Utilizing the enterprise-grade EVM API from Moralis, builders can simply name a wise contract perform from JavaScript. Merely set up Moralis’ SDK and name the ”runContractFunction” endpoint! Moreover, by defining particular parameters within the code snippet beneath, together with the contract tackle, perform title, ABI, and so on., you’ll be able to run any EVM ”read-only” contract perform with just a few strains of code: 

const response = await Moralis.EvmApi.utils.runContractFunction({
tackle,
functionName,
abi,
});

In order for you extra info on how this works, verify the documentation web page to run a contract perform or comply with alongside on this tutorial as we apply this in follow! That mentioned, irrespective of which path you resolve to comply with, that you must have a Moralis account. So, create one totally free now and unlock the facility of blockchain!

Overview

Good contracts are on the core of blockchain growth and are important parts of the Web3 ecosystem. Within the case of Ethereum, sensible contracts encompass two components, one in every of which is wise contract capabilities. Such a perform is a chunk of code used a number of occasions to carry out given duties. Consequently, in Web3 growth, it’s extremely helpful for a developer to know tips on how to run Web3 contract strategies. If you wish to learn the way to take action, be a part of us on this tutorial as we present you tips on how to name a wise contract perform from JavaScript utilizing Moralis! 

Earlier than we present you tips on how to name a wise contract perform from JavaScript, the article will briefly cowl the intricacies of each contracts and capabilities. So, if you’re already accustomed to these ideas, be at liberty to skip straight into the central a part of the tutorial. 

To name sensible contract capabilities seamlessly, we will likely be utilizing Moralis’ Ethereum Web3 API. Nevertheless, that is solely one of many outstanding blockchain growth instruments provided by Moralis. As such, if you’re actually critical about turning into a blockchain developer, you must discover a few of Moralis’ different interfaces. An instance is the Streams API, enabling you to rapidly arrange Web3 webhooks to stream on-chain knowledge immediately into the backend of Web3 tasks! 

So, if you wish to entry these instruments and absolutely leverage the facility of blockchain know-how, join with Moralis now solely totally free! 

Exploring Contracts and Features – Tips on how to Name Good Contract Operate from JavaScript

Earlier than exploring tips on how to name a wise contract perform with JavaScript, the article will briefly dive into the intricacies of contracts and capabilities. If you’re already accustomed to these two ideas, be at liberty to skip straight into the ”Tips on how to Name Good Contract Operate from JavaScript” tutorial. In any other case, be a part of us within the following sections, the place we begin by answering the query, ”what are sensible contracts?”. 

What are Good Contracts? 

Good contracts – additionally usually known as ”Web3 contracts” – are on the spine of the Web3 ecosystem and are primarily codified agreements between two or extra events over the web. Consequently, sensible contracts have the identical basic functions as conventional contracts. Nevertheless, there’s a essential distinction between sensible contracts and conventional ones that’s fairly necessary to be aware of. The code on the blockchain regulates the ”phrases and circumstances” slightly than a third-party actor. 

developer constructing smart contract and calling it with JavaScript

To slender the scope barely, allow us to focus extra particularly on Ethereum sensible contracts, as that is the most well-liked community for blockchain growth. These sensible contracts are packages operating on the Ethereum blockchain. Moreover, they encompass two core parts: code and knowledge. The code is a set of capabilities, and the info is the contract’s state.

A standard metaphor for describing the performance of a wise contract is a digital merchandising machine. Like conventional merchandising machines, sensible contracts produce assured outputs based mostly on given inputs. Accordingly, you’ll be able to present contracts with cryptocurrency, and so they run code in return. 

However, that briefly covers sensible contracts. For a extra profound breakdown, try our article on Web3 contracts! Now, let’s get extra particular and discover one in every of their core parts: sensible contract capabilities! 

What are Good Contract Features?

As we briefly talked about within the preliminary part, capabilities are one in every of two core parts of Ethereum sensible contracts. So, what precisely are sensible contract capabilities? A wise contract perform is a chunk of reusable code that may be referred to as from exterior or inside a selected sensible contract that accomplishes a particular job. Creating capabilities offers a number of advantages, reminiscent of eliminating the necessity to write code a number of occasions and decreasing the possibility of errors occurring. 

two workers exchanging contract by calling a smart contract function from JavaScript code

Moreover, there are two forms of sensible contract capabilities:

Features that generate on-chain transactions.Features which are ”read-only” and, subsequently, don’t lead to blockchain transactions.

On this tutorial, we’ll give attention to the previous. Particularly, within the subsequent part, we’ll present you tips on how to use Moralis to name a ”read-only” sensible contract perform from JavaScript. If this sounds thrilling, keep caught in as we cowl the method from begin to end! 

Tips on how to Name Good Contract Operate from JavaScript 

The next tutorial sections illustrate how one can name a wise contract perform from JavaScript. To make this as accessible as attainable as you comply with our lead, we’ll make the most of Moralis’ EVM API and the ”runContractFunction” endpoint. By this endpoint, you’ll be able to name any ”read-only” sensible contract perform from JavaScript with only some strains of code! 

moralis written in grey letters

To exhibit how this works, we’ll present you tips on how to name the ”getPrice()” perform of the “Cool Cats” NFT contract. Calling this perform returns the minting worth of the tokens, which you should utilize as you see slot in your growth endeavors. Here’s a fast overview of the elements we cowl on this article: 

Set Up a NodeJS ProjectAdd the Code to the ”index.js” FileRun the Program

By masking the sections above, you’ll be taught not solely tips on how to name ”getPrice()” however any ”read-only” sensible contract perform. So, if this sounds thrilling, be a part of us on this tutorial as we kick issues off by displaying you tips on how to arrange a NodeJS venture! 

Nevertheless, maybe you like watching YouTube movies to teach your self. If that’s the case, you may as well try the Moralis YouTube clip beneath. On this video, you will discover a complete breakdown of your entire course of, together with further examples of different sensible contract perform calls: 

Set Up a NodeJS Venture 

On this preliminary part of the tutorial on tips on how to name a wise contract perform from JavaScript, we’ll present you tips on how to arrange a NodeJS venture. As such, to start with, if in case you have not already, make certain to put in the most recent model of NodeJS. You possibly can obtain and set up it utilizing the next hyperlink: “https://nodejs.org/en/”. 

From there, open your built-in growth surroundings (IDE) and create a brand new venture folder. We’re utilizing Visible Studio Code (VSC) all through the article. As such, if you happen to go for one other surroundings, word that there may sometimes be slight variations within the course of. However, after you have opened your IDE, go forward and launch a brand new terminal. If you’re utilizing VSC, click on on the ”Terminal” tab on the high after which hit ”New Terminal”: 

visual studio code terminal prompt

From there, you’ll be able to initialize a brand new NodeJS venture by operating the command beneath within the venture’s root folder: 

npm init -y

With the venture initialized, you additionally want to put in the required dependencies. To take action, run this command within the terminal:

npm i moralis dotenv

That covers the preliminary setup technique of the NodeJS venture. Nevertheless, from right here, you additionally want so as to add three new information ”.env”, ”abi.json”, and ”index.js”. As such, within the following sub-section, we’ll present you tips on how to create them and take a better have a look at what content material it’s essential to add to every.

Add ”.env”, abi.json”, and ”index.js” 

The primary file that you must create is ”.env”, which will likely be used to securely retailer your Web3 API key. As such, open the file and create a brand new ”MORALIS_KEY” surroundings variable. It ought to look one thing like this: 

MORALIS_KEY = “JnJnO…”

Nevertheless, as you might need concluded already, that you must substitute ”JnJnO…” along with your precise key. To get the important thing, that you must have an lively Moralis account. So both log in or join with Moralis totally free proper now. From there, log in to the admin panel, go to the ”Web3 APIs” tab, copy the important thing, and enter it into the ”.env” file: 

web3 api landing page showing key

Now that you’ve got added your Moralis API key, the following step is to create the ”abi.json” file. For this file, it would be best to add the ABI of the contract you have an interest in. To get the contract ABI, we’ll use the Etherscan blockchain explorer. Particularly, we’ll use the Cool Cats NFT contract to exhibit how this works. 

However, open Etherscan and navigate to the contract you have an interest in. In our case, it appears to be like one thing like this: 

etherscan landing page showing cool cats smart contract

From there, scroll down and click on on the ”Contract” tab: 

contract page for cool cats collection

You possibly can then scroll down even additional, and you must discover the contract ABI nearly on the backside: 

contract abi code outlined

Copy this code and enter it into the ”abi.json” file. It ought to now look one thing like this: 

abi json file with code structure to call smart contract function with JS code

Lastly, the final file that you must add is ”index.js”. This would be the file to which we add the logic used to name a wise contract perform from JavaScript. Consequently, this ”index.js” requires further consideration, which is why we dedicate the next part to breaking down the code! 

Add the Code to the ”index.js” File 

Now that you’ve got arrange the NodeJS venture and created the required information, it’s time to add the code used to name a wise contract perform from JavaScript. So, to start with, open ”index.js” and add the next code snippet on the high of the file: 

const Moralis = require(“moralis”).default;
require(“dotenv”).config();
const ABI = require(“./abi.json”);

The above code imports Moralis, offers entry to the contents of the ”.env” file, and shops the contract ABI within the ”ABI” variable. From there, that you must initialize Moralis and move the Web3 API key you specified earlier as a parameter. To take action, add the next code beneath the ”ABI” variable: 

Moralis.begin({
apiKey: course of.env.MORALIS_KEY
})

Subsequent, with Moralis initialized, create a brand new asynchronous perform. This perform will use Moralis’ EVM API to name the ”runContractFunction” endpoint with just a few parameters. On this case, since we need to name the ”getPrice()” perform, you solely want so as to add the ”tackle”, ”functionName”, and ”abi” as parameters: 

.then(async()=>{

const response = await Moralis.EvmApi.utils.runContractFunction({
tackle:”0x1A92f7381B9F03921564a437210bB9396471050C”,
functionName:”getPrice”,
abi: ABI
})

Lastly, to high issues off, we console-log the response by including the next code on the backside of the ”index.js” file: 

console.log(response.uncooked)

All in all, your file ought to now look one thing like this: 

const Moralis = require(“moralis”).default;
require(“dotenv”).config();
const ABI = require(“./abi.json”);

Moralis.begin({
apiKey: course of.env.MORALIS_KEY
}).then(async()=>{

const response = await Moralis.EvmApi.utils.runContractFunction({
tackle:”0x1A92f7381B9F03921564a437210bB9396471050C”,
functionName:”getPrice”,
abi: ABI
})

console.log(response.uncooked)
})

So, by operating the ”index.js” file, this system ought to return the mint worth of the Cool Cats NFTs. However, allow us to briefly present you tips on how to run this system and evaluate the ends in the following part! 

Run the Program 

Lastly, now that you’ve got added the code used to name a wise contract perform, all that is still is operating this system. To take action, open a brand new terminal and easily run the next command: 

node index.js

This executes the code, and you must obtain a response just like the one proven beneath: 

result page from using JavaScript and calling the smart contract function

The response is ”20000000000000000”, which is the quantity ”2” adopted by sixteen zeros. As such, that is the mint worth with out contemplating the decimals. The precise worth is 0.2 ETH. 

Congratulations! That’s it for this tutorial! If in case you have adopted alongside this far, you now know tips on how to name a wise contract perform from JavaScript. What’s extra, although we confirmed you tips on how to name the ”getPrice()” perform, specifically, you’ll be able to apply the identical basic ideas to name different ”read-only” capabilities of any EVM-based contract! 

If you wish to try what different sensible contract capabilities can be found, you’ll be able to intently look at the ”abi.json” file or browse Etherscan. For Etherscan, you’ll be able to click on on the ”Contract” tab after which hit ”Learn Contract” to seek out all capabilities accessible. As an example, here’s what it appears to be like like for the Cool Cats contract: 

contract and read only landing page

What’s extra, if you’d like additional info on tips on how to name a wise contract perform with JavaScript, try the EVM API documentation or the documentation web page to run a contract perform. 

Abstract – Tips on how to Name Good Contract Operate From JavaScript

On this article, we taught you tips on how to name a wise contract perform from JavaScript utilizing Moralis. Extra particularly, we used the ”runContractFunction” endpoint to name the ”getPrice()” perform of the Cool Cats contract. Consequently, if in case you have adopted alongside this far, you should utilize the identical basic ideas to name any sensible contract perform sooner or later! 

If you happen to discovered this tutorial informative, make certain to take a look at further Moralis-based content material right here on the Web3 weblog. As an example, discover one of the best Ethereum API in 2023 or be taught the variations between ethers.js vs Web3 streams! 

However, it doesn’t matter what blockchain endeavor you embark on sooner or later, join with Moralis now, as this Web3 supplier facilitates a extra seamless developer expertise for everybody! 



Source link

Tags: CallContractfunctionJavaScriptSmart
Share76Tweet47

Related Posts

MATIC Faucet – Free Polygon Testnet Faucet 2023

MATIC Faucet – Free Polygon Testnet Faucet 2023

by Blockchain Daily Report
March 27, 2023
0

On this article, we are going to cowl an entire step-by-step breakdown of tips on how to get Polygon testnet...

Hong Kong blockchain initiatives natural evolution for finance hub, says Signum Digital CEO

Hong Kong blockchain initiatives natural evolution for finance hub, says Signum Digital CEO

by Blockchain Daily Report
March 24, 2023
0

After the worldwide crypto failures and bankruptcies in 2022 and China’s recognized distaste for cryptocurrencies, Hong Kong regulators stunned with...

Hong Kong poised for ambitious changes

Hong Kong poised for ambitious changes

by Blockchain Daily Report
March 23, 2023
0

Welcome to Future Guidelines, March 23, 2023 – introduced by Joel Flynn.2023 is shaping as much as be a yr...

How DAOs can be remade to be more successful

How DAOs can be remade to be more successful

by Blockchain Daily Report
March 23, 2023
0

Centralized crypto finance took a beating over the past 12 months.However the folks and buyers who relied on centralized constructions...

How to Get a Wallet Balance on Aptos

How to Get a Wallet Balance on Aptos

by Blockchain Daily Report
March 23, 2023
0

Discover the best method to get a pockets steadiness on Aptos with the Web3 Information API from Moralis. With this...

Load More
  • Trending
  • Comments
  • Latest
Mine CLORE Coins Used by the CLORE.AI Distributed Computing Platform

Mine CLORE Coins Used by the CLORE.AI Distributed Computing Platform

January 23, 2023
WildRig Multi 0.36.4 beta Now With Faster NEXA Performance and Lower Fee

WildRig Multi 0.36.4 beta Now With Faster NEXA Performance and Lower Fee

January 23, 2023
It Is ‘Not a Currency’ and Has a ‘Fundamental Value of Zero’ – Bitcoin News

It Is ‘Not a Currency’ and Has a ‘Fundamental Value of Zero’ – Bitcoin News

March 28, 2023
President Nayib Bukele Touts El Salvador as the ‘New Land of the Free’ in Vintage Americana Poster Featuring Bitcoin as Legal Tender – Bitcoin News

President Nayib Bukele Touts El Salvador as the ‘New Land of the Free’ in Vintage Americana Poster Featuring Bitcoin as Legal Tender – Bitcoin News

March 28, 2023
Shiba Inu Burn Rate Falls 70% This Week

Shiba Inu Burn Rate Falls 70% This Week

March 28, 2023
Investors Flock to US Money Market Funds Amid Banking Crisis

Investors Flock to US Money Market Funds Amid Banking Crisis

March 28, 2023
Dan Dolev’s view on Coinbase stock after CFTC sued Binance

Dan Dolev’s view on Coinbase stock after CFTC sued Binance

March 28, 2023
Polygon Launches zkEVM Mainnet Beta,

Polygon Launches zkEVM Mainnet Beta,

March 28, 2023
Vaneck CEO Predicts Bull Cycle for Bitcoin and Gold — Expects Fed Tightening to End Soon – Markets and Prices Bitcoin News

Vaneck CEO Predicts Bull Cycle for Bitcoin and Gold — Expects Fed Tightening to End Soon – Markets and Prices Bitcoin News

March 28, 2023
Binance CEO Zhao Calls CFTC Suit an ‘Incomplete Recitation of Facts’

Binance CEO Zhao Calls CFTC Suit an ‘Incomplete Recitation of Facts’

March 28, 2023
Facebook Twitter Instagram Youtube RSS

Find the latest Bitcoin, Ethereum, blockchain, crypto, Business, Fintech News, interviews, and price analysis at Blockchain Daily Report.

CATEGORIES

  • Altcoin
  • Analysis
  • Bitcoin
  • Blockchain
  • Crypto Exchanges
  • Crypto Mining
  • Crypto Updates
  • DeFi
  • Ethereum
  • Metaverse
  • NFT
  • Regulations
  • Scam Alert
  • Uncategorized
  • Web3

SITE MAP

  • Disclaimer
  • Privacy Policy
  • DMCA
  • Cookie Privacy Policy
  • Terms and Conditions
  • Contact us

Copyright © 2022 Blockchain Daily Report.
Blockchain Daily Report is not responsible for the content of external sites.

No Result
View All Result
  • HOME
  • BITCOIN
  • CRYPTO UPDATES
    • GENERAL
    • ALTCOINS
    • ETHEREUM
    • CRYPTO EXCHANGES
    • CRYPTO MINING
  • BLOCKCHAIN
  • NFT
  • DEFI
  • METAVERSE
  • WEB3
  • SCAM ALERT
  • REGULATIONS
  • ANALYSIS

Copyright © 2022 Blockchain Daily Report.
Blockchain Daily Report is not responsible for the content of external sites.

  • bitcoinBitcoin(BTC)$26,983.00-3.49%
  • ethereumEthereum(ETH)$1,715.34-3.06%
  • USDEXUSDEX(USDEX)$1.07-0.53%
  • tetherTether(USDT)$1.00-0.10%
  • binancecoinBNB(BNB)$308.01-6.30%
  • usd-coinUSD Coin(USDC)$1.000.02%
  • rippleXRP(XRP)$0.4778114.47%
  • cardanoCardano(ADA)$0.348431-1.32%
  • dogecoinDogecoin(DOGE)$0.072504-2.08%
  • staked-etherLido Staked Ether(STETH)$1,700.49-3.77%