Daniel  Hughes

Daniel Hughes

1673100900

Web3 Client Extended with Alchemy Integration

Alchemy Web3

Web3 client extended with Alchemy and browser provider integration.

⚠️ MAINTENANCE MODE ⚠️

As of July 2022, this repo is now in maintenance mode. The new SDK based on ethers.js is now available on GitHub or NPM. It has feature parity with this library as well as better typing, more abstractions, and more documentation.

Going forward, updates to this library will be made on a best-effort basis. If you see a bug or have a feature request, please open an issue or pull request on the Github issues section.

Introduction

Alchemy Web3 provides website authors with a drop-in replacement for the web3.js Ethereum API client. It produces a client matching that of web3.js, but brings multiple advantages to make use of Alchemy API:

Uses Alchemy or an injected provider as needed. Most requests will be sent through Alchemy, but requests involving signing and sending transactions are sent via a browser provider like Metamask or Trust Wallet if the user has it installed, or via a custom provider specified in options.

Easy access to Alchemy's higher level API. The client exposes methods to call Alchemy's exclusive features.

Automatically retries on rate limited requests. If Alchemy returns a 429 response (rate limited), automatically retry after a short delay. This behavior is configurable.

Robust WebSocket subscriptions which don't miss events if the WebSocket needs to be reconnected.

Alchemy Web3 is designed to require minimal configuration so you can start using it in your app right away.

Installation

With a package manager

With Yarn:

yarn add @alch/alchemy-web3

Or with NPM:

npm install @alch/alchemy-web3

With a CDN in the browser

Alternatively, add one of the following script tags to your page:

<!-- Minified -->
<script src="https://cdn.jsdelivr.net/npm/@alch/alchemy-web3@latest/dist/alchemyWeb3.min.js"></script>
<!-- Unminified -->
<script src="https://cdn.jsdelivr.net/npm/@alch/alchemy-web3@latest/dist/alchemyWeb3.js"></script>

When using this option, you can create Alchemy-Web3 instances using the global variable AlchemyWeb3.createAlchemyWeb3.

Usage

Basic Usage

You will need an Alchemy account to access the Alchemy API. If you don't have one yet, sign up here.

Create the client by importing the function createAlchemyWeb3 and then passing it your Alchemy app's URL and optionally a configuration object.

import { createAlchemyWeb3 } from "@alch/alchemy-web3";

// Using HTTPS
const web3 = createAlchemyWeb3(
  "https://eth-mainnet.alchemyapi.io/v2/<api-key>",
);

or

// Using WebSockets
const web3 = createAlchemyWeb3(
  "wss://eth-mainnet.ws.alchemyapi.io/ws/<api-key>",
);

You can use any of the methods described in the web3.js API and they will send requests to Alchemy:

// Many web3.js methods return promises.
web3.eth.getBlock("latest").then((block) => {
  /* … */
});

web3.eth
  .estimateGas({
    from: "0xge61df…",
    to: "0x087a5c…",
    data: "0xa9059c…",
    gasPrice: "0xa994f8…",
  })
  .then((gasAmount) => {
    /* … */
  });

With a Browser Provider

If the user has a provider in their browser available at window.ethereum, then any methods which involve user accounts or signing will automatically use it. This provider might be injected by Metamask, Trust Wallet or other browsers or browser extensions if the user has them installed. For example, the following will use a provider from the user's browser:

web3.eth.getAccounts().then((accounts) => {
  web3.eth.sendTransaction({
    from: accounts[0],
    to: "0x6A823E…",
    value: "1000000000000000000",
  });
});

Note on using Metamask

As just discussed, Metamask will automatically be used for accounts and signing if it is installed. However, for this to work you must first request permission from the user to access their accounts in Metamask. This is a security restriction required by Metamask: details can be found here.

To enable the use of Metamask, you must call ethereum.enable(). An example of doing so is as follows:

if (window.ethereum) {
  ethereum
    .enable()
    .then((accounts) => {
      // Metamask is ready to go!
    })
    .catch((reason) => {
      // Handle error. Likely the user rejected the login.
    });
} else {
  // The user doesn't have Metamask installed.
}

Note that doing so will display a Metamask dialog to the user if they have not already seen it and accepted, so you may choose to wait to enable Metamask until the user is about to perform an action which requires it. This is also why Alchemy Web3 will not automatically enable Metamask on page load.

With a custom provider

You may also choose to bring your own provider for writes rather than relying on one being present in the browser environment. To do so, use the writeProvider option when creating your client:

const web3 = createAlchemyWeb3(ALCHEMY_URL, { writeProvider: provider });

Your provider should expose at least one of sendAsync() or send(), as specified in EIP 1193.

You may swap out the custom provider at any time by calling the setWriteProvider() method:

web3.setWriteProvider(provider);

You may also disable the write provider entirely by passing a value of null.

Automatic Retries

If Alchemy Web3 encounters a rate limited response, it will automatically retry the request after a short delay. This behavior can be configured by passing the following options when creating your client. To disable retries, set maxRetries to 0.

maxRetries

The number of times the client will attempt to resend a rate limited request before giving up. Default: 3.

retryInterval

The minimum time waited between consecutive retries, in milliseconds. Default: 1000.

retryJitter

A random amount of time is added to the retry delay to help avoid additional rate errors caused by too many concurrent connections, chosen as a number of milliseconds between 0 and this value. Default: 250.

Sturdier WebSockets

Alchemy Web3 brings multiple improvements to ensure correct WebSocket behavior in cases of temporary network failure or dropped connections. As with any network connection, you should not assume that a WebSocket will remain open forever without interruption, but correctly handling dropped connections and reconnection by hand can be challenging to get right. Alchemy Web3 automatically adds handling for these failures with no configuration necessary.

If you use your WebSocket URL when initializing, then when you create subscriptions using web3.eth.subscribe(), Alchemy Web3 will bring the following advantages over standard Web3 subscriptions:

Unlike standard Web3, you will not permanently miss events which arrive while the backing WebSocket is temporarily down. Instead, you will receive these events as soon as the connection is reopened. Note that if the connection is down for more than 120 blocks (approximately 20 minutes), you may still miss some events that were not part of the most recent 120 blocks.

Compared to standard Web3, lowered rate of failure when sending requests over the WebSocket while the connection is down. Alchemy Web3 will attempt to send the requests once the connection is reopened. Note that it is still possible, with a lower likelihood, for outgoing requests to be lost, so you should still have error handling as with any network request.

Alchemy's Transfers API

The produced client also grants easy access to Alchemy's transfer API.

web3.alchemy.getAssetTransfers({fromBlock, toBlock, fromAddress, toAddress, contractAddresses, excludeZeroValue, maxCount, category, pageKey})

Returns an array of asset transfers based on the specified parameters.

Parameters:

An object with the following fields:

  • fromBlock: Optional inclusive from hex string block (default latest)
  • toBlock: Optional inclusive to hex string block (default latest)
  • order: Optional string that specifies the ordering of the results by block number. Must be one of ["asc", "desc"] (default "asc")
  • fromAddress: Optional from hex string address (default wildcard)
  • toAddress: Optional to hex string address (default wildcard) NOTE: fromAddress is ANDed with toAddress
  • contractAddresses: Optional array of hex string contract addresses for "token" transfers (default wildcard) NOTE: contractAddresses are ORed together
  • excludeZeroValue: Optional boolean to exclude transfers with zero value (default true)
  • maxCount: Optional number to restrict payload size (default and max of 1000)
  • category: Optional array of categories (defaults to the following categories: ["external", "internal", "token"])
  • pageKey: Optional uuid pageKey to retrieve the next payload

Returns:

An object with the following fields:

  • pageKey: Uuid for next page of results (undefined for the last page of results).
  • transfers: An array of objects with the following fields sorted in ascending order by block number
    • category: "external", "internal", "token", "erc20", "erc721", "erc1155" - label for the transfer
    • blockNum: The block where the transfer occurred (hex string).
    • from: From address of transfer (hex string).
    • to: To address of transfer (hex string). null if contract creation.
    • value: Converted asset transfer value as a number (raw value divided by contract decimal). null if erc721 transfer or contract decimal not available.
    • erc721TokenId: Raw erc721 token id (hex string). null if not an erc721 transfer
    • erc1155Metadata: A list of objects containing the erc1155 tokenId (hex string) and value (hex string). null if not an erc1155 transfer
    • asset: "ETH" or the token's symbol. null if not defined in the contract and not available from other sources.
    • hash: Transaction hash (hex string).
    • rawContract: Object of raw values:
      • value: Raw transfer value (hex string). null if erc721 or erc1155 transfer
      • address: Contract address (hex string). null if "external" or "internal"
      • decimal: Contract decimal (hex string). null if not defined in the contract and not available from other sources.

Alchemy's Enhanced API

The produced client also grants easy access to Alchemy's enhanced API.

web3.alchemy.getTokenAllowance({contract, owner, spender})

Returns token balances for a specific address given a list of contracts.

Parameters:

An object with the following fields:

  • contract: The address of the token contract.
  • owner: The address of the token owner.
  • spender: The address of the token spender.

Returns:

The allowance amount, as a string representing a base-10 number.

web3.alchemy.getTokenBalances(address, contractAddresses)

Returns token balances for a specific address given a list of contracts.

Parameters:

  1. address: The address for which token balances will be checked.
  2. contractAddresses: An optional array of contract addresses. Not specifying this will return all token balances.

Returns:

An object with the following fields:

  • address: The address for which token balances were checked.
  • tokenBalances: An array of token balance objects. Each object contains:
    • contractAddress: The address of the contract.
    • tokenBalance: The balance of the contract, as a string representing a base-10 number.
    • error: An error string. One of this or tokenBalance will be null.

web3.alchemy.getTokenMetadata(address)

Returns metadata (name, symbol, decimals, logo) for a given token contract address.

Parameters:

address: The address of the token contract.

Returns:

An object with the following fields:

  • name: The token's name. null if not defined in the contract and not available from other sources.
  • symbol: The token's symbol. null if not defined in the contract and not available from other sources.
  • decimals: The token's decimals. null if not defined in the contract and not available from other sources.
  • logo: URL of the token's logo image. null if not available.

web3.alchemy.getNfts({owner, pageKey, contractAddresses})

Parameters:

An object with the following fields:

  • owner: The address that you want to fetch NFTs for.
  • pageKey: (Optional) A key to fetch the next page of results.
  • contractAddresses: (Optional) An array of contract addresses to filter the owner's results to.
  • withMetadata: (Optional) If false, the returned NFTs will omit metadata. Defaults to true.

Returns:

When metadata is included, the returned object has the following fields:

  • ownedNfts: An array of NFT objects that the address owns. Each NFT object has the following structure.
    • contract:
      • address: The address of the contract or collection that the NFT belongs to.
    • id:
      • tokenId: Raw token id.
      • tokenMetadata:
        • tokenType: The type of token being sent as part of the request (Can be one of ["erc721" | "erc1155"]).
    • title: The title of the NFT, or an empty string if no title is available.
    • description: The descriptions of the NFT, or an empty string if no description is available.
    • tokenUri: (Optional)
      • raw: Uri representing the location of the NFT's original metadata blob. This is a backup for you to parse when the metadata field is not automatically populated.
      • gateway: Public gateway uri for the raw uri.
    • media: (Optional) An array of objects with the following structure.
      • uri: A tokenUri as described above.
    • metadata: (Optional)
      • image: (Optional) A uri string that should be usable in an tag.
      • attributes: (Optional) An array of attributes from the NFT metadata. Each attribute is a dictionary with unknown keys and values, as they depend directly on the contract.
    • timeLastUpdated: ISO timestamp of the last cache refresh for the information returned in the metadata field.
  • pageKey: (Optional) A key to fetch the next page of results, if applicable.
  • totalCount: The total number of NFTs in the result set.

If metadata is omitted, an object with the following fields is returned:

  • ownedNfts: An array of NFT objects that the address owns. Each NFT object has the following structure.
    • contract:
      • address: The address of the contract or collection that the NFT belongs to.
    • id:
      • tokenId: Raw token id.
      • tokenMetadata:
        • tokenType: The type of token being sent as part of the request (Can be one of ["erc721" | "erc1155"]).
  • pageKey: (Optional) A key to fetch the next page of results, if applicable.
  • totalCount: The total number of NFTs in the result set.

web3.alchemy.getNftMetadata({contractAddress, tokenId, tokenType})

Parameters:

An object with the following fields:

  • contract: The address of the token contract.
  • tokenId: Raw token id (hex string).
  • tokenType: (Optional) The type of token being sent as part of the request (Can be one of ["erc721" | "erc1155"]).

Returns:

An object with the following fields:

  • contract:
    • address: The hex string of the contract addresses for "token" transfers.
  • id:
    • tokenId: Raw token id.
    • tokenMetadata:
      • tokenType: The type of token being sent as part of the request (Can be one of ["erc721" | "erc1155"]).
  • title: Name of NFT.
  • description: A brief description of the NFT taken from the contract metadata.
  • tokenUri: (Optional)
    • raw: Uri representing the location of the NFT's original metadata blob. This is a backup for you to parse when the metadata field is not automatically populated.
    • gateway: Public gateway uri for the raw uri.
  • media: (Optional) An array of objects with the following structure.
    • uri: A tokenUri as described above.
  • metadata: (Optional)
    • image: (Optional) A uri string that should be usable in an tag.
    • attributes: (Optional) An array of attributes from the NFT metadata. Each attribute is a dictionary with unknown keys and values, as they depend directly on the contract.
  • timeLastUpdated: ISO timestamp of the last cache refresh for the information returned in the metadata field.

web3.alchemy.getTransactionReceipts({blockNumber | blockHash})

Fetches all transaction receipts for a block number or a block hash.

Parameters:

  • blockNumber - (hex) The block number to get transaction receipts for
  • blockHash - The block hash to get transaction receipts for

Note that either blockNumber or blockHash can be set.

Returns:

  • {receipts: TransactionReceipt[]} | null - An array of transaction receipts, or null if the block number or hash is not found.

The returned object is a list of transaction receipts for each transaction in this block. See eth_getTransactionReceipt for the payload of an individual transaction receipt.

web3.eth.subscribe("alchemy_fullPendingTransactions")

Subscribes to pending transactions, similar to the standard Web3 call web3.eth.subscribe("pendingTransactions"), but differs in that it emits full transaction information rather than just transaction hashes.

Note that the argument passed to this function is permitted to be either of "alchemy_fullPendingTransactions" or "alchemy_newFullPendingTransactions", which have the same effect. The latter is the string used in raw eth_subscribe JSON-RPC calls, while the former is consistent with the existing Web3.js subscription APIs (for example, web3.eth.subscribe("pendingTransactions") corresponds to the raw JSON-RPC call of type newPendingTransactions). While this is unfortunately confusing, supporting both strings attempts to balance consistency and convenience.

web3.eth.subscribe("alchemy_filteredFullPendingTransactions", options)

Like an alchemy_fullPendingTransactions subscription, but also allows passing an options argument containing an address field to filter the returned transactions to those from or to the specified address. The options argument is as described in the documentation here.

Similar to the previous point, note that the argument passed to this function may be either of "alchemy_filteredFullPendingTransactions" or "alchemy_filteredNewPendingTransactions".


 

Copyright © 2019 Alchemy Insights Inc.

EIP 1559

web3.eth.getFeeHistory(blockRange, startingBlock, percentiles[])

Fetches the fee history for the given block range as per the eth spec.

Parameters

  • blockRange: The number of blocks for which to fetch historical fees. Can be an integer or a hex string.
  • startingBlock: The block to start the search. The result will look backwards from here. Can be a hex string or a predefined block string e.g. "latest".
  • percentiles: (Optional) An array of numbers that define which percentiles of reward values you want to see for each block.

Returns

An object with the following fields:

  • oldestBlock: The oldest block in the range that the fee history is being returned for.
  • baseFeePerGas: An array of base fees for each block in the range that was looked up. These are the same values that would be returned on a block for the eth_getBlockByNumber method.
  • gasUsedRatio: An array of the ratio of gas used to gas limit for each block.
  • reward: Only returned if a percentiles parameter was provided. Each block will have an array corresponding to the percentiles provided. Each element of the nested array will have the tip provided to miners for the percentile given. So if you provide [50, 90] as the percentiles then each block will have a 50th percentile reward and a 90th percentile reward.

Example

Method call

web3.eth.getFeeHistory(4, "latest", [25, 50, 75]).then(console.log);

Logged response

{
  oldestBlock: 12930639,
  reward: [
    [ '0x649534e00', '0x66720b300', '0x826299e00' ],
    [ '0x649534e00', '0x684ee1800', '0x7ea8ed400' ],
    [ '0x5ea8dd480', '0x60db88400', '0x684ee1800' ],
    [ '0x59682f000', '0x5d21dba00', '0x5d21dba00' ]
  ],
  baseFeePerGas: [ '0x0', '0x0', '0x0', '0x0', '0x0' ],
  gasUsedRatio: [ 0.9992898398856537, 0.9999566454373825, 0.9999516, 0.9999378 ]
}

web3.eth.getMaxPriorityFeePerGas()

Returns a quick estimate for maxPriorityFeePerGas in EIP 1559 transactions. Rather than using feeHistory and making a calculation yourself you can just use this method to get a quick estimate. Note: this is a geth-only method, but Alchemy handles that for you behind the scenes.

Parameters

None!

Returns

A hex, which is the maxPriorityFeePerGas suggestion. You can plug this directly into your transaction field.

Example

Method call

web3.eth.getMaxPriorityFeePerGas().then(console.log);

Logged response

0x560de0700

Download details:

Author:  alchemyplatform
Source code: https://github.com/alchemyplatform/alchemy-web3

License: MIT license

#web3 #blockchain 

What is GEEK

Buddha Community

Web3 Client Extended with Alchemy Integration
Daniel  Hughes

Daniel Hughes

1673100900

Web3 Client Extended with Alchemy Integration

Alchemy Web3

Web3 client extended with Alchemy and browser provider integration.

⚠️ MAINTENANCE MODE ⚠️

As of July 2022, this repo is now in maintenance mode. The new SDK based on ethers.js is now available on GitHub or NPM. It has feature parity with this library as well as better typing, more abstractions, and more documentation.

Going forward, updates to this library will be made on a best-effort basis. If you see a bug or have a feature request, please open an issue or pull request on the Github issues section.

Introduction

Alchemy Web3 provides website authors with a drop-in replacement for the web3.js Ethereum API client. It produces a client matching that of web3.js, but brings multiple advantages to make use of Alchemy API:

Uses Alchemy or an injected provider as needed. Most requests will be sent through Alchemy, but requests involving signing and sending transactions are sent via a browser provider like Metamask or Trust Wallet if the user has it installed, or via a custom provider specified in options.

Easy access to Alchemy's higher level API. The client exposes methods to call Alchemy's exclusive features.

Automatically retries on rate limited requests. If Alchemy returns a 429 response (rate limited), automatically retry after a short delay. This behavior is configurable.

Robust WebSocket subscriptions which don't miss events if the WebSocket needs to be reconnected.

Alchemy Web3 is designed to require minimal configuration so you can start using it in your app right away.

Installation

With a package manager

With Yarn:

yarn add @alch/alchemy-web3

Or with NPM:

npm install @alch/alchemy-web3

With a CDN in the browser

Alternatively, add one of the following script tags to your page:

<!-- Minified -->
<script src="https://cdn.jsdelivr.net/npm/@alch/alchemy-web3@latest/dist/alchemyWeb3.min.js"></script>
<!-- Unminified -->
<script src="https://cdn.jsdelivr.net/npm/@alch/alchemy-web3@latest/dist/alchemyWeb3.js"></script>

When using this option, you can create Alchemy-Web3 instances using the global variable AlchemyWeb3.createAlchemyWeb3.

Usage

Basic Usage

You will need an Alchemy account to access the Alchemy API. If you don't have one yet, sign up here.

Create the client by importing the function createAlchemyWeb3 and then passing it your Alchemy app's URL and optionally a configuration object.

import { createAlchemyWeb3 } from "@alch/alchemy-web3";

// Using HTTPS
const web3 = createAlchemyWeb3(
  "https://eth-mainnet.alchemyapi.io/v2/<api-key>",
);

or

// Using WebSockets
const web3 = createAlchemyWeb3(
  "wss://eth-mainnet.ws.alchemyapi.io/ws/<api-key>",
);

You can use any of the methods described in the web3.js API and they will send requests to Alchemy:

// Many web3.js methods return promises.
web3.eth.getBlock("latest").then((block) => {
  /* … */
});

web3.eth
  .estimateGas({
    from: "0xge61df…",
    to: "0x087a5c…",
    data: "0xa9059c…",
    gasPrice: "0xa994f8…",
  })
  .then((gasAmount) => {
    /* … */
  });

With a Browser Provider

If the user has a provider in their browser available at window.ethereum, then any methods which involve user accounts or signing will automatically use it. This provider might be injected by Metamask, Trust Wallet or other browsers or browser extensions if the user has them installed. For example, the following will use a provider from the user's browser:

web3.eth.getAccounts().then((accounts) => {
  web3.eth.sendTransaction({
    from: accounts[0],
    to: "0x6A823E…",
    value: "1000000000000000000",
  });
});

Note on using Metamask

As just discussed, Metamask will automatically be used for accounts and signing if it is installed. However, for this to work you must first request permission from the user to access their accounts in Metamask. This is a security restriction required by Metamask: details can be found here.

To enable the use of Metamask, you must call ethereum.enable(). An example of doing so is as follows:

if (window.ethereum) {
  ethereum
    .enable()
    .then((accounts) => {
      // Metamask is ready to go!
    })
    .catch((reason) => {
      // Handle error. Likely the user rejected the login.
    });
} else {
  // The user doesn't have Metamask installed.
}

Note that doing so will display a Metamask dialog to the user if they have not already seen it and accepted, so you may choose to wait to enable Metamask until the user is about to perform an action which requires it. This is also why Alchemy Web3 will not automatically enable Metamask on page load.

With a custom provider

You may also choose to bring your own provider for writes rather than relying on one being present in the browser environment. To do so, use the writeProvider option when creating your client:

const web3 = createAlchemyWeb3(ALCHEMY_URL, { writeProvider: provider });

Your provider should expose at least one of sendAsync() or send(), as specified in EIP 1193.

You may swap out the custom provider at any time by calling the setWriteProvider() method:

web3.setWriteProvider(provider);

You may also disable the write provider entirely by passing a value of null.

Automatic Retries

If Alchemy Web3 encounters a rate limited response, it will automatically retry the request after a short delay. This behavior can be configured by passing the following options when creating your client. To disable retries, set maxRetries to 0.

maxRetries

The number of times the client will attempt to resend a rate limited request before giving up. Default: 3.

retryInterval

The minimum time waited between consecutive retries, in milliseconds. Default: 1000.

retryJitter

A random amount of time is added to the retry delay to help avoid additional rate errors caused by too many concurrent connections, chosen as a number of milliseconds between 0 and this value. Default: 250.

Sturdier WebSockets

Alchemy Web3 brings multiple improvements to ensure correct WebSocket behavior in cases of temporary network failure or dropped connections. As with any network connection, you should not assume that a WebSocket will remain open forever without interruption, but correctly handling dropped connections and reconnection by hand can be challenging to get right. Alchemy Web3 automatically adds handling for these failures with no configuration necessary.

If you use your WebSocket URL when initializing, then when you create subscriptions using web3.eth.subscribe(), Alchemy Web3 will bring the following advantages over standard Web3 subscriptions:

Unlike standard Web3, you will not permanently miss events which arrive while the backing WebSocket is temporarily down. Instead, you will receive these events as soon as the connection is reopened. Note that if the connection is down for more than 120 blocks (approximately 20 minutes), you may still miss some events that were not part of the most recent 120 blocks.

Compared to standard Web3, lowered rate of failure when sending requests over the WebSocket while the connection is down. Alchemy Web3 will attempt to send the requests once the connection is reopened. Note that it is still possible, with a lower likelihood, for outgoing requests to be lost, so you should still have error handling as with any network request.

Alchemy's Transfers API

The produced client also grants easy access to Alchemy's transfer API.

web3.alchemy.getAssetTransfers({fromBlock, toBlock, fromAddress, toAddress, contractAddresses, excludeZeroValue, maxCount, category, pageKey})

Returns an array of asset transfers based on the specified parameters.

Parameters:

An object with the following fields:

  • fromBlock: Optional inclusive from hex string block (default latest)
  • toBlock: Optional inclusive to hex string block (default latest)
  • order: Optional string that specifies the ordering of the results by block number. Must be one of ["asc", "desc"] (default "asc")
  • fromAddress: Optional from hex string address (default wildcard)
  • toAddress: Optional to hex string address (default wildcard) NOTE: fromAddress is ANDed with toAddress
  • contractAddresses: Optional array of hex string contract addresses for "token" transfers (default wildcard) NOTE: contractAddresses are ORed together
  • excludeZeroValue: Optional boolean to exclude transfers with zero value (default true)
  • maxCount: Optional number to restrict payload size (default and max of 1000)
  • category: Optional array of categories (defaults to the following categories: ["external", "internal", "token"])
  • pageKey: Optional uuid pageKey to retrieve the next payload

Returns:

An object with the following fields:

  • pageKey: Uuid for next page of results (undefined for the last page of results).
  • transfers: An array of objects with the following fields sorted in ascending order by block number
    • category: "external", "internal", "token", "erc20", "erc721", "erc1155" - label for the transfer
    • blockNum: The block where the transfer occurred (hex string).
    • from: From address of transfer (hex string).
    • to: To address of transfer (hex string). null if contract creation.
    • value: Converted asset transfer value as a number (raw value divided by contract decimal). null if erc721 transfer or contract decimal not available.
    • erc721TokenId: Raw erc721 token id (hex string). null if not an erc721 transfer
    • erc1155Metadata: A list of objects containing the erc1155 tokenId (hex string) and value (hex string). null if not an erc1155 transfer
    • asset: "ETH" or the token's symbol. null if not defined in the contract and not available from other sources.
    • hash: Transaction hash (hex string).
    • rawContract: Object of raw values:
      • value: Raw transfer value (hex string). null if erc721 or erc1155 transfer
      • address: Contract address (hex string). null if "external" or "internal"
      • decimal: Contract decimal (hex string). null if not defined in the contract and not available from other sources.

Alchemy's Enhanced API

The produced client also grants easy access to Alchemy's enhanced API.

web3.alchemy.getTokenAllowance({contract, owner, spender})

Returns token balances for a specific address given a list of contracts.

Parameters:

An object with the following fields:

  • contract: The address of the token contract.
  • owner: The address of the token owner.
  • spender: The address of the token spender.

Returns:

The allowance amount, as a string representing a base-10 number.

web3.alchemy.getTokenBalances(address, contractAddresses)

Returns token balances for a specific address given a list of contracts.

Parameters:

  1. address: The address for which token balances will be checked.
  2. contractAddresses: An optional array of contract addresses. Not specifying this will return all token balances.

Returns:

An object with the following fields:

  • address: The address for which token balances were checked.
  • tokenBalances: An array of token balance objects. Each object contains:
    • contractAddress: The address of the contract.
    • tokenBalance: The balance of the contract, as a string representing a base-10 number.
    • error: An error string. One of this or tokenBalance will be null.

web3.alchemy.getTokenMetadata(address)

Returns metadata (name, symbol, decimals, logo) for a given token contract address.

Parameters:

address: The address of the token contract.

Returns:

An object with the following fields:

  • name: The token's name. null if not defined in the contract and not available from other sources.
  • symbol: The token's symbol. null if not defined in the contract and not available from other sources.
  • decimals: The token's decimals. null if not defined in the contract and not available from other sources.
  • logo: URL of the token's logo image. null if not available.

web3.alchemy.getNfts({owner, pageKey, contractAddresses})

Parameters:

An object with the following fields:

  • owner: The address that you want to fetch NFTs for.
  • pageKey: (Optional) A key to fetch the next page of results.
  • contractAddresses: (Optional) An array of contract addresses to filter the owner's results to.
  • withMetadata: (Optional) If false, the returned NFTs will omit metadata. Defaults to true.

Returns:

When metadata is included, the returned object has the following fields:

  • ownedNfts: An array of NFT objects that the address owns. Each NFT object has the following structure.
    • contract:
      • address: The address of the contract or collection that the NFT belongs to.
    • id:
      • tokenId: Raw token id.
      • tokenMetadata:
        • tokenType: The type of token being sent as part of the request (Can be one of ["erc721" | "erc1155"]).
    • title: The title of the NFT, or an empty string if no title is available.
    • description: The descriptions of the NFT, or an empty string if no description is available.
    • tokenUri: (Optional)
      • raw: Uri representing the location of the NFT's original metadata blob. This is a backup for you to parse when the metadata field is not automatically populated.
      • gateway: Public gateway uri for the raw uri.
    • media: (Optional) An array of objects with the following structure.
      • uri: A tokenUri as described above.
    • metadata: (Optional)
      • image: (Optional) A uri string that should be usable in an tag.
      • attributes: (Optional) An array of attributes from the NFT metadata. Each attribute is a dictionary with unknown keys and values, as they depend directly on the contract.
    • timeLastUpdated: ISO timestamp of the last cache refresh for the information returned in the metadata field.
  • pageKey: (Optional) A key to fetch the next page of results, if applicable.
  • totalCount: The total number of NFTs in the result set.

If metadata is omitted, an object with the following fields is returned:

  • ownedNfts: An array of NFT objects that the address owns. Each NFT object has the following structure.
    • contract:
      • address: The address of the contract or collection that the NFT belongs to.
    • id:
      • tokenId: Raw token id.
      • tokenMetadata:
        • tokenType: The type of token being sent as part of the request (Can be one of ["erc721" | "erc1155"]).
  • pageKey: (Optional) A key to fetch the next page of results, if applicable.
  • totalCount: The total number of NFTs in the result set.

web3.alchemy.getNftMetadata({contractAddress, tokenId, tokenType})

Parameters:

An object with the following fields:

  • contract: The address of the token contract.
  • tokenId: Raw token id (hex string).
  • tokenType: (Optional) The type of token being sent as part of the request (Can be one of ["erc721" | "erc1155"]).

Returns:

An object with the following fields:

  • contract:
    • address: The hex string of the contract addresses for "token" transfers.
  • id:
    • tokenId: Raw token id.
    • tokenMetadata:
      • tokenType: The type of token being sent as part of the request (Can be one of ["erc721" | "erc1155"]).
  • title: Name of NFT.
  • description: A brief description of the NFT taken from the contract metadata.
  • tokenUri: (Optional)
    • raw: Uri representing the location of the NFT's original metadata blob. This is a backup for you to parse when the metadata field is not automatically populated.
    • gateway: Public gateway uri for the raw uri.
  • media: (Optional) An array of objects with the following structure.
    • uri: A tokenUri as described above.
  • metadata: (Optional)
    • image: (Optional) A uri string that should be usable in an tag.
    • attributes: (Optional) An array of attributes from the NFT metadata. Each attribute is a dictionary with unknown keys and values, as they depend directly on the contract.
  • timeLastUpdated: ISO timestamp of the last cache refresh for the information returned in the metadata field.

web3.alchemy.getTransactionReceipts({blockNumber | blockHash})

Fetches all transaction receipts for a block number or a block hash.

Parameters:

  • blockNumber - (hex) The block number to get transaction receipts for
  • blockHash - The block hash to get transaction receipts for

Note that either blockNumber or blockHash can be set.

Returns:

  • {receipts: TransactionReceipt[]} | null - An array of transaction receipts, or null if the block number or hash is not found.

The returned object is a list of transaction receipts for each transaction in this block. See eth_getTransactionReceipt for the payload of an individual transaction receipt.

web3.eth.subscribe("alchemy_fullPendingTransactions")

Subscribes to pending transactions, similar to the standard Web3 call web3.eth.subscribe("pendingTransactions"), but differs in that it emits full transaction information rather than just transaction hashes.

Note that the argument passed to this function is permitted to be either of "alchemy_fullPendingTransactions" or "alchemy_newFullPendingTransactions", which have the same effect. The latter is the string used in raw eth_subscribe JSON-RPC calls, while the former is consistent with the existing Web3.js subscription APIs (for example, web3.eth.subscribe("pendingTransactions") corresponds to the raw JSON-RPC call of type newPendingTransactions). While this is unfortunately confusing, supporting both strings attempts to balance consistency and convenience.

web3.eth.subscribe("alchemy_filteredFullPendingTransactions", options)

Like an alchemy_fullPendingTransactions subscription, but also allows passing an options argument containing an address field to filter the returned transactions to those from or to the specified address. The options argument is as described in the documentation here.

Similar to the previous point, note that the argument passed to this function may be either of "alchemy_filteredFullPendingTransactions" or "alchemy_filteredNewPendingTransactions".


 

Copyright © 2019 Alchemy Insights Inc.

EIP 1559

web3.eth.getFeeHistory(blockRange, startingBlock, percentiles[])

Fetches the fee history for the given block range as per the eth spec.

Parameters

  • blockRange: The number of blocks for which to fetch historical fees. Can be an integer or a hex string.
  • startingBlock: The block to start the search. The result will look backwards from here. Can be a hex string or a predefined block string e.g. "latest".
  • percentiles: (Optional) An array of numbers that define which percentiles of reward values you want to see for each block.

Returns

An object with the following fields:

  • oldestBlock: The oldest block in the range that the fee history is being returned for.
  • baseFeePerGas: An array of base fees for each block in the range that was looked up. These are the same values that would be returned on a block for the eth_getBlockByNumber method.
  • gasUsedRatio: An array of the ratio of gas used to gas limit for each block.
  • reward: Only returned if a percentiles parameter was provided. Each block will have an array corresponding to the percentiles provided. Each element of the nested array will have the tip provided to miners for the percentile given. So if you provide [50, 90] as the percentiles then each block will have a 50th percentile reward and a 90th percentile reward.

Example

Method call

web3.eth.getFeeHistory(4, "latest", [25, 50, 75]).then(console.log);

Logged response

{
  oldestBlock: 12930639,
  reward: [
    [ '0x649534e00', '0x66720b300', '0x826299e00' ],
    [ '0x649534e00', '0x684ee1800', '0x7ea8ed400' ],
    [ '0x5ea8dd480', '0x60db88400', '0x684ee1800' ],
    [ '0x59682f000', '0x5d21dba00', '0x5d21dba00' ]
  ],
  baseFeePerGas: [ '0x0', '0x0', '0x0', '0x0', '0x0' ],
  gasUsedRatio: [ 0.9992898398856537, 0.9999566454373825, 0.9999516, 0.9999378 ]
}

web3.eth.getMaxPriorityFeePerGas()

Returns a quick estimate for maxPriorityFeePerGas in EIP 1559 transactions. Rather than using feeHistory and making a calculation yourself you can just use this method to get a quick estimate. Note: this is a geth-only method, but Alchemy handles that for you behind the scenes.

Parameters

None!

Returns

A hex, which is the maxPriorityFeePerGas suggestion. You can plug this directly into your transaction field.

Example

Method call

web3.eth.getMaxPriorityFeePerGas().then(console.log);

Logged response

0x560de0700

Download details:

Author:  alchemyplatform
Source code: https://github.com/alchemyplatform/alchemy-web3

License: MIT license

#web3 #blockchain 

erick salah

1600756660

QuickBooks Amazon Integration | Steps to Integrate | +1(844)313-4856

QuickBooks accounting software always surprises with its amazing features. The addition of QuickBooks in Amazon bring more profits. The aim of this integration is to monitor and track the entire process more accurately to increase the business economy. This article will provide a brief description of “QuickBooks Amazon Integration” along with its advanced features.

Brief Description :
Make Amazon Accounting Automated - To find accuracy and less-time consuming process, amazon needs to integrate with QuickBooks accounting software. It makes the entire amazon accountancy automated to find better results and to reduce human efforts. In that way, they have more time to focus on all other services also. With these things, they will able to focus on each process to get potential profit.
With help of this integration, Amazon seller knows and understands all financial issues like never before. It helps to identify and manage your entire Amazon transaction data. After syncing with this approach, you can work more confidently to track FBA fees, inventory cost, taxes, shipping expenses, and many more processes. It introduces many advanced features such as Advanced Automation, Dedicated support, Full Analytics, Easy Installation, and Affordable cost.
After integration, you can easily import Amazon order related information into the QuickBooks self-employed to meet with easy techniques to categorize the business transaction. This amazing feature is only available via QuickBooks self-employed labs to choose the users. To integrate with your Amazon account, perform the below steps:
o From the upper right corner, choose the “Gear” icon
o Then choose “Labs” and then click on the “Turn it On” option
o After that, fill your Amazon credentials
o Then, it permits the connection to complete the process
Once you have integrated with Amazon, you can easily view a few orders at very first. Whenever transactions are imported via connected amazing to view order details, then they will easily be identified how many products have been attached to it. You have the option to split all transactions by order product.
While parting in QuickBooks Self-Employed, the transactions default to a split by thing, with the delivery and sales taxes for the allocated order relatively over the items.
New things you get in QuickBooks Amazon Integration:
Record your Orders:
∙ you can easily record order individually or summed up by month, week, day, or a specific settlement period with journal entries
∙ You can easily create invoices and sales Receipts
∙ In QuickBooks, consequently, update your inventory with each Amazon deal
∙ In QuickBooks, missing products automatically create
∙ Easy to access all details about record transactions such as Sales tax, discount promo codes, payment method. The shipping method, shipping address, and billing address
∙ Work with QuickBooks class-tracking, assemblies, bundle items, and group item
∙ Along with QuickBooks, You can work with all type of currencies
Sync Inventory:
∙ You can easily hold on to inventory levels updated with every sale and return
∙ Forecasting Inventory
∙ While adding stock to your QuickBooks, you find Automatically update inventory levels
∙ Sync items escorted by variations
∙ You can easily work with QuickBooks Enterprises advanced inventory module
∙ East to track numerous inventory sites
Sales tax Compliance:
∙ You can work for both single as well as multiple tax jurisdictions
∙ Guide Sales tax to an explicit product in QuickBooks for exact sales tax filing
Reports you want them:
∙ To find the reports in your manner, how Amazon Channel performing with a summary of transactions
∙ You get a clear view of all profits and losses by order, region, product, customer, and many more.
Listings:
∙ you can publish your products from QuickBooks to your Amazon store including images and all other related details.
∙ Bulk Export listing
Fully Automated:
Utilize the scheduler to automate all posting to find accuracy in real-time
Manage Refunds & cancellations:
You can easily make credit memos against the initial sale for exact transaction level accounting
Handle high volumes:
● You can easily record thousands of transactions per day
● You can easily record or utilize summaries to keep the QuickBooks company file smaller
Generate purchase orders:
● You find advanced configurable settings for generating POs
● Automated process to generate the vendor emails & purchase orders
It integrates with your all Amazon stores and capabilities such as amazon prime, Amazon.com, Amazon UK, Amazon EU, Amazon Canada, Amazon Mexico, FBA, and Amazon Seller central
Few things to remember:
No new transactions are made. Existing transactions imported from your bank or credit card coordinated to orders on Amazon and the order related items are added to them.
For Amazon to order details to show up in QuickBooks Self-Employed, you more likely than not associated with the record you use to buy items on Amazon. In any case, if the record isn’t associated, the transaction details won’t show up in light of the fact that they won’t match the transaction. So in case if you utilize two installment techniques on Amazon, just the items bought with the installment strategy associated with QuickBooks Self-Employed will appear in QuickBooks Self-Employed. Items bought with a gift card or limited-time credit won’t show up.
After you’ve spared the part transaction, your work will stay, regardless of whether you select to kill the Amazon combination. Just the actual order items will vanish from the transaction.
Conclusion:
I hope the above information helps you know about the benefits and all the necessary information about the “QuickBooks Amazon Integration” It helps to grow your business with new ideas. QuickBooks’ in-built features reduce all complex issues to make things easy and simple. Thank you for spending your quality time to read my blog. If you have any doubt regarding the QuickBooks Amazon integration . then you can call our QuickBooks Support team at +1-844-313-4856 or do live chat with our QuickBooks online support team 24x7.

##quickbooks amazon integration ##quickbooks amazon ##integration quickbooks with amazon ##qb amazon integration

Einar  Hintz

Einar Hintz

1599364620

API Integration Practices and Patterns

We all hear it so often that we almost stop hearing it: “Integration is critical to meeting users’ needs.”

Integration work consumes 50%-80% of the time and budget of digital transformation projects, or building a digital platform, while innovation gets only the leftovers, according to SAP and Salesforce. And as everyone from legacy enterprises to SaaS startups launches new digital products, they all hit a point at which the product cannot unlock more value for users or continue to grow without making integration a feature.

If I were to sum up the one question behind all of the other questions that I hear from customers, enterprises, partners, and developers, it would be something like: “Is integration a differentiator that we should own? Or an undifferentiated but necessary feature that supports what we’re trying to accomplish?”

This Refcard won’t try to answer that question for you. Rather, no matter what type of development work you do, API integration is a fact of life today, like gravity. Why? Today, experience is paramount. The average enterprise uses more than 1,500 cloud applications (with the number growing by 20% each year). Every app needs to integrate with other systems in a fluid and ever-changing application ecosystem. So instead, I’ll share some of the common practices you’re likely to contend with as well as some patterns to consider.


This is a preview of the API Integrations Practices and Patterns Refcard. To read the entire Refcard, please download the PDF from the link above.

#apis #api integration #integration patterns #api cloud #api patterns #api authentication #api errors #apis and integrations

How to Build a 2D Web3 Game

Do you recall the early days of the video game industry when classic games in 2D environments had everyone stuck to their screen for hours? Retro games are still quite popular, and even modern game developers still create 2D games today. However, Web3 brings new concepts to the gaming industry, such as the play-to-earn (P2E) model, where players can earn fungible and non-fungible tokens (NFTs). Thus, if we combine popular 2D environments and Web3, offering earning potentials, the ability to use NFTs as in-game assets, etc., our 2D Web3 game would attract numerous users. As such, we decided to illustrate herein how to build a 2D Web3 game using the right Web3 tech stack and accomplish this process in a matter of minutes.

Moving forward, we’ll incorporate a publicly available 2D game into a React application. In addition, to include Web3 functionality, we’ll use the ultimate Web3 development platform, Moralis. This “Firebase for crypto” platform will enable us to easily incorporate Web3 authentication using the most popular Web3 walletMetaMask. Also, with Moralis’ SDK, we will get a chance to add other on-chain features to our 2D Web3 game example. Plus, we’ll rely on some other phenomenal tools to get us to the finish line, such as Phaser and Visual Studio Code (VSC). Nonetheless, we encourage you to follow our lead and join us by tackling this example project. By doing so, you will not only learn to create a 2D Web3 game but also get familiar with the tools mentioned above. So, create your free Moralis account, which you’ll need as we move on.    

Preview of Our 2D Web3 Game Example

Before we start our example project, we want to do a quick demo of our example 2D Web3 game. This will help you determine whether or not you want to roll up your sleeves and follow our tutorial as we move on. 

First, users are greeted by the “Start” button:

Web3 Game Login

By clicking on the above button, users are prompted by their MetaMask extensions to sign the “Log in using Moralis” message. Essentially, this is how to authenticate with MetaMask:  

After receiving the above signature request, users need to click on the “Sign” button. By doing so, they complete their Web3 login for our game. 

Also, keep in mind that there are different ways to implement Web3 authentication. However, when using Moralis, things are made as simple as possible. For web dapps (decentralized applications), MetaMask integration is the go-to tool. On the other hand, WalletConnect is the best solution for mobile dapps. Nonetheless, Moralis also offers Web3 authentication via email and Web3 social login. Both of these options are excellent to boost Web3 user onboarding success rates.

The Aim of Our 2D Web3 Game

Once users confirm the sign-in message, they are presented with the game’s main menu screen: 

Then, users need to click anywhere on the screen to start the game. This loads the game: 

Moreover, the purpose of the game is to click (shoot) the bandits (cowboys with the guns) before they shoot you. As you can see in the screenshot above, there are also characters with money bags. Players are not supposed to shoot them. In addition, the numbers at the top indicate the money bags that players need to collect to complete the level. However, if any of the bandits shoot the player before getting shot, it is game over:

Now you know what we will be creating. Hence, you can decide whether or not you want to follow along with our progress moving on. However, we need to point out that we will not be dealing with the frontend of the above-presented game. By using Phaser, we will use an existing Web2 game as a boilerplate and then just add Web3 backend features.  

Build a 2D Web3 Game with Phaser and Moralis

As mentioned, we will use Phaser, the most popular open-source studio game engine, to find a finished 2D game. Then, we will use the best Web3 backend platform, Moralis, to incorporate the above-presented blockchain functionality. Essentially, we will take a 2D Web2 game and convert it into a 2D Web3 game.

Obtaining an Existing Game from Phaser

So, we start by going to Phaser’s official website. There, we select “Examples” from the top menu. On the next page, we scroll down a bit and click on the “Games” folder. From there, we select the “Bank Panic” game:

Now that we’ve set up our minds on a particular example game, we can use Phaser’s code and assets available on GitHub. Hence, use the “Download” option in the top menu:

On the “Download” page, we get to download Phaser:

Then, click on the “clone” option on the next page to get to Phaser’s GitHub:

There, click on “photonstorm”:

Next, we will select “phaser3-examples” to ensure that the “Bank Panic” game files are included:

Inside “phaser3-examples”, open the “public” folder:

Then, inside the “public” folder, click on the “assets” folder:

Next, open “games” and finally “bank-panic”:

When we look inside the “bank-panic” folder, we see that it contains sounds, images, and other files required for this game to function properly. As such, we have a green light to clone the code. Thus, we go back to the “phaser3-example” page, where we click on “code” and then ”Download ZIP”:

Using VSC to Set Things Up Properly

Note: We use VSC in this example; however, feel free to use your preferred code editor.

We start by creating a React app template. We do this by entering the “npx create-react-app phaser-moralis” command into VSC’s terminal:

Also, keep in mind that “phaser-moralis” is the name we decided to use for our dapp. You can follow our lead or use any name you want. To finally create our React app, enter “yes” next to “Ok to proceed? (y)”. Once that folder is created, we add it to our IDE workspace:

Then, select the “phaser-moralis” folder and click on “Add”:

Now, we unzip the “phaser3-examples-master.zip” file that we downloaded previously. Once unzipped, we navigate to the “bank panic” folder (phaser3-examples-master > public > src > games > bank panic). This is where our example game’s scene files are:

As you can see in the screenshot above, we select all files except the “main.js” file. We move those files into a new “scenes” folder, within our “src” folder inside our React app’s folder (created above):

Now that we’ve transferred our example game’s scene files, we need to do the same for all of the image and sound files. To do this, we have to locate the “bank panic” folder inside “assets” and then “games”. Then, we copy or move the entire folder into the  new “assets” folder inside the “public” folder of our project:

By moving these files, we are essentially integrating Phaser’s example game into our ReactJS application.  Next, we navigate into the “phaser-moralis” folder by entering the “cd phaser-moralis” command in VSC’s terminal.

2D Web3 Game Code Walkthrough – Tweaking Phaser Files

All of you who want to access the finished code of our 2D Web3 game, you can do so on GitHub. Though, we recommend following along with our steps and making the necessary tweaks to get the most out of this article. We start by changing the title inside the “index.html” file from “React App” to “Phase x React x Moralis”:

Then, change “.js” extensions into “.jsx” extensions for “App.js” and for “index.js”:

Next, we tweak the “index.jsx” file by adding a container to which our canvas element will attach to. Above the “<App />” line, we add the following:

<div id= “game-container”></div>

Moreover, we wrap the above container around the “App” component:

Then, we open the “App.jsx” file, where we first import our Phaser files at the top:

This is also our cue to install Phaser by entering “npm i phaser” into VSC’s terminal. Next, still inside the “App.jsx” file, we initiate our “game” variable using “let game = null;”. Then, we need to add some additional imports and tweak the “App()” function. This is also where we add the following “config” object, through which our Phaser game gets initiated:

  if (!loaded) {
    setLoaded(true);
    const config = {
      type: Phaser.AUTO,
      //gameTitle: "Phaser x Moralis",
      parent: "game-container",
      autoCenter: Phaser.Scale.CENTER_HORIZONTALLY,
      autoFocus: true,
      fps: {
        target: 60,
      },
      physics: {
        default: "arcade",
        arcade: {
          gravity: { y: 200 },
          debug: false,
        },
      },
      backgroundColor: "#282c34",
      scale: {
        mode: Phaser.Scale.ScaleModes.NONE,
      },
      scene: [Boot, Preloader, MainMenu, MainGame],
    };
    // init 2d game (Phaser canvas element)
    if (game === null) {
      // init instance of phaser game as per config
      game = new Phaser.Game(config);
      // listen to in-game events
      // before starting we sign in with wallet
      game.events.on("LOGIN_PLAYER", (event) => {
        console.log("⛓⛓⛓ Login via Web3 Wallet ⛓⛓⛓");
        // trigger wallet authentication
        login();
      });
    }

Importing Phaser

For the above code to function, we also need to import Phaser in our scene files (“Boot.js”, “Door.js”, “Game.js”, “MainMenu.js”, and “Preloader.js”) using the ‘import phaser from “phaser”;’ line. Moreover, we also need to assign the initial values inside the “Game.js” file:

Furthermore, we need to change some file paths inside the “Preloader.js” and “Boot.js” files. Inside the former,  we change the “assets/game/bank-panic/” value inside “this.load.setPath” to “assets/bank-panic/”. Moreover, inside the “Boot.js”, we change “assets/game/bank-panic/loading.png” to “assets/bank-panic/loading.png”.

Going From 2D Web2 Game to 2D Web3 Game with Moralis 

With all of the above tweaks applied, we have a functioning 2D game available. However, it currently has nothing to do with Web3. Fortunately, we can use Moralis to include all sorts of Web3 features seamlessly. Though, for this example project, we will focus on adding Web3 authentication.

We start by importing React Moralis with the “npm i react-moralis” command in VSC’s terminal. Then, we revisit the “index.jsx” file, where we import “react-moralis” with the ‘import { MoralisProvider } from “react-moralis”;’ line. Next, we add a standard “Application” function (video below at 12:05). The latter serves as a standard login to our Moralis server. To make that work, we also create a new “.env” file (12:52), where we add our Moralis server’s details:

The next task is to obtain our Moralis server’s details. If you’re new to Moralis, here are the steps to get the details (13:15):

  • Log in to your Moralis account or create your free Moralis account.
  • Create a Moralis server.
  • Access the server’s details and copy them.
  • Paste the server’s details (server URL and app ID) into the “.env” file.

Moving forward, we made some small tweaks to the “index.jsx” file (14:10). Then, we add React-Moralis functions in “App.jsx” (14:36), which gives us the power of Moralis’ SDK. As such, we easily cover authentication with MetaMask. Finally, we include Redux for dispatching events from our 2D Web3 game to our React hooks and vice versa (15:13). 

Note: Make sure to watch the video below and watch closely to get all the steps right.

https://www.youtube.com/watch?v=Z4dWavvyhbA

How to Build a 2D Web3 Game – Summary

At this point, you should have your own 2D Web3 game functioning properly. Using Phaser, MetaMask, and Moralis, you’ve been able to do that in less than thirty minutes. Along the way, you’ve learned how to use Phaser’s example games. Moreover, you’ve learned how to complete the initial Moralis setup and then use it to include Web3 functionality. As such, you can now use these skills to create your own 2D Web3 games. However, you may not yet be confident enough to start your own projects. Thus, taking on other example projects may be the right direction for you. On the other hand, you may want to explore other blockchain development topics.  

  This story was originally published at https://moralis.io/how-to-build-a-2d-web3-game-full-guide%ef%bf%bc/ 

#web3 #web3 

Best of Crypto

Best of Crypto

1657182720

How to Create Transaction with Web3.js

Abstract

The demo code provides developers with an overview of how to sign, send, and receive receipt of transactions, and verify the results of their execution. The sample also provides the event monitoring code so that the developer can understand how to listen to an event one or more times.

Getting Started

Understanding The Functions of the Smart Contract

  • Constructor: The constructor function of the smart contract, which is called when the contract is deploying, at the same time it will initialize the number to _initialNumber;
  • increment: The function of incrementing the number by given _value;
  • rest: The function of resetting the number to 0;
  • getNumber: The function of getting the number.

How to run it

  1. Install dependencies: npm install
  2. Copy the configuration file: cp .env.example .env
  3. Edit the configuration file: vim .env, copy your project ID and private key to the .env file.
PRIVATE_KEY=YOUR_PRIVATE_KEY
INFURA_ID=YOUR_PROJECT_ID

4.   Run the index.js file: node index.js

Interpret Source Code

compile.js

You can't use .sol files directly, you need to compile it to binary file firstly.

Load the smart contract file Incrementer.sol into source variable.

// Load contract
const source = fs.readFileSync("Incrementer.sol", "utf8");

Compile the smart contract file

const input = {
  language: "Solidity",
  sources: {
    "Incrementer.sol": {
      content: source,
    },
  },
  settings: {
    outputSelection: {
      "*": {
        "*": ["*"],
      },
    },
  },
};

const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));

| Note: The version of solidity in this task is 0.8.0, different versions may have different compile ways.

Get the Contract Object

const contractFile = tempFile.contracts["Incrementer.sol"]["Incrementer"];

Export contractFile Object

If you want to use the contractFile object in other js files, you need to export it.

module.exports = contractFile;

index.js

1. Load the Incrementer smart contract from compile file

const contractOfIncrementer = require("./compile");

2. Read private key from environment variables

For security’s sake, the private key is not hard-coded, but it can be read as environment variables. When run this task, the dotenv plugin will automatically read the configurations in the .env file and load them as environment variables, and then you can use the private key and other environment variables via process.env.

require("dotenv").config();
const privatekey = process.env.PRIVATE_KEY;

3. Create the web3 instance

web3 is the main API of the web3js library. It is used to interact with the blockchain.

// Provider
const providerRPC = {
  development: "https://kovan.infura.io/v3/" + process.env.INFURA_ID,
  moonbase: "https://rpc.testnet.moonbeam.network",
};
const web3 = new Web3(providerRPC.development); //Change to correct network

| Note: The INFURA_ID is the PROJECT ID of the Infura project you created in last task

4. Get the account address

On blockchain, each user has a address, which is unique for others, and you can get the address by the private key. In this task, you can use the we3.eth.accounts.privateKeyToAccount API to get your account address by passing the private key as a parameter.

const account = web3.eth.accounts.privateKeyToAccount(privatekey);
const account_from = {
  privateKey: privatekey,
  accountAddress: account.address,
};

5. Get the bytecode and abi

When deploying the smart contract, you need to specify the bytecode and abi of the smart contract. The bytecode is the compiled binary code of the smart contract, and the abi (Application Binary Interface) is the interface of the smart contract.

const bytecode = contractOfIncrementer.evm.bytecode.object;
const abi = contractOfIncrementer.abi;

6. Get contract instance

In the last step, you got the bytecode and abi, so you can create the contract instance by the abi.

// Create contract instance
  const deployContract = new web3.eth.Contract(abi);

7. Create the transaction of the deployContract

// Create Tx
const deployTx = deployContract.deploy({
    data: bytecode,
    arguments: [5],
});

8. Sign the transaction

Use your private key to sign the transaction.

// Sign Tx
const deployTransaction = await web3.eth.accounts.signTransaction(
    {
        data: deployTx.encodeABI(),
        gas: 8000000,
    },
    account_from.privateKey
);

9. Send the transaction / Deploy your smart contract

Send your deploy transaction to the blockchain. You will receive a receipt, and get this contract address from the receipt.

const deployReceipt = await web3.eth.sendSignedTransaction(
    deployTransaction.rawTransaction
);
console.log(`Contract deployed at address: ${deployReceipt.contractAddress}`);

10. Load the contract instance from blockchain through above address

In previous steps, you built a contract instance, and then deployed the transaction by sending the contract to the blockchain so that you can operate the transaction later. Besides, you could also load a contract instance that is already on the blockchain so that you can operate it directly and avoid the process of deploying it.

let incrementer = new web3.eth.Contract(abi, deployReceipt.contractAddress);

11. Use the view function of a contract

Whether a contract instance is create by deploying, or by loading, you can interact with the contract once you have an instance of the contract already on the blockchain.
There are two types of contract functions: view and without view. The functions with view promise not to modify the state, while the functions without view will generate the corresponding block data on the blockchain. For example, after calling the getNumber function of the contract, you will get the public variable number of the contract, and this operation will not charge any gas.

let number = await incrementer.methods.getNumber().call();

12. Build a transaction

Before you send the transaction to the blockchain, you need to build the transaction, it means you need to specify the parameters of the transaction.

let incrementTx = incrementer.methods.increment(_value);

// Sign with Pk
let incrementTransaction = await web3.eth.accounts.signTransaction(
  {
    to: createReceipt.contractAddress,
    data: incrementTx.encodeABI(),
    gas: 8000000,
  },
  account_from.privateKey
);

13. Send the transaction and get the receipt

You can use sendSignedTransaction function to send above transaction to the blockchain, and got the receipt to check result.

const incrementReceipt = await web3.eth.sendSignedTransaction(
  incrementTransaction.rawTransaction
);

Listen to Event Increment

When invoking the interfaces of the contract, the only way to get information about the processing details, apart from the results returned by the interface, is through events.
In the interfaces, you retrieve the corresponding internal information by triggering an event, and then capturing this event generated by the external block.

const web3Socket = new Web3(
new Web3.providers.WebsocketProvider(
    'wss://kovan.infura.io/ws/v3/' + process.env.INFURA_ID
));
incrementer = new web3Socket.eth.Contract(abi, createReceipt.contractAddress);

| kovan don't support http protocol to event listen, need to use websocket. More details , please refer to this blog

Listen to Increment event only once

incrementer.once('Increment', (error, event) => {
    console.log('I am a onetime event listener, I am going to die now');
});

Listen to Increment event continuously

incrementer.events.Increment(() => {
    console.log("I am a longlive event listener, I get a event now");
});

References

Link: https://github.com/Dapp-Learning-DAO/Dapp-Learning/tree/main/basic/02-web3js-transaction

#solidity #blockchain #smartcontract #web3 #web3.js