If you are interested in blockchain programming and want to leverage AWS Lambda for Web3, follow along in this tutorial as it demonstrates how to build and deploy a Web3 AWS Lambda app in three simple steps:
- Covering the Prerequisites
- Setting Up a New Project
- Developing the Lambda Application
By covering the steps above, you will learn how to create an AWS Lambda function by integrating Moralis’ NodeJS SDK with the service. By completing this Web3 AWS tutorial, you will be able to run Web3 JavaScript code with Lambda, which you can implement in all future blockchain projects!
If this sounds exciting and you want to get going immediately, you can jump into the tutorial by visiting the “AWS Web3 Tutorial” section below. What’s more, you can check out the Web3 documentation page for AWS Lambda and the complete GitHub repository for the application down below:
Complete Web3 AWS Lambda Documentation – https://github.com/MoralisWeb3/examples-aws-lambda-nodejs/tree/main/aws-node-project
Overview
Are you interested in AWS and want to leverage Lambda to create sophisticated Web3 projects? If so, join us in this AWS Lambda tutorial, teaching you how to develop and deploy a Web3-ready Lambda application with multiple functions. Specifically, you will learn how to create functions for fetching the native token/NFT balances and running the code with AWS Lambda!
What’s more, in combination with showing you how to create Lambda functions, this article also covers the intricacies of this service and what it means in a Web3 context. As such, we will explore how to get AWS Web3 ready by covering the best AWS Web3 Lambda solution – Moralis! However, if you want a more detailed breakdown, check out our article on AWS Lambda and what it is used for.
If you are already familiar with this service, you might want to check out additional content here at Moralis’ Web3 blog. For instance, check out our article answering the question, ”what is GameSparks?”.
Nevertheless, before moving forward, sign up with Moralis immediately since you must have an account to follow along! What’s more, with a Moralis account, you can access other tools – such as Moralis’ Web3 APIs – to fully leverage the power of blockchain technology!
AWS for Web3 – What is AWS, Lambda, and Web3?
To adequately grasp what AWS and Lambda entail in a Web3 context, this initial section breaks down these three components separately. As such, to begin with, we will kick things off by answering the following question: ”what is AWS?”.
AWS is an abbreviation for ”Amazon Web Services”, and it is the most extensive and adopted cloud platform worldwide. AWS offers more than 200 services, ranging from infrastructure technologies, such as database, storage, and compute solutions, to emerging technologies like artificial intelligence, machine learning, etc. By utilizing AWS, you can leverage the latest technologies to innovate and experiment at a higher pace, providing a significant competitive advantage, especially in a fast-moving industry like Web3.
Within Amazon’s comprehensive AWS ecosystem, you will find Lambda, a serverless, event-driven computing service. With AWS Lambda, developers can run code without having to worry about servers or clusters. All they need to do is write and upload code in the form of ”Lambda functions”, and the service takes care of the rest!
Lambda functions are the backbone of this service, and they trigger based on events, meaning Lambda only invokes them when necessary. Some prominent examples include HTTP requests, an object modification in Amazon S3, a table update in DynamoDB, etc. Moreover, since Lambda only runs the functions when needed, developers only pay for the computing time the code consumes. As such, Lambda presents excellent opportunities for scaling and cost reductions.
That briefly covers AWS and Lambda; if you want more information on this service and how it works, check out our article explaining AWS Lambda functions and architecture in further detail!
Nevertheless, now that you have familiarized yourself with AWS Lambda, the following sub-section briefly introduces the final component: Web3!
What is Web3?
Web3 is, in layman’s terms, widely understood as the latest – and third – ”generation” of the internet. The initial ”phase” or ”generation” is commonly referred to as Web1. During this phase, users mainly consumed and read content, suggesting that the experience was relatively static.
With the rise of prominent social media conglomerates, the web shifted from static content consumption to more dynamic and interactive elements. As such, users were no longer limited to reading information but could contribute by creating content themselves. However, the Web2 revolution brought significant issues associated with centralization, such as placing large quantities of personal data in the hands of large businesses and social media platforms. To solve these issues, we saw the introduction of the internet’s third generation: Web3.
Web3 aims to keep the positive dynamic aspects of Web2 while simultaneously removing the issues of centralization by creating a decentralized internet. As such, one of the primary purposes of Web3 is to create an internet where data is not owned by large corporations but rather shared among users. This shift presents great opportunities for emerging and existing companies to claim market share by innovating and disrupting conventional business models!
If you want to read more about Web3 and how it works, check out the following article: ”The Ultimate Guide to Web3”.
Nevertheless, with a brief introduction to AWS, Lambda, and Web3, the following section will explain how to get AWS Web3 ready!
How to Get AWS Web3 Ready
Both AWS and Lambda are commonly used in traditional Web2 development to build applications, websites, and other software projects. However, with the rise of Web3, blockchain developers are now looking for ways to easily get AWS Web3 ready. In doing so, they can leverage prominent services like Lambda in their Web3 development endeavors to create dapps quicker and more effectively!
Unfortunately, this is easier said than done, which is why developers are in high demand for Web3 infrastructure providers like Moralis! Moralis provides enterprise-grade Web3 APIs and other tools, making Web3 development significantly more accessible. What’s more, thanks to the many integrations Moralis feature, you can combine APIs, SDKs, etc., with other platforms like AWS!
Accordingly, one option for getting AWS Web3 ready is Moralis, and we elaborate further on this in the following section, where we explore the best AWS Web3 Lambda solution!
The Best AWS Web3 Lambda Solution
If you are looking to develop Web3 projects and want to leverage AWS services like Lambda, the easiest way to do so is with the help of Moralis, as you can quickly integrate Moralis’ NodeJS SDK with AWS Lambda!
By doing so, you can run Web3-compatible JavaScript code through this AWS service. What’s more, there are multiple ways in which you can integrate the NodeJS SDK, and two prominent examples are by creating and deploying a Lambda application or developing a Lambda NodeJS Express API. Nevertheless, by integrating the SDK, you can leverage the features and benefits of Lambda, such as automatic scaling and cost reductions, which can prove beneficial in future development endeavors!
If this sounds exciting and you want to learn more about integrating Moralis’ NodeJS SDK with AWS Lambda, follow in the next section, where we cover an AWS Lambda Web3 tutorial in further detail!
AWS Web3 Tutorial
Now that you are more familiar with AWS Lambda and why you might want to leverage this service in Web3 development, this part covers a comprehensive AWS Lambda Web3 tutorial. Furthermore, the following sections will show you how to integrate Moralis’ NodeJS SDK with Lambda, allowing you to run Web3 JavaScript functions through this AWS service. To illustrate the process, we will be developing and deploying a Lambda application with two functions: ”getNativeBalance()” and ”getWalletNfts()”.
Moreover, thanks to the accessibility of Moralis’ Lambda integration, you can create this application and get AWS Web3 ready in only three steps:
- Covering the Prerequisites
- Setting Up a New Project
- Developing the Lambda Application
So, without further ado, let’s kick things off by covering the required prerequisites!
Step 1: Covering the Prerequisites
To create this AWS Lambda app with multiple functions, you need to cover the following seven prerequisites:
- Create a Moralis account
- Install an integrated development environment (IDE)
- Set up an AWS account
- Install NodeJS
- Set up the AWS CLI
- Install Serverless Framework
- Create an IAM User
Most prerequisites are straightforward and can be dealt with using the links above. However, there are a few things you need to consider when creating the IAM user. To create the user, log in to AWS’ Management Console and open the IAM console. You then need to click on ”Users” and ”Add users” in the navigation bar. As a result, it should take you to the following page:
Once you arrive at the page above, add a username and make sure to include both credential types. When moving on to the second part, check the box for ”AdministratorAccess”:
Lastly, cover the remaining steps until you reach the last one, where you need to ensure that you download your AWS credentials in a ”.csv” file:
Step 2: Setting Up a New Project
In this second step, we will show you how to set up the project. However, before doing so, you need to configure your AWS credentials. As such, open your IDE, launch a new terminal, and run the following command:
aws configure
Once you run the command above, it’ll prompt you to input your ”AWS Secret Access Key”. Following this, you must add your ”AWS Access Key ID”. Lastly, there will be two remaining prompts, for which you only need to hit ”enter”. All in all, it should look something like this:
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY Default region name [None]: ENTER Default output format [None]: ENTER
Project Setup
With the AWS credential configurations complete, we will now show you how to set up the project. To begin with, create a new folder. Then, open it with your IDE, and run the following command in a new terminal:
serverless
This will trigger your terminal, and you must make a few decisions. For the first question, select the ”Starter” option:
Next up, name your project by inputting a name or immediately hit ”enter”:
When you name the project, it will autonomously download a new Serverless Framework template. Once it completes, the terminal will ask you to log in. For now, you can skip this by inputting ”n” and hitting ”enter”:
From there, you will be asked if you want to deploy the project. You can put this off for now by once again inputting ”n” and hitting “enter”:
As a result, you should now have a sample project in your local directory looking something like this:
Next up, add a new folder called ”functions”:
You can then go ahead and move the ”handler.js” file into this folder:
Lastly, open the ”serverless.yml” file and replace the contents with the code from the snippet below:
service: aws-node-project frameworkVersion: '3' provider: name: aws runtime: nodejs14.x environment: MORALIS_API_KEY: 'replace_me' functions: hello: handler: functions/handler.hello
Furthermore, notice that you need to add your Moralis API key by replacing ”replace_me” within the code. You can acquire the key by logging into Moralis and clicking on the ”Web3 APIs” tab:
Step 3: Developing the Lambda Application
This section shows you how to add the two functions of the application. However, before doing so, you need to install Moralis dependencies. As such, ”cd” into the project’s root folder and run the command below in the terminal:
npm install moralis
With the dependencies installed, we will progress by showing you how to add the ”getNativeBalance()” function. That function fetches the native balance of a Web3 wallet. Furthermore, we’ll also add the ”getWalletNfts()” function, which does the same for NFTs:
- ”getNativeBalance()” – To begin with, rename the existing ”handler.js” file to ”getNativeBalance.js”:
From there, open ”serverless.yml” and change the function handler and name:
Lastly, copy the code from the snippet below and replace everything within the ”getNativeBalance.js” file:
'use strict'; const Moralis = require('moralis').default; const startMoralis = async () => { await Moralis.start({ apiKey: process.env.MORALIS_API_KEY }); }; startMoralis(); module.exports.handler = async (event) => { // Get native balance const nativeBalance = await Moralis.EvmApi.balance.getNativeBalance({ address: event.address, chain: event.chain }); // Format the native balance formatted in ether via the “.ether” getter const nativeBalanceEther = nativeBalance.result.balance.ether; return { result: nativeBalanceEther } };
- ”getWalletNfts()” – To add this function, start by creating a new file called ”getWalletNfts.js”:
You can then open ”serverless.yml” and input the code below into the ”functions” section:
getWalletNfts: handler: functions/getWalletNfts.handler
Finally, open ”getWalletNfts.js” and add the code from the following snippet:
'use strict'; const Moralis = require('moralis').default; const startMoralis = async () => { await Moralis.start({ apiKey: process.env.MORALIS_API_KEY, }); }; startMoralis(); module.exports.handler = async (event) => { // Get wallet NFTs const nfts = await Moralis.EvmApi.nft.getWalletNFTs({ address: event.address, chain: event.chain, limit: 10 }); return { result: JSON.stringify(nfts) } };
Now that covers the two functions and the entirety of the Lambda application. From here, all that remains is to test and deploy the application to AWS. As such, we will take the last section to show you how to do so!
Testing and Deploying the Application
Let us start by testing the functions to ensure everything works as intended. As such, progress by creating a new file called ”event.json” in the project’s root folder:
From there, you need to add two parameters to this file, ”address” and ”chain”:
{ "address": "0x99EXAMPLEADDRESS", "chain": "chain_id" }
However, make sure you add the address of the wallet you want to monitor and the chain ID of the blockchain you want to query. With the parameters added, you can test each function. To do so, run the command below and swap ”FUNCTION_NAME” with the function’s actual name:
serverless invoke -f “FUNCTION_NAME” --path event.json
If you test ”getNativeBalance()”, it should return the following message if everything works as intended:
Once you are happy with the results, you can deploy them by navigating to the root folder of the application in your terminal and running the following command:
serverless deploy
When the app successfully deploys, you should be presented with the following output in your terminal:
That’s it for this AWS Lambda NodeJS tutorial! You now know how to create and deploy an AWS Lambda function! However, if you experienced trouble at any point during this tutorial, check out the Web3 documentation page for AWS Lambda. The documentation should hopefully answer any of your queries!
Web3 AWS Lambda – Summary
In this article, you learned how to integrate Moralis’ NodeJS SKD with AWS. Furthermore, you did so by creating a Lambda application with multiple functions. What’s more, thanks to the capabilities of Moralis, you were able to get AWS Web3 ready in only three steps:
- Covering the Prerequisites
- Setting Up a New Project
- Developing the Lambda Application
As such, if you have followed along this far, you now know how to run Web3 JavaScript code with AWS Lambda. Consequently, you can now leverage the benefits of this service, such as lowering costs and not having to worry about managing servers!
If you found this article helpful, consider checking out additional Moralis guides. For instance, you might be interested in our article exploring the ultimate ERC20 token API. Also, make sure to read our guide on how to use Polygon webhooks!
Nevertheless, no matter what Web3 development endeavor you embark on, sign up with Moralis straight away. You can create your account for free, and it only takes a couple of seconds!
Read More: moralis.io