# Welcome to Meter!

Meter is DeFi infrastructure with a built-in, crypto-native, metastable currency, MTR.  It uses HotStuff based PoS consensus with MTRG (Meter Governance Token) to manage the blockchain ledger.  Meter functions as a highly-decentralized, high-performance side chain for Ethereum and other public chains.

We are working to achieve three things with Meter’s DeFi infrastructure:&#x20;

1. Complete Bitcoin’s original vision and create a metastable sound money independent of the fiat system.&#x20;
2. Address performance issues that current chains are facing with our Hybrid PoW/PoS + HotStuff consensus that is backward compatible with Ethereum.&#x20;
3. Interconnect with other public chains like ETH and run as a side chain to enable scaling and value interaction.

Please read on to learn more!


# Introduction to Meter

## What is Meter?

Meter is a DeFi infrastructure with a built-in, crypto-native, metastable currency.  It functions as a highly-decentralized, high-performance EVM compatible side chain for Ethereum and other public chains.

The Meter system uses Proof of Work to create a fully-decentralized, low-volatility coin MTR for fees and payments, and HotStuff-based Proof of Stake with the MTRG governance coin to validate transactions.

This hybrid consensus mechanism makes Meter fast - the system can process thousands of transactions per second, reaching finality almost instantly - and super secure.&#x20;

DeFi app developers can also use our highly-decentralized, HotStuff-consensus PoS chain as an EVM-compatible side chain to increase the speed and scalability of decentralized exchanges, derivative trading platforms, yield farming programs, and other DeFi apps.&#x20;

## What problems does Meter solve?

Meter solves two major problems:

1. The lack of a stable, decentralized unit of account representing an established value for DeFi applications. Basically, native cryptocurrencies are too volatile to be used for frequent transactions, and stablecoins are either centralized, have limited capacity, or depend on oracles.
2. Issues with scaling and interoperability of currently available blockchains. There is a need for a high-performance blockchain that is EVM-compatible but interoperable between other blockchains to help scale and move value between them.

## How can Meter be used?

Meter can be used in a number of ways.

### DeFi infrastructure

Meter was built from the ground up to enable DeFi. DeFi apps like decentralized exchanges, synthetic asset platforms, lending applications, and many others can be built on top of Meter to leverage its fast, decentralized network.&#x20;

And with Meter's EVM compatibility and future interoperability with Polkadot, Cosmos and many other public blockchains, Meter can be used as a side chain to help scale and enable value interaction acros.&#x20;

### Everyday payments

Meter can be used for everyday purchases and payments, such as for your cup of coffee, a new shirt, or payments to friends and family across the world.

### Store of value

While governments are devaluing their currencies with continuous printing, Meter maintains its long-term value by being pegged to 10 kWh of electricity, one of the most stable resources in the world.&#x20;


# Hybrid PoV Consensus Mechanism

## Overview of Proof-of-Value Consensus Mechanism

The Meter network employs an innovative Proof of Value (PoV) consensus mechanism, a hybrid of Proof of Work (PoW) and Proof of Stake (PoS).

The Meter system consists of two tokens:

1. MTR, the low-volatility meta-stable token created by PoW miners.
2. MTRG, the governance token used by PoS validators in a HotStuff 2 BFT style consensus to validate transactions.

Unlike traditional cryptocurrencies, the Meter protocol separates the economic consensus from the record-keeping consesuses. The economic consensus determines how much new value will be added to the economy whereas the record-keeping consesus prevents double spending. In the Meter system MTR represents the economic consesus while MTRG represents the record-keeping consensus.

This division of work mirrors the physical world where miners extract gold or silver from the Earth while bankers maintain the financial system. Miners and validators collaborate to make the Meter system more stable, secure, and scalable.

## Why is Proof of Value better than Proof of Work and Proof of Stake?

Most existing blockchains mix currency creation with record keeping despite them being fundamentally two separate consensuses.

The advantages of separating the two are as follows:

1. PoW mining of MTR consumes less energy due to the economic game design
2. Transactions are processed extremely quickly with instant finality.
3. Traditional problems with PoS such as long-range attacks and the 'rich-get-richer' problem can be avoided.

The hybrid consensus mechanism makes Meter extremely secure. In order to attack the Meter network, you would be required to pass the sybil resistance for both PoW and PoS. Since transactions settle instantly in our system it is more secure than Bitcoin or Ethereum where transaction rollback problems exist.

More details about Proof of Value can be found here:

{% embed url="<https://medium.com/meter-io/what-is-proof-of-value-consensus-meter-c47f989065fa>" %}

## What is the difference between HotStuff consensus and Tendermint or Capser FFG

[HotStuff consensus](https://arxiv.org/abs/1803.05069) is a variant of Byzantine fault-tolerant (BFT) consensus protocol proposed and mathematically proven by [Ted Yin](https://www.cs.cornell.edu/~tedyin/) during his internship at VMware Research in 2018. Compared to the traditional pBFT consensus proposed in the 1970s HotStuff has the following benefits:

1. Simple and elegant leader change (censorship and network failure resistance). In traditional pBFT consensus like Tendermint if the leader (block proposer) fails or becomes malicious the system will not be able to reach consensus and finalize blocks. Changing leader is extremely complicated and communication intensive. Most implementations have had to change certain assumptions to avoid dealing with leader change. In Tendermint, for example, the developer assumed that the network has strong synchrony (meaning all the nodes share the same well-synced global clock). If a leader fails to reach consensus within the time slot all the validator nodes will move to the next round. HotStuff-based BFT has a built-in leader change algorithm. The complexity of changing the leader is the same as that of creating a regular block. One of the advantages of HotStuff consensus is that it doesn't rely on the synchronized global clock. It assumes the network is partially synchronous, meaning the network may be jammed or partitioned from time to time, but will eventually become synchronized. This brings the tremendous benefit of preventing malicious nodes and censorship in the network. ETH 2's Casper FFG is a variant of BFT consensus with a partially synchronous network assumption with the help of the VRF random beacon. This however requires a different trade off of liveness and consistency. In ETH2 the system continuously generates new blocks even though there are not enough validators to reach a 2/3 majority and finalize the block (the blocks then become unusable as they could be reverted in the future). In Meter's PoV we use PoW to create a source of randomness, while the HotStuff consensus halts committing new blocks if 2/3s majority is not reached. This is much more desirable behavior for financial applications.
2. Higher performance than pBFT, HotStuff consensus is designed as a pipeline consensus. This means the system processes two or three blocks at the same time. Since HotStuff doesn't have to run a synchronous mode it is able to reach consensus as quickly as the network speed allows. Therefore the block period can be much shorter than pBFT and be variable based on the network on the node status. Meter limits the smallest the block period to be 1.5 seconds, with the typical block period being 1.9 to 2 seconds. The throughput potential is 9\~10 times that of Tendermint. A more technical comparison of HotStuff, Capser FFG and Tendermint can be found at the following Link:

{% embed url="<https://dahliamalkhi.github.io/posts/2018/03/bft-lens-casper/>" %}

{% embed url="<https://dahliamalkhi.github.io/posts/2018/04/BFT-lens-tndrmnt/>" %}

{% embed url="<https://decentralizedthoughts.github.io/2023-04-01-hotstuff-2/>" %}

3\. Less communication and lower data storage requirements.  The pipeline implementation and BLS signature aggregation we used in Meter's HotStuff consensus means Meter's consensus message is o(n) in complexity compared to the o(n^2) complexity in Tendermint. This means the communication required in the current 125 committee nodes configuration in Tendermint Meter could run 15,625 nodes - an increase of over 12,000%. Using Meter's current transaction volume the block database is expected to grow at a rate of 1\~2GB/month.


# MTR - The Metastable Coin

## What is MTR?

Meter Stable (MTR) is the unit of account and medium of exchange for the Meter network. It is a fully-decentralized, permissionless, low-volatility cryptocurrency that is created using SHA256 Proof of Work, the same method used by Bitcoin.

Meter uses the cost of production and the PoW miners’ arbitraging behavior to establish a long-term equilibrium price for the market. This equilibrium price anchors MTR to the competitive global electricity price which is more stable in value than any fiat currency based on historical data. Between 1960 and 2021 electricity prices went up 6.3x when measured in USD, but stayed the same after adjusting for inflation.

![US Electricity Price Measured by USD vs Adjust for Inflations](/files/-MNH_wGBssLxawWGb1Qw)

The supply of MTR is uncapped. When demand is higher miners will expand the supply whereas when demand is lower the internal MTRG auction process wil continually remove MTR from circulation, reducing supply. This makes the value of MTR neither deflationary nor inflationary.

## What is MTR used for?

Externally MTR can be used to make everyday payments and as a store of value.

On the Meter network MTR is used for transaction payments, gas, and storage fees PoS validators receive for approving transactions.

MTR may also be converted to MTRG through a competitive bidding process. In Bitcoin the miners use their hash power to directly compete for the newly created Bitcoins. In Meter the miners first convert their hash power into mining credits (MTR) and then use the MTR to compete for MTRG. Please refer to the "[On-Chain Auctions](/overview-of-meter/on-chain-auctions)” section for more information.

## How is Meter different than other stablecoins?

Meter solves many of the issues that existing stablecoins face.

Fiat-backed stablecoins like USDT and USDC are centralized and are thus subject to regulatory restrictions, while crypto-backed stablecoins like DAI face capacity challenges.

The cryptocurrencies used as collateral may only be a small percentage of circulating supply in order to avoid avalanche crashes during liquidation scenarios. They must also rely on oracles which are typically centralized since there are limited sources of high quality data. If the oracle provides wrong data something as simple as a software/hardware glitch could cause the entire financial system to fail. This is a far too systemic risk for the most fundamental building blocks of a financial system.

Meter's true decentralization and permissionless nature is designed to avoid such systemic risks. By giving up the USD peg MTR maintains long term purchasing power and stable value. This also eliminates counter-party, regulatory, and oracle risks typically found in crypto and fiat-backed stablecoins.

Read more[ here](https://medium.com/meter-io/meter-why-we-are-different-7cd94ea6eead).

## How does MTR maintain stability?

Each MTR is created with 10 kWh of electricity using SHA256 Proof of Work, the same method as BTC.

Miners’ profit chasing behavior ties the cost of global competitive electricity price to the value of MTR. This creates more stable purchasing power than any fiat currency in the world. When the price of MTR goes up profit-driven miners will allocate more of their mining equipment to mine MTR; when the price of MTR decreases they will point their mining equipment to other PoW chains.

The miners actions cause the Meter block reward to elastically change in response which brings the price of MTR back to its' state of competitive equilibrium.

In Bitcoin miners use hash power to bid on newly created BTC. The block reward is constant, but the price is not. In Meter miners convert their hash power to mine MTR, where the price is constant but block rewards are variable based on total network hash power.

We expect the long term sustainable market equilibrium to be in the 0.6 to 1.25 USD range for MTR to be continuously created. Once the MTRG on-chain auction starts even if the price of MTR drops the auction consumptions will remove any surplus MTR from circulation and bring the price back to the sustainable range. The stability of the system is ever increasing as it grows.

Meter has a [reserve mechanism](/overview-of-meter/the-meter-reserve) to account for larger price fluctuations.


# MTRG - Meter Governance Coin

## What is MTRG and what is it used for?

MTRG is the governance token of the Meter system. Holders of MTRG can perform the following actions:

1. Stake MTRG tokens directly as a PoS validator or delegate to other PoS validators to approve transactions and earn MTR.
2. Earn various fees paid in MTR from the [on-chain auction](/overview-of-meter/on-chain-auctions) and on-chain/cross-chain transactions.
3. Stake MTRG tokens in future DeFi apps created by the Meter team.
4. Participate in governance of the Meter system.

MTRG holders will be able to vote on major changes to monetary policy, MTR production parameters, new feature additions, and other governance-related issues.&#x20;


# On-Chain Auctions

One of the most important uses of the MTR token is to obtain MTRG to participate in safeguarding, governance, and growth of the Meter system.&#x20;

This is done via on-chain auctions that are automatically generated by the Meter system every 24 epochs (roughly 24 hours), as shown below. The only way to participate in these auctions is to use MTR as the bidding currency. <br>

![Meter’s On-Chain Auction](https://lh6.googleusercontent.com/xdpa7KQAPyugvHA8QFDHRpyUjNoZUPr4oaW2NzZAKKkTy5RVNw19yT4r8CdKxtX0av_mQaggqZuO2e6xLSw8IgwLMcZevePdAo--aovUCdDdDfpbSUQTEugk_KYMDUNn2J70gOyT)

Participants bid MTR to acquire MTRG with no specific bidding price. However the Meter wallet provides an interface to show how many MTRs are received and the amount of MTRG offered for the current auctions. At the end of the 24th epoch, all participants acquire MTRG at the same price and the next auction begins. The majority of the MTR tokens from the proceeds of the auction will be put into the Meter reserve pool (see below section for more information about the reserve). The rest of the MTR tokens will be distributed to the validators as block rewards. &#x20;

The auction settlement price will be equal to Total MTR received / Total MTRG offered for auction. The total number of MTRG offered for auction is capped by the supply curve and then further reduced by the weighted average of the settlement price for the past 30 on-chain auctions.  If the average price is higher, more MTRG will be offered in the auction (but can not exceed the cap) and vice versa.&#x20;

There will also be a reserve price of 0.5 MTR / MTRG at launch. If the calculated auction settlement price is lower than the reserve price, the auction will settle at the reserve price. Any unsold MTRG tokens will be saved in a special foundation reserve account for future protocol and ecosystem development. The community can decide how to use these tokens, choose to change or remove the reserve price, and adjust the amount of MTRG distributed through auction via the governance process.&#x20;


# The Meter Reserve

The Meter protocol does not have a centralized government but retains the concept of possessing a reserve to absorb any significant shocks to MTR’s price stability.&#x20;

At launch, 100% of the proceeds collected from the on-chain auctions (in MTRs) gradually go to validators as block rewards in the next 24 epochs.  However a portion of the proceeds can be put into a system reserve. The MTRs that are put into the reserve are temporarily removed from circulation. This reserve allocation ratio is a parameter that can be adjusted via the Meter governance process.

&#x20;


# Meter's Ethereum Emulation Mode

In order to better support Ethereum developers, we introduced a full Ethereum emulation mode on Meter.  One could think it as Apple M1 running x86 applications.  Meter's nodes will emulate the runtime environment for Ethereum transactions and smart contracts.  The nodes also supports the Ethereum RPC interface.  Ethereum toolchains, applications and wallets will treat Meter network as one of the Ethereum testnets.  Almost all the Ethereum applications could run Meter with almost no modifications.  &#x20;


# Interacting with Meter Mainnet Using MetaMask

Meter mainnet now supports two transactions (tx) formats:&#x20;

1. The native Meter tx: which is more expansive and supports staking, on-chain auctions, validator transactions, and future multiple chains/shards. This tx format is used by the Meter mainnet wallet which is a PC/Mac application [downloadable](https://www.meter.io/wallets/) from the Meter website or [Github](https://github.com/meterio/meter-wallet).&#x20;
2. Ethereum tx: This is designed for backward compatibility with existing Ethereum dApps and ecosystem including wallets like [Metamask](https://metamask.io/).

Metamask communicates with the Meter mainnet through an RPC (Remote Procedure Call) emulation layer.  The user will have to configure a custom RPC network inside MetaMask. Here is how to do so.

## Setup Meter Network in MetaMask with Wallet.meter.io

{% embed url="<https://youtu.be/SKH4PTJtX0A>" %}

## Setup Meter Network in MetaMask with **Chainlist.org**

{% embed url="<https://youtu.be/RGJ9cJHZ_j8>" %}

## Setup Meter Network in MetaMask **manually**

**For the browser plugin version of Metamask:**

The easiest way to configure Metamask for your browser extension is to select Meter Network from "Support Networks" in the [Meter Passport Wallet](https://wallet.meter.io).

If you are configuring manually, there following are the details:

1. Select the network drop-down menu, and then click on the 'Add Network' at the bottom.

<figure><img src="/files/iL1g9RvyBG9FL765P2n4" alt=""><figcaption></figcaption></figure>

2\. Enter the following information for the Custom Network and click "Save":

<figure><img src="/files/hQBjwq35yFNXWh1q6gu2" alt=""><figcaption></figcaption></figure>

If you are using the mobile app version of Metamask, new Network settings can be added through the Network dropdown --> 'Add Network' --> 'Custom Network'

![](/files/5aapTPp3os6Frm6IK4S4)![](/files/isBhLprDS1wsmrumFM4u)

## Network Information:

**Network Name:** Meter Mainnet

**RPC URL:**&#x20;

&#x20;   <https://rpc.meter.io> or&#x20;

&#x20;   <https://meter.blockpi.network/v1/rpc/public> (maintained by [public.blockpi.io](https://public.blockpi.io/))

**Chain ID:** 82

**Symbol:** MTR

**Block Explorer URL:** <https://scan.meter.io>&#x20;

**MTRG can be treated as a custom ERC20 token:**

-MTRG: [0x228ebBeE999c6a7ad74A6130E81b12f9Fe237Ba3](https://scan.meter.io/address/0x228ebbee999c6a7ad74a6130e81b12f9fe237ba3)

## Setup Meter Desktop Wallet Account in MetaMask

{% embed url="<https://youtu.be/11ZjtEpiF0U>" %}


# Interacting with Meter Mainnet Using Ledger

## **Introduction**

Hardware wallets provide a safer way to store crypto assets due to their ability to manage the private key (used for signing transactions) offline. They provide an additional layer of security against the risks of compromised private keys (phishing attacks) or malicious smart contracts frequently experienced by users relying on web wallets for safety of their assets.

***Note:** The assets are always stored on the blockchain and not on the hardware wallet.*

Ledger offers three hardware wallet solutions at the time of writing: Ledger Nano S, Ledger Nano S Plus and Ledger Nano X.

You can interact with Meter using your Ledger hardware wallet through the Meter Ledger Live app. Meter Network is also supported through the Ethereum App on Ledger Live. The difference in using the applications is outlined below;

| Meter App on Ledger Live                                                           | Ethereum App on Ledger Live                                             |
| ---------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| Dedicated application, always connected to the right network                       | Need to confirm chain ID (Meter Chain ID: 82) for every transaction     |
| Specific to Meter Network, cannot be used across other Networks setup on Meter SDK | Generic, can be used across other Networks in addition to Meter Network |

In this tutorial, you will learn how to get started with your Ledger hardware wallet on Meter Network using the Meter app. These steps are applicable across all 3 devices (Ledger Nano X,  Ledger Nano S and Ledger Nano S Plus).

## **Supported Assets**

As the Meter App is supported through third party service (MetaMask), all assets available on Meter Network are currently supported.

MTRG can be added as a custom ERC20 token:

-MTRG: 0x228ebBeE999c6a7ad74A6130E81b12f9Fe237Ba3

The native assets - MTR and MTRG - are not currently available on Ledger Live.

## **Prerequisites**

Before you get started, update [Ledger Live](https://www.ledger.com/ledger-live/download) to the latest version available. Also, make sure you've your Ledger hardware wallet device running the latest firmware. The Ledger support website offers tutorials on how to update the firmware of [Ledger Nano S](https://support.ledger.com/hc/en-us/articles/360002731113-Update-Ledger-Nano-S-firmware), [Ledger Nano S Plus](https://support.ledger.com/hc/en-us/articles/4445777839901-Update-Ledger-Nano-S-Plus-firmware?docs=true) and [Ledger Nano X](https://support.ledger.com/hc/en-us/articles/360013349800-Update-Ledger-Nano-X-firmware) devices.

At the time of writing, the following versions were used:

* [Ledger Live 2.46.2](https://support.ledger.com/hc/en-us/articles/360020773319-What-s-new-in-Ledger-Live-?docs=true)
* [Ledger Nano S firmware v2.1.0](https://support.ledger.com/hc/en-us/articles/360010446000-Ledger-Nano-S-firmware-release-notes?docs=true)
* [Ledger Nano S Plus firmware v1.0.3](https://support.ledger.com/hc/en-us/articles/4494540771997-Ledger-Nano-S-Plus-Firmware-Release-Notes?docs=true)
* [Ledger Nano X firmware v2.0.2](https://support.ledger.com/hc/en-us/articles/360014980580-Ledger-Nano-X-firmware-release-notes?docs=true)

In addition, you'll need MetaMask as an intermediary between your Ledger device and Meter. Make sure that your MetaMask is [connected to Meter](https://docs.meter.io/wallet-setup/interacting-with-meter-mainnet-using-metamask). As of [MetaMask version 10.5.0](https://consensys.net/blog/metamask/metamask-and-ledger-integration-fixed/), connecting your Ledger device with MetaMask on Chrome is easy again. You just need to have the latest version of MetaMask installed.

## **Install the Meter Ledger Live App**

The Meter app is dependent on the Ethereum app, so first you will need to install the Ethereum app. Once the Ethereum app is installed you will be able to install the Meter app without a problem. Please note that the Meter app is only for the Meter network.

**Video Tutorial:**

{% embed url="<https://youtu.be/68VhSfb6FyE>" %}

**Step-by-Step Guide:**

To get started, open up Ledger Live and:

1. Select **'My Ledger'** from the menu
2. Connect and unlock your device (this must be done before installation)
3. In the **App catalog** search for Ethereum (ETH) and click **Install**. Your Ledger device will show **Processing** and once the installation is complete, the app will appear on your Ledger device
4. Search for Meter (MTR) in the **App catalog** and click **Install**. Again, your Ledger device will show **Processing** and once complete, the Meter app will appear on your Ledger device

In the Ledger Live app, you should see the Ethereum and Meter app listed under the **Apps installed** tab on the **'My Ledger'** page. After the apps have been successfully installed, you can close out of Ledger Live.

## **Import your Ledger Account to MetaMask**

Now that you've installed the Ledger Live apps, you can connect your Ledger to the computer, unlock it, and open the Meter app.

Then import your Ledger account to MetaMask as shown below;

{% embed url="<https://youtu.be/VO453rD6IyU>" %}

If you're using Chrome or a Chrome-based browser like Brave, you'll be prompted to select your Ledger device to via a pop-up to connect via WebHID. If a pop-up doesn't appear, you may need to change your MetaMask settings to enable a WebHID connection. You can check and update your MetaMask settings by following these steps:

1. Expand the top-right menu and go to **Settings**
2. Navigate to **Advanced**
3. Scroll down to **Preferred Ledger Connection Type** and select **WebHID** from the dropdown

***Note:** The Preferred Ledger Connection Type setting is only available on Chrome and Chrome-based browsers. This setting doesn't exist on other browsers such as Firefox.*

If MetaMask was able to connect successfully to your Ledger device, you should see a list of five Meter/Ethereum-styled accounts. If not, double-check that Ledger Live is closed, you've connected your Ledger device to the computer, unlocked it, and have the Meter app open.

## **View Balances**

If you've imported your Ledger account successfully, you should see your account and balance displayed in the main MetaMask screen

You can switch accounts in MetaMask at any time to view the balance of your other imported Ledger accounts.

## **Receive Tokens**

To get started interacting with your Ledger device, you will need to send some funds to it. Copy your address from MetaMask by clicking on your account name and address in MetaMask.

Next, you will need to obtain some MTR tokens and using the address you just copied, send the tokens to your account. After the transaction has successfully gone through, you will see your balance update.

{% embed url="<https://youtu.be/KyjeDCMHYMM>" %}

***Note:** You can receive both native tokens - MTR and MTRG from different sources (CEX, Address)*

## **Send Tokens**

***Note:** You need MTR tokens as gas currency for Meter Mainnet to send any assets. You can perform* [*gasless swap*](https://wallet.meter.io/swap) *if you have MTRG tokens available in your wallet.*

Next up is sending and signing transactions on Meter using your Ledger device.&#x20;

{% embed url="<https://youtu.be/yL3RrArPxho>" %}

Here are the steps to review on your ledger device:

1. Click the button to proceed to the next screen. Your Ledger device is only warning you to review the transaction
2. Check the number of tokens being sent then proceed to the next screen
3. Check the recipient's address and proceed to the next screen
4. Check the max fees applicable to this transaction. This is the gas price multiplied by the gas limit you've set on MetaMask. When ready, proceed to the next screen
5. If you agree with all the transaction details, approve it. This will sign the transaction and will trigger MetaMask to send it. If you don't agree with all the transaction details, reject it. This will cancel the transaction, and MetaMask will mark it as failed

Right after you've approved the transaction, MetaMask sends it to the network. Once the transaction is confirmed, it will be displayed as **Send** on the **Activity tab** in MetaMask.

And that is it! You've signed a transaction and sent some MTR tokens using your Ledger hardware wallet!

## **Interact with Contracts Using your Ledger**

By default, Ledger devices don't admit a data field in the transaction object. Consequently, users can't deploy or interact with smart contracts.

However, if you want to use your Ledger hardware wallet for transactions related to smart contracts, you need to change a configuration parameter inside the app on your device. To do so, take the following steps:

1. On your Ledger, open the Meter or Ethereum app
2. Navigate to **Settings**
3. Find the **Blind signing** page. It should state **NOT Enabled** at the bottom
4. Select/validate the option to change its value to **Enabled**

***Note:** This option is necessary to use your Ledger device to interact with ERC-20 token contracts that might live inside the Meter ecosystem.*

## **Support**

Users can reach out on [Telegram](https://t.me/Meter_IO), [Twitter](https://twitter.com/Meter_IO) or [Discord](https://discord.gg/WPjTpMG) for immediate support related to ledger integration. You can also reach out to us via email at <info@meter.io>.


# Adding Custom Tokens to MetaMask

## Native Tokens

In Meter, both MTR and MTRG are native network coins. However, Metamask can only display one native coin (ETH in Ethereum's case). We configured the gas token MTR to replace the default ETH in the wallet.&#x20;

To properly display and transact MTRG, we created ERC-20 wrappers for MTRG and MTR so MetaMask and dApps could treat them as ERC-20 tokens as well.&#x20;

MTRG can be treated as a custom ERC20 token in Metamask:

*ERC20 System Interface:*

**-MTRG: 0x228ebBeE999c6a7ad74A6130E81b12f9Fe237Ba3**

## Popular ERC20 tokens on Meter can be found at:

{% embed url="<https://github.com/meterio/token-list/blob/master/generated/chain-configs/meter.json>" %}

{% embed url="<https://youtu.be/W_uc52uR27s>" %}


# Getting MTR for Gas

MTR is required to pay for gas and transaction fees on the Meter blockchain. &#x20;

Each transfer transaction on Meter requires about 0.0021 MTR and a swap takes around 0.016 to 0.02 MTR.  Here are the ways to get MTR if you don't want to use a centralized exchange:

## MTR airdrop on bridging funds with passport.meter.io

Bridge any assets from other blockchains to Meter through [Meter Passport](https://passport.meter.io).  Each bridge transaction will receive **0.3 MTR** in airdrop.

{% embed url="<https://youtu.be/Jg69rQhLP-w>" %}

## Gasless swap with wallet.meter.io

Use Gasless swap in [Meter Wallet](https://wallet.meter.io/swap).  It runs a transaction relay service that helps to swap MTRG into MTR without using gas (the service pays the gas for you).

{% embed url="<https://youtu.be/OTdcsOSqgAQ>" %}


# Revoking Contract Spend Limits

Users can leverage wallet.meter.io to change contract spend permissions for tokens on Meter Network

{% embed url="<https://youtu.be/4BOlGf4YM5Y>" %}


# Specifying gas (GWEI) for transactions

Meter Network currently uses a fixed gas price of '100 GWEI' for all the transactions.

Changing the GWEI in MetaMask does not impact the processing of the transaction.


# Speeding Up/ Canceling Transactions

Meter does not use gas price to rank the transaction orders.

**Therefore, there is no point to click on the "Speed up" button for the transaction**. &#x20;

Any transactions that are not processed within 320 blocks are automatically canceled in Meter.


# Meter Passport Architecture

***NOTE:** The current version of Meter Passport is V2.0, its security audit is available* [*here*](https://github.com/meterio/Passportv2Contracts/tree/main/audit)*.*

One of Meter's goals is maximizing interoperability with other public blockchains.  Meter Passport is a multi-chain router that enables smart contracts to both transfer assets and communicate across blockchains.

It can transfer native tokens, and tokens in various token standards like ERC20, ERC721, ERC1155 in addition to passing arbitrary generic messages between blockchains.

<figure><img src="https://lh4.googleusercontent.com/B-qCAiDrSm2Qiq3HlLnU-K2iIjF8XbdcUN17VXw5e38icYwVmWuU4F8czihjKLJbYWiUP2mWVNetFfvHp5lZQLHd5ZpzkJMqIR1ARd8k0MQDG_r1-sinSf3tnbLINgMqlt7CQvfncv2tDUfCfre2jmfjmaY2LgtxMZ0LCxCRcbHdsdv6mGch85HjL05R" alt=""><figcaption></figcaption></figure>

The overall Architecture is as follows;

A user transferring tokens from ChainA to ChainB, first deposits the tokens into the bridge contract of ChainA. The contract locks the tokens on ChainA, emitting an event once deposit is successful.

The relayers, off-chain operators of the system, will listen to these events and create a relay transaction to the relay chain. The Relayers will sign the data of the deposit and submit their signatures on the relay chain. Once the threshold is met, one of the relayers or any user can collect all the signatures and send them to Chain B. The smart contract on ChainB will validate again all the signatures and the deposit data and then release the fund on ChainB.

The initial implementation of Meter Passport was further developed on top of Chainsafe's multisig based v2 bridge contract.  Operational wise it is secured by five relayers including **Protofire, Harshquark, Wetez, InfinityStones, and Meter Foundation.** &#x20;


# Salient Features

### Meter Network as Relay Chain

With Meter Passport V2.0, **Meter Network is now used as the relay chain** with a signature collection contract deployed on Meter for the relayers to vote.&#x20;

Compared to other EVM chains, the **instant finality** behavior on Meter Network **makes it an ideal Relay Chain**. Every transaction in the block is 100% finalized, introducing **minimal delay** and ensuring **certainty** to the cross-chain transactions.

### Lower Bridging Cost

The new relay chain design significantly **reduces the operational overhead** for the relayers. They just have to listen to the transactions on multiple networks and send transactions on the Meter network.

Once a proposal passes on the relay chain, only one transaction is needed on the destination chain to complete the bridging process.

### Increased Relayer Uptime

The addition of dual RPC endpoints for the relayers further **increases the Relayer uptime**. Such design allows more Relayers to join the cross chain validation and makes the process more secure and censorship resistant.

### Increased Liveness

As long as there are enough relayers online to sign cross-chain transactions on the relay chain, **anyone could submit the relayers’ signatures directly** on the destination Chain. These will dramatically enhance the liveness and usability of the bridge.

We believe the relay chain voting approach is almost as efficient as the ECDSA threshold signature based approach in terms of gas cost, but provides significantly better liveness, full transparency, and more security to the users.


# Bridge Fee

The bridge fees are used to pay for the transaction cost for the relayers on the destination chain and the relay chain.  They are paid on the source chains' native gas token.

Currently all inbound bridge transactions to Meter Mainnet will receive 0.3 MTR in airdrop.


# Programming Meter Passport

Meter Passport shares the same programming interface as [Sygma (Chainsafe) Bridge.](https://buildwithsygma.com/)

#### Adding ERC20 token support in existing supported chains:

For adding standard ERC20 tokens to Meter Passport, please submit a Pull Request in Meter Passports token repo:&#x20;

{% embed url="<https://github.com/meterio/token-list>" %}
ERC20 Token List Repo
{% endembed %}

ERC20 tokens with special features like transfer tax and burning, please reach out to our team through telegram or discord channel.

#### Generic Message Passing

Meter Passport is the first bridge that supports generic cross chain messaging in production.  [Ampleforth](https://ampleforth.org) team uses Meter Passport for both AMPL token transfers and crosschain rebasing.  Meter Passport is a fork of ChainSafe's Sygma bridge v2.  The generic message-passing interface is the same as the Sygma Bridge.  The details of the generic messaging passing can be found in the Sygma bridge documents.

{% embed url="<https://docs.buildwithsygma.com/architecture/generic>" %}
Sygma Generic Message Passing Docs
{% endembed %}


# Tutorials for Using Meter Passport

A video tutorial on using Meter Passport can be found [here](https://youtu.be/pii65LCFXQ4).

Important Links:

<https://wallet.meter.io>  Managing your assets on different chains

<https://passport.meter.io>  Bridging assets across different chains

The bridge is currently secured by Protofire, Hashquark, InfinityStones, Wetez, and Meter.  3 out of these 5 relayers have to sign off on a transaction to go through.  Typical transfer between BSC, Moonriver, and Meter takes around 10 to 20 seconds, while any transfer that involves Ethereum requires 25 block confirmations for the bridge deposit transaction on the Ethereum side (When the UI shows "In transit") which may take 6 to 10 minutes. &#x20;

The bridge fee exists to support the gas spending and operations for the team of decentralized relayers.  For MoonRiver users, MTRG will be directly airdropped on the MoonRiver network at launch to cover bridge and gas fees on Ethereum.  This is a short-term promotional program funded by the Meter Foundation to help the MoonRiver community building the initial DeFi ecosystem.  The MTRG tokens can be transferred to Meter Mainnet and traded on [VoltSwap](https://voltswap.finance).  Meter also has a standard bridge fee subsidy program that reimburses up to 85% of the bridge fee in MTRG described in the [Bridge Fee Subsidy Program](/passport/bridge-fee-subsidy-program).

Different assets are supported depend on the source and destination chains.  Click “Change” to select the network where you want to bring the tokens from. Then select the token and the amount. Make sure “I want to send funds to my address.” is checked for bridge fee subsidy and airdrops.  Lastly, click on “Start Transfer” to initiate the bridging.

![](/files/-MkEAAKnGj_b-6FpqKgA)

2\) Allow Meter Passport to access the token that you want to bridge and then confirm the bridge transaction (two transactions the first time you send a token include both the approval and the bridge transaction.)

![](/files/-MkIdjLD6rnGbbMYsetc)

![](file:///C:/Users/zhuxh/AppData/Local/Temp/msohtmlclip1/01/clip_image006.jpg)![](file:///C:/Users/zhuxh/AppData/Local/Temp/msohtmlclip1/01/clip_image008.gif)

![](/files/-MkIcBRPnUvtYJAUbF8N)

3\) Now that your tokens have been bridged (transferred) to the destination.  If you are bridging into Meter should automatically receive 0.3 MTR airdrop in your wallet whenever you bridge an asset into Meter.  You could use it for the initial transfers and swaps on the Meter mainnet.&#x20;


# MTRG Crosschain Info

## The Meter Passport

[Meter Passport](https://passport.meter.io) allows MTRG and other ERC20 and ERC721 tokens to be transferred among the supported blockchains.&#x20;

Here is important information about MTRG on different chains.  To reduce user confusion, we have decided to call all wrapped versions of MTRG on different chains as MTRG.  The Ethereum version was deployed earlier and was called eMTRG.

Ethereum:

1. eMTRG
   1. Contract address: [0xBd2949F67DcdC549c6Ebe98696449Fa79D988A9F](https://etherscan.io/token/0xBd2949F67DcdC549c6Ebe98696449Fa79D988A9F)
   2. [eMTRG / ETH Uniswap pool](https://uniswap.info/pair/0x837f68d11cd15e8ab10dd5f3f210516f2cf2bcfb)
2. eMTR
   1. Contract address: [0x29e9fdf5933824ad21bc6dbb8bf156efa3735e32](https://etherscan.io/token/0x29e9fdf5933824ad21bc6dbb8bf156efa3735e32)

Binance Smart Chain(BSC):

MTRG contract address: [0xBd2949F67DcdC549c6Ebe98696449Fa79D988A9F](https://etherscan.io/token/0xBd2949F67DcdC549c6Ebe98696449Fa79D988A9F)

Base Mainnet:

eMTRG contract address: [0xa023E6f6B4862EA38cbe45e377abD908abAb2f82](https://basescan.org/address/0xa023e6f6b4862ea38cbe45e377abd908abab2f82)

Meter Mainnet:

MTRG ERC20 Interface: <mark style="color:blue;">0x228ebBeE999c6a7ad74A6130E81b12f9Fe237Ba3</mark>

## Operating the Same Account on Metamask and Meter Wallet

Metamask configuration information can be found in the previous section

Meter Wallet supports native Meter transactions including staking, starting candidate nodes, vote on candidates.  Metamask is used in the Ethereum emulation mode to interact with dApps.  It is easy to operate the same account in both Meter Wallet and Metamask.  Meter wallet is completely [open sourced](https://github.com/meterio/meter-wallet).  Your private key will only be encrypted and stored on your local computer.

To export the private keys from Meter Wallet to Metamask:

![Backup Keystore into a .json file from MeterWallet](/files/-MfxM_aily7qBBtrNzuC)

![Import the .json file into Metamask](/files/-MfxNAdQSZDiaov5_BId)

Export Private Key from Metamask and Import to Meter Wallet

![Export Private Key from Account details in Metamask](/files/-MfxNwYt7jsyj1pJKVOk)

![Import Metamask Private Key to Meterwallet](/files/-MfxOW4T7IK_qMPucS_N)


# Onboarding Passport for Your Project

The primary purpose of this document is to provide guidelines for projects on how they can onboard their tokens to the Meter Passport bridge and start transferring assets to/from Moonbeam/Moonriver.<br>

The document is divided into the following sections:

* Roadmap of the onboarding process
* Which token model to use
* Deploying wrapped token representation
* Register tokens on the bridge
* Technical limitations
* Security concerns
* Contact information

### Roadmap of the Onboarding Process

The roadmap of onboarding your token to the bridge is the following:<br>

* Decide which token model to use
* Deploy the wrapped token contract on the destination chain
* Register the tokens

The following sections go through each of the steps.

### Decide which token model to use

There are two main possibilities for transferring tokens from one chain to another: the lock-unlock mechanism and the lock/mint - burn/unlock mechanism. In both models, tokens in the destination chain are typically called “wrapped representations” of the original tokens.<br>

Each model has pros and cons in terms of user experience, setup, token accountability, and security. You can read more about each token model in the [Technical Guidelines](/passport/technical-guideline-for-meter-passport) document.<br>

The token model you decide defines the smart contract you’ll need to deploy for the wrapped token representation for the destination chains.<br>

### Deploy the wrapped token representation

Once your team has decided which token model to use, you’ll need to deploy the smart contract to the destination chain, in this case, Moonriver/Moonbeam. At its core, it doesn’t matter what EIP the token is based on, as long as it complies with the following ERC20 token functions (you could also send a request to the Meter Passport team (email <moonriver@meter.io> to deploy a [preset ERC20 contract](https://github.com/meterio/chainbridge-solidity-v1.0.0-eth/blob/master/contracts/ERC20Safe.sol) for you if there are no customized functions needed:<br>

Origin chain (original tokens):

* Transfer (standard ERC20 transfer function)

Destination chain (wrapped representation):<br>

* Transfer (standard ERC20 transfer function)
* Minting and burning function, needed if using the lock/mint - burn/unlock token mode. Needs to add the handler contract as minter/burner

If you use the same private key/nonce as for your original token contract, the wrapped representation will have the same address (which is pretty cool!).<br>

You’ll have to provide the token address to the Meter Passport team to register the asset on the bridge.

### Register the tokens on the bridge

With the smart contracts deployed, both in the origin (original token contract) and destination (wrapped token contract) chains, the next step is to register them in the bridge’s smart contract and front-end interface.<br>

To do so, please send the following information to <moonriver@meter.io> (Moonbeam is not yet available):<br>

* Team Name/Website
* Github link of the original token contract, must live under the team’s official Github repository
* Github link of the wrapped token contract, must live under the team’s official Github repository
* Address of the original token contract, specifying in which blockchain it is deployed (for example: “Ethereum: 0x12345….”
* Address of the wrapped token contract, specifying in which blockchain it is deployed (for example: “Moonriver: 0x98765….”
* Logos and names that your team wants to use for each of the tokens

### Technical limitations

Currently, Meter Passport is based on a slightly modified version of ChainSafe’s Chainbridge. The bridge offers a generic handler contract that can carry out any action in the destination chain, passed as bytes in the event emitted on the origin chain. However, interacting with the generic handler requires allocating resources to adapt the use case to the contract’s interface.<br>

Therefore, the bridge offers two other handlers: one for the basic ERC20 token standard and one for the ERC721 token standard. Currently, the Meter Passport bridge works with ERC20 token standard only. Thus, to transfer tokens through the bridge, they must comply with a basic ERC20 token interface and, depending on the token model chosen, have mint/burn capabilities.<br>

Currently, Meter Passport uses 25 block confirmations for all transactions on Ethereum.  Therefore, a transfer out of Ethereum typically takes 6 to 10 minutes after the bridge deposit transaction is confirmed, while a transfer to Ethereum takes around the same time.  From time to time when Ethereum is highly congested and the gas price changes dramatically in a very short time period, transactions may take longer to complete.  Feel free to direct the users to the Meter telegram channels if they run into any transfer related issues.  <br>

Another current limitation of the bridge is the gas consumption. The transaction that the user will send in the origin chain, which initiates the subsequent chain of events, costs around 280000 gas units (gas units\* gasPrice is the total transaction cost for the user). The total cost on the destination chain (including all the transactions that the bridge mechanism needs by design) is around 730000 gas units.<br>

Meter team is working on a new release that should dramatically reduce gas consumption.&#x20;

### Security concerns

The Meter Passport bridge runs with a set of trusted relayers that relay messages between EVM-compatible blockchains. These messages subsequently transfer assets between chains (wrapped tokens representing the original token). <br>

The bridge works with a multisig mechanism to prevent single relayers from abusing the system. Proposals (actions to be executed on the destination chain) are executed only if a signature threshold is achieved. Meter Passport works with a 3/5 threshold.<br>

Therefore, the main security concern of this bridging mechanism is that it relays in a semi-centralized set of relayers and not a fully decentralized model. But, due to how the contracts work, as the number of relayers and multisig threshold increases, the gas consumption on the destination chain increases.<br>

Meter Passport is currently secured by [Protofire](https://protofire.io/), [Hashquark](http://hashquark), [InfinityStones](https://infinitystones.io/), [Wetez](https://www.wetez.io/) and the [Meter team](https://www.meter.io/). It is aimed to be a shared secure infrastructure for various blockchains and multichain dApps. 3 out of 5 the relayers group were securing the Avalanche-Ethereum Bridge with more than $300M value locked on the bridge and the other relayers are highly reputable staking service providers validating on Polkadot, BSC, Cosmos, and many other PoS networks.  The Ampleforth team has leveraged Meter Passport to launch its multi-chain AMPL. The Meter team is working on a threshold signature based implementation that supports an unlimited number of relayers for a higher level of security.  <br>

### Contact information

For any inquiries regarding the bridge, please contact:\ <br>

* Moonriver: <moonriver@meter.io>
* Moonbeam (not yet available)

If you have any questions related to Moonbeam/Moonriver, please use the following channels:<br>

* Discord: <https://discord.gg/PfpUATX>
* Telegram: <https://t.me/Moonbeam_Official>

For Meter passport related support questions, please use the following channels:

* Discord: <https://discord.com/invite/SCkaAqQCsZ>

Telegram: <https://t.me/Meter_IO>


# Technical Guideline for Meter Passport

The primary purpose of this document is to provide guidelines for projects on how they can transfer assets to/from Moonbeam/Moonriver using the Meter Passport bridge implementation.<br>

The document is divided into the following sections:

* How the bridge works
* Different token transfer models supported by the bridge
* As a project, what do you have to do
* Links of interest
* Contact information

### How does the bridge work at a high level?

**TLDR:**

Meter Passport works with a set of trusted decentralized relayers that read events from a source chain and execute actions on a destination chain. Users will pay for gas in the source chain to initiate the action, while relayers will pay for gas to execute it on the destination.

**Details:**

Meter Passport bridge is, at its core, a message-passing protocol. Events on a source chain are used to send a message that is routed to the destination chain. There are three main roles:

* Listener: extract events from a source chain and construct a message
* Router: passes the message from the Listener to the Writer
* Writer: interpret messages and submit transactions to the destination chain

Passport currently relies on trusted relayers that carry messages from an event on a source chain to a destination chain. It features a mechanism that prevents any individual relayer from abusing their power and mishandling funds. At a high level, relayers create proposals in the target chain submitted for approval by other relayers. Approval voting also happens in the target chain, and each proposal is only executed after it meets a certain voting threshold.

In terms of paying for gas, users of the bridge will cover gas costs in the source chain, while relayers will pay for gas related to the execution of the action on the destination chain. The bridge can charge a fee to the users to help cover expenses associated with running the bridge.

On both sides of the bridge, there are a set of smart contracts, where each has a specific function:

Bridge contract — users and relayers interact with this contract. It delegates calls to the handler contracts for deposits, starts a transaction on the source chain, and executes the proposals on the target chain.

Handler contracts — validates the parameters provided by the user, creating a deposit/execution record.

Target contract — as the name suggests, this is the contract we are going to interact with on each side of the bridge.

### Token transfers - The different models

**TLDR:**

There are two supported token transfer models for the bridge. A lock-unlock model locks tokens on the origin chain and unlocks wrapped tokens (representations) on the destination chain. A lock/mint - burn/unlock model locks token on the origin chain and mints wrapped tokens (representations) on the destination chain. To transfer wrapped tokens back, these would be burned in the now origin chain, enabling an unlocking event in the now destination chain.

**Details:**

There are two main possibilities for transferring tokens from one chain to another: the lock-unlock mechanism and the lock/mint - burn/unlock mechanism. In both models, tokens in the destination chain are typically called “wrapped representations” of the original tokens.<br>

Each model has pros and cons in terms of user experience, setup, token accountability and security. Let’s briefly review each model.

#### LOCK-UNLOCK

In this model, tokens from the source chain (original tokens) are locked inside the handler contract of the source chain. The relayer’s multisig account can only withdraw them. When locking tokens, an event is emitted with the transfer data, picked by the relayers.<br>

Once the multisig threshold is reached, wrapped tokens can then be unlocked from the handler contract of the destination chain. This creates the lock-unlock sequence. Therefore, a certain amount of wrapped tokens need to be minted at contract creation and locked in the handler contract.<br>

For example, Alice wants to transfer 5 TACO tokens to Bob from chain A to chain B. When she initiates the transfers, those 5 TACO tokens are locked in the token handler contract on chain A. An event is emitted stating, among other things, the recipient address and amount of tokens, which is picked up by the relayers. If the multisig threshold is reached, 5 wTACO (wrapped TACO) tokens are unlocked from the handler contract on chain B, and transferred to Bob. If Bob wanted to send 5 wTACO tokens to Charlie on chain A, he would then lock these tokens in the handler contract on chain B, initiating the series of events that leads to unlocking of 5 TACO tokens on chain A, which are transferred to Charley.\
\
The main benefit of this token model is that it gives your team certain control on the maximum amount of tokens that can be wrapped in the target network, because wrapped tokens need to be preminted and transferred to the handler’s address. However, the main drawback is that token accountability becomes an issue, and the lack of wrapped tokens in the handler contract  can prevent the bridge from operating properly. This method is not preferred by the Meter Passport team.<br>

#### Lock/mint - burn/unlock

In this model, as before,  tokens from the source chain (original tokens) are locked inside the handler contract of the origin chain. The relayer’s multisig account can only withdraw them. When locking tokens, an event is emitted with the transfer data, picked by the relayers.<br>

Once the multisig threshold is reached, wrapped tokens can then be minted as a wrapped representation, via the handler contract, in the wrapped token contract on the destination chain. This creates the lock/mint sequence. Note that the handler’s contract address needs to be given a minter role in the wrapped token contract on the destination chain. <br>

To transfer back wrapped tokens, these would be burned via the handler contract in the origin chain (previously the destination chain). As before, an event is emitted with the transfer data, picked up by the relayers. Once the multisig threshold is reached, tokens locked in the handler contract of the destination chain (previously the origin chain) are unlocked and transferred to the recipient. This creates the burn/unlock sequence. Note that the handler’s contract address needs to be given a burner role in the wrapped token contract on the destination chain. <br>

For example, Alice wants to transfer 5 TACO tokens to Bob from chain A to chain B. When she initiates the transfers, those 5 TACO tokens are locked in the token handler contract on chain A. An event is emitted stating, among other things, the recipient address and amount of tokens, which is picked up by the relayers. If the multisig threshold is reached, 5 wTACO (wrapped TACO) tokens are minted in the wrapped token contract on chain B, and transferred to Bob. If Bob wanted to send 5 wTACO tokens to Charlie on chain A, he would then burn these tokens via the handler contract on chain B (not directly), initiating the series of events that leads to an unlocking of 5 TACO tokens on chain A, which are transferred to Charley.<br>

The main benefit of this token model is that there is a wrapped token per locked original token in the origin chain. Therefore, token accountability is easier and assets can freely flow through the bridge, as long as users initiate the action. The main drawback is that the contract to be deployed as the wrapped token representation needs to support the mint/burn (mint and burnFrom interfaces in the [contract](https://github.com/ChainSafe/chainbridge-solidity/blob/master/contracts/ERC20Safe.sol)) mechanisms. This model is preferred by the Meter Passport team.

### As a project - What do we need to know about the Bridge?

Fungible tokens that will be transferred using this bridging mechanism need to have a minimum set of functionalities to work with the bridge. At its core, it doesn’t really matter what EIP the token is based on, as long as it complies with the following  ERC20 token functions:<br>

Origin chain (original tokens):<br>

* Transfer (standard ERC20 transfer function)

Destination chain (wrapped representation):<br>

* Transfer (standard ERC20 transfer function)
* Minting and burning function, needed if using the lock/mint - burn/unlock mechanism. Needs to add the handler contract as minter/burner

An example token contract can be found here.

With either token transfer model, a token registration procedure needs to take place. As such, your project should communicate to the relayers which token contract you want to link on which chain. For example, let’s say we want to have a TACO token (originated on Ethereum):\ <br>

* TACO token Ethereum: 0x123456….
* wTACO token Moonriver: 0x987654…

Note: if you use the same private key and nonce that you used to deploy the original token contract to deploy the token contract on other chains, they will all have the same address (which is awesome!)<br>

### Links of interest

Meter Passport bridge tokens Github:

<https://github.com/meterio/token-list><br>

Bridge contract Github:&#x20;

<https://github.com/meterio/Passportv2Contracts>

Chainbridge original documentation:

<https://docs.buildwithsygma.com/><br>

For Meter passport related support questions, please use the following channels:

* Discord: <https://discordapp.com/invite/WPjTpMG>
* Telegram: <https://t.me/Meter_IO>


# Security Audit for Meter Passport V2.0

The Meter Passport v2.0 smart contracts were developed on the ChainSafe v2.x bridge contracts. Meter’s additions were mainly focusing on the relay chain signature aggregation design. The original contracts were internally audited through a separate team at ChainSafe.

The final version of the smart contracts were audited by HAECHI AUDIT.

During the audit, 8 findings of varying severity levels (three critical, two major, and three minor) were found and subsequently resolved ensuring that the codebase is rigorously tested and verified. HAECHI also recommended two tips to improve the codebase’s overall efficiency and usability.

You can view the published audit report in full detail [here](https://github.com/meterio/Passportv2Contracts/tree/main/audit).


# Staking MTRG

Here are details about how MTRG staking works and a tutorial on how to stake with the Meter wallet.

#### As part of the dual chain infrastructure, Meter Network leverages the Proof-Of-Stake chain for record keeping consensus. The key purpose of staking is to secure the Meter Network against Sybil attacks. &#x20;

Community users not planning on running a full-node can leverage staking solution to secure the Network while ensuring that their MTRG is non-dilutive.&#x20;

## Brief Background

#### **Edison Mainnet Launch**

July 4, 2020 (Functional mainnet without Staking and on-chain MTRG auctions). Nodes are run by the Meter Foundation

Further Reading: [Edison Mainnet Launch](https://medium.com/meter-io/the-meter-mainnet-is-now-live-3d0a4a1e1174)

**Tesla Mainnet Launch**

March 19, 2021 (Fully functional Mainnet with Staking and On-chain MTRG auctions). Node Operations are open to the community.

Further Reading: [Tesla Mainnet](https://medium.com/meter-io/the-meter-mainnet-is-now-live-3d0a4a1e1174)

**Staking Launch Block height on Mainnet:** 9,470,000

## Important Information

### **Minimum Staking Amount**&#x20;

100 MTRG

### **Staking Applications**

Meter Network supports web staking with [staking.meter.io](https://staking.meter.io/) as well as staking on Meter Desktop wallet

\*Meter Desktop wallet will be sunset gradually and no longer be maintained. It is available to download on Meter.io homepage (section “Meter Desktop Wallet at the bottom of the page)

### **Staking Rewards**

Staking rewards are sourced from the annual network emission and are provided every 24 epochs (typically 24 hours) to the address staking on the Meter Mainnet.

\**Users can DM “/staking (wallet address)” to @MeterValidatorBot on Telegram to get daily messages when their wallet receives the staking rewards. Users lose potential rewards only when the candidate they have delegated gets jailed.*

### **Staking Reward Token**

Community can earn either MTRG or MTR through the staking program.

### **Network Emission Rate**

Annual 5% (this can be changed through governance). Current Annual Inflation is available on [scan.meter.io](https://scan.meter.io/) .&#x20;

Daily emission available here: [Meter on-chain auctions](https://scan.meter.io/auction)

### **Circulating Supply**

Circulating Supply includes the daily emission of MTRG through the network inflation required to secure the network. Current Circulating supply is available on [scan.meter.io](https://scan.meter.io/) .

### **Consensus Committee Size**

A consensus committee size determines how many Node Operators will take part in the record keeping consensus every epoch. **Only the validators active in the consensus committee for the epoch earn staking rewards for that epoch.** The current committee size of Meter Mainnet is 500 nodes enabled by the highly performant HotStuff Consensus capable of supporting 1000s of nodes. This is in start contrast to other BFT consensus mechanisms supporting 100s of nodes.

### **Staking Ratio**

The proportion of circulating supply of MTRG that is staked. Current Staking Ratio is available on [scan.meter.io](https://scan.meter.io/) homepage.

### **Staking Returns**

Annual inflation rate divided by Staking Ratio

As on June 27, 2022:

Staking Ratio — 48.31%,

Annual Inflation — 5%

Staking Returns — 10.35%

Current Staking Ratio and Annual Inflation available on [scan.meter.io](https://scan.meter.io/) homepage.

## **General Definitions**

### Buckets/ Vote ID

MTRG staking is done via “buckets/ Vote ID” which includes a specific amount of MTRG the community users want to stake.&#x20;

### Candidate

The node operators with whom the user would like to delegate their MTRG tokens. You can choose a bucket either to vote for your own validator candidate nodes (the top 500 validator nodes by votes can participate in the consensus currently) or other candidate nodes.

### Unbound

In order to withdraw MTRG stake from the staking application, the user must 'unbound' the bucket and then wait for a period of 7 days and at the end of the epoch, MTRG will be available in the user's wallet.

### Bonus Votes&#x20;

Bonus votes are MTRG votes accrued to the bucket/ Vote ID to incentivize long term staking on the Network. The longer a user stakes, the more votes the user bucket/ vote ID will accrue. The accumulation rate is 5% annually based on the 7 day unbounding period.

### Add More/ Partial Unbound

Users will be able to increase the bucket size by any amount of MTRG available in their account. The functionality to reduce the bucket/ Vote ID size is under development. Currently, users will have to unbound and completely withdraw the entire bucket.&#x20;

### Undelegate

Users have to ability to change the candidate they have delegated to at any time. This is particularly helpful when the Node on which MTRG is delegated is not performing well (jailed multiple times) leading to loss of rewards for the delegator or the delegator wishes to move to a Node Candidate with lower commission or starts their own node.

### Commission

The commission percentage is the portion of Delegator rewards shared with the node operator for the ability to participate in record-keeping consensus. Currently, the maximum commission charged is 10%

### Auto Bid

New emitted MTRG is earned by the delegators through the [on-chain auctions](/overview-of-meter/on-chain-auctions). The brief staking rewards process is as below;

1. Delegators/ Node Operators earn MTR rewards every epoch for participating in record keeping consensus. These MTR are sourced from previous days' auction process
2. If auto-bid is selected by the delegator on their bucket/ Vote ID, MTR received is deposited in the duction auction to bid for newly emitted MTRG on the current day
3. At the end of 24 epochs, Delegators get the MTRG based on the MTR submitted in to the Dutch auctions
4. If auto-bid is not selected by the delegator on their bucket/ Vote ID, the delegators receives MTR as the reward for the day

### Liquid Staking

To provide better DeFi composiblity and New emitted MTRG is earned by the delegators through the [on-chain auctions](/overview-of-meter/on-chain-auctions). The brief staking rewards process is as below;

1. Delegators/ Node Operators earn MTR rewards every epoch for participating in record keeping consensus. These MTR are sourced from previous days' auction process
2. If auto

## &#x20;Tutorials

{% content-ref url="/pages/M2EBmHKpm2PNiwSFdsko" %}
[How to Stake MTRG](/full-node-and-validation/staking-mtrg-how-to-stake-and-staking-details/how-to-stake-mtrg)
{% endcontent-ref %}

{% content-ref url="/pages/a7kFmieGdDzUih6gG7MC" %}
[How to Stake Incremental MTRG](/full-node-and-validation/staking-mtrg-how-to-stake-and-staking-details/how-to-stake-incremental-mtrg)
{% endcontent-ref %}

{% content-ref url="/pages/N0p9eNmtbyMzyGMKTs46" %}
[How to Undelegate MTRG](/full-node-and-validation/staking-mtrg-how-to-stake-and-staking-details/how-to-undelegate-mtrg)
{% endcontent-ref %}

{% content-ref url="/pages/nCAACjEvuAijC3iIsAJw" %}
[How to Unbound MTRG](/full-node-and-validation/staking-mtrg-how-to-stake-and-staking-details/how-to-unbound-mtrg)
{% endcontent-ref %}

## FAQs

{% content-ref url="/pages/cpgGmoFGuBZeLzayBQLL" %}
[Frequently Asked Questions](/full-node-and-validation/staking-mtrg-how-to-stake-and-staking-details/frequently-asked-questions)
{% endcontent-ref %}


# How to Stake MTRG

## Prerequisites: <a href="#id-7161" id="id-7161"></a>

> 1\. Min of 100 MTRG
>
> 2\. Some MTR for transaction fees

## Video Tutorial

{% embed url="<https://youtu.be/3UJcLTyJvc8>" %}

## Step-by-Step Guide

### Step 1

Access [staking.meter.io](https://staking.meter.io/) and connect to MetaMask wallet with the requisite address

![](https://miro.medium.com/max/1400/1*sPnEkO2iPevwCTlwzWTLtQ.png)![](https://miro.medium.com/max/1400/1*PS7d3E2Hb5UQbSzb6ocSMQ.png)

### Step 2

Confirm the available balance of MTRG and MTR and choose to Vote against the Candidate shortlisted.

More details on choosing a candidate can be found here;

{% content-ref url="/pages/x3PUBpWBuzTFrR4xaz3i" %}
[Choosing Candidates](/full-node-and-validation/staking-mtrg-how-to-stake-and-staking-details/how-to-stake-mtrg/choosing-candidates)
{% endcontent-ref %}

![](/files/CZ9VhblNDGDFOwSBSGVH)

***Note:** The requisition address should have minimum of 100 MTRG and some MTR for transaction fees*

### Step 3

Stake/ Delegate to the Candidate and submit the vote

![](/files/87g8oSkOqX0Zxe0X1vyq)

![](https://miro.medium.com/max/1400/1*Jz3UCh4GZYgoGWxjIXIdCw.png)

Staking amount < 100 gives an error.

**Note:** *Candidate is blanked out to keep the tutorial impartial*

### Step 4

Confirm the transaction in MetaMask

![](https://miro.medium.com/max/1400/1*uoZ-T375WqHyygbPe1eaqQ.png)

**Note:** *Typical transaction costs for staking are less than 0.05 MTR*

### Step 5

Vote ID: Key information

![](https://miro.medium.com/max/1400/1*ccTvxqiQ6Mmv8enHC0r7tA.png)

Note: *Meter literature also refers Vote ID as “Bucket ID”. They are interchangeable terms.*

![](https://miro.medium.com/max/1400/1*yLBY6Smm4Aou3y3-c1I0zw.png)

**Note:** *Bonus votes increases the weight of the Vote ID in the staking rewards. Higher the bonus votes, more the staking rewards. The system rewards long term stakers with increasing bonus votes*

**Note:** *The screen shot was added post “add more” MTRG to bucket thus showing votes as 105 MTRG*

Factors affecting Staking Rewards can be found here;

{% content-ref url="/pages/p6ndI9uVFnY6LEK9Kfhj" %}
[Factors affecting Staking Rewards](/full-node-and-validation/staking-mtrg-how-to-stake-and-staking-details/how-to-stake-mtrg/factors-affecting-staking-rewards)
{% endcontent-ref %}

### **You have successfully staked/ delegated your MTRG.** <a href="#id-652f" id="id-652f"></a>


# Choosing Candidates

Meter Network currently does not have uptime analytics for Node Operators. However, historically since April 2021, there has been minimum downtime across node operators.&#x20;

It is safe for users to choose any candidate to delegate their stake.

Alternatively, Users can DM “/staking (wallet address)” to @MeterValidatorBot on Telegram to get daily messages when your wallet receives the staking rewards.&#x20;

Users lose potential rewards only when the candidate they have delegated gets jailed.

#### Information currently available on the Candidates

![](/files/4KHWtWekgA6lYqqkcKKH)

**Candidate Name:** The name of the candidate node on which you can stake

**Address:** Address running the node

**Commission:** The portion of the staking rewards that will be withheld for providing the staking service

**Total Votes:** Total MTRG that has been staked/ delegated on the candidate

**nVoter:** Number of buckets (each of minimum 100 MTRG) that have been staked on the candidate


# Factors affecting Staking Rewards

Delegators/ Stakers will choose from the list of available candidates to delegate their stake.

#### **Key Factors affecting Staking Rewards are;** <a href="#id-020c" id="id-020c"></a>

**Staking Ratio** — *More MTRG staked equals lower share per MTRG staked to the delegator/ staker. However, it also means more secure network against Sybil attacks*

**Total number of MTRG staked by the user** — *More MTRG staked by the user equal higher rewards to the delegator/ staker*

**Commission charged by the Candidate** — *More commissioned charged equal lower staking rewards to the delegator/ staker*

**Consensus Committee Size** — *Committee size lower than node count means there will be epoch where users do not receive rewards. The current committee size is 500 and node count is 285*


# How to Stake Incremental MTRG

## Purpose <a href="#id-8a00" id="id-8a00"></a>

‘Vote More’ MTRG enables users to add more MTRG to the existing Vote ID. This maybe done for one of the below reasons;

1\. The user does not have additional 100 MTRG to meet the threshold to create a new Vote ID

2\. The user adds staking rewards periodically to the existing Vote ID to compound staking rewards

## Prerequisites <a href="#id-1ef9" id="id-1ef9"></a>

> 1\. Existing Vote of minimum 100 MTRG
>
> 2\. Additional MTRG to add to the Vote ID

## Video Tutorial

{% embed url="<https://youtu.be/-w20sTrmAx4>" %}

## Step-by-Step Guide

### Step 1

“Vote more” on the existing Vote ID

![](https://miro.medium.com/max/1400/1*UyheNxwMquK5kKbT9PAWOA.png)

### Step 2

Add “Extra Amount” of MTRG to the Vote ID

![](https://miro.medium.com/max/1400/1*Le6X0WEpLDHzQQ4wQYHxpw.png)

**Note:** *User can add any amount of MTRG to the bucket up to the current ‘free’ MTRG balance on the account*

### Step 3

Confirm the transaction in MetaMask

![](https://miro.medium.com/max/1400/1*wIMIEHtLV9-ao_WVpS0rFg.png)

### Step 4

Confirm the “locked MTRG” balance increase

![](https://miro.medium.com/max/1400/1*DAcZb_Fk_1A6VDqXFVDxkg.png)

### You have successfully staked/ delegated additional MTRG to your existing Votes. <a href="#id-1a4d" id="id-1a4d"></a>


# How to Undelegate MTRG

## Purpose <a href="#id-5819" id="id-5819"></a>

“Undelegate” enables users to change the candidate on the Vote while continuing staking. This maybe done for one of the below reasons;

1\. The current candidate has been jailed leading to loss of rewards for the user

2\. The user/ acquaintance has a new node setup. The votes need to be moved to the new candidate

3\. The user wants to move Votes to a candidate with lower commission

## Prerequisites: <a href="#f2b4" id="f2b4"></a>

> Existing Vote ID

## Video Tutorial

{% embed url="<https://youtu.be/pRWMUvtFr7g>" %}

## Step-by-Step Guide

### Step 1

“Undelegate” on the existing Vote ID

![](https://miro.medium.com/max/1400/1*9JVnwgCeuHdRNtlQwKuArQ.png)

### Step 2

Confirm the “Undelegate”

![](https://miro.medium.com/max/1400/1*nGCMPPkwrz1pkqZZQ7fcjQ.png)

*Please read the instructions before you “undelegate”*

**Note:** *Users do not receive rewards unless they “delegate” the Vote ID again to a new candidate*

**Note:** *The Vote ID loses the bonus votes on “Undelegate”*

### Step 3&#x20;

Confirm the transaction in MetaMask

![](https://miro.medium.com/max/1400/1*IAytHUuUg4KW12sVszO4Eg.png)

### Step 4

Note the changes to the Vote ID

![](https://miro.medium.com/max/1400/1*6NaAuY-7-hOVj5ZU5owb1g.png)

![](https://miro.medium.com/max/1400/1*JsyyDkE4IbBHQ8KLfxHETA.png)

### Step 5

“Delegate” on the existing Vote ID to vote on a new candidate

![](https://miro.medium.com/max/1400/1*PZZ1K5Hl4X9a_LTKgbX8sw.png)

**Note:** *“Delegate” is only visible for a Vote ID that is previously undelegated.*

### Step 6

Choose the new Candidate and submit

![](https://miro.medium.com/max/1400/1*PMkx_wFFzJB1BeLNP34Mfw.png)

### Step 7

Confirm the transaction in MetaMask

![](https://miro.medium.com/max/1400/1*pXHLSdGT3pFApW5cO_kCWQ.png)

### Step 8

Confirm the New Candidate delegation

![](https://miro.medium.com/max/1400/1*UP5B-Vw4XKUsAX9WANHR6Q.png)

### You have successfully undelegated MTRG from one candidate and delegated back to a new candidate. <a href="#af2f" id="af2f"></a>


# How to Unbound MTRG

## Purpose <a href="#f263" id="f263"></a>

“Unbound” enables users to remove the MTRG from staking. This maybe done for one of the below reasons;

1\. Partake in Node Operation to earn higher rewards through Meter Foundation Delegation

2\. Deploy MTRG in DeFI applications like DEX liquidity or Lending and Borrowing

## Prerequisites <a href="#id-0f7c" id="id-0f7c"></a>

> 1\. Existing Vote ID

## Video Tutorial

{% embed url="<https://youtu.be/2yGCGYctEkg>" %}

## Step-by-Step Guide

### Step 1

&#x20;“Unbound” on the existing Vote ID

![](https://miro.medium.com/max/1400/1*GMMnY2_jO9sPnlYAXADvSw.png)

### Step 2

Confirm the “Unbound”

![](https://miro.medium.com/max/1400/1*L9yZ9rki-wmsz-1aWP7YAw.png)

*Please read the instructions before you “unbound”*

**Note:** “*Unbound” without “Undelegate” will ensure that user keep getting rewards during the unbound period of 1 week*

### Step 3

Confirm the transaction in MetaMask

![](https://miro.medium.com/max/1400/1*UEiE7ZkV6pXDcA4zUCu4xw.png)

### Step 4

Note the changes to the ‘state’ column with the timer ‘Mature in 7 days’

![](https://miro.medium.com/max/1400/1*Ke4g8i7_WQ9LIUKV7NUdJg.png)

**Note:** *MTRG is locked in staking until the end of epoch once “Unbound” countdown is over. Please wait until the end of current epoch to ensure MTRG are available in your account. The ‘state’ column displays the additional time as ‘Matured 50 mins ago’*

**Note:** *Please track the ‘state’ column on the Vote ID to track the latest status of the unbound process*

### You have successfully unbounded MTRG staking.  <a href="#e4c9" id="e4c9"></a>

#### The MTRG will be available in your account after 7 days + 1 epoch (typically 1 hr.) <a href="#e4c9" id="e4c9"></a>


# Frequently Asked Questions

### Basics

#### Where do I stake on Meter Mainnet? <a href="#id-92fd" id="id-92fd"></a>

Users can leverage Web staking with MetaMask on [staking.meter.io](https://staking.meter.io/). Existing users can continue using Meter Desktop Wallet to stake MTRG.

#### **What is the staking APY?** <a href="#id-3ab0" id="id-3ab0"></a>

The staking APY is variable. Staking APY = (Annual Inflation %) divided by (staking ratio %). While the annual inflation can only be changed through governance, the staking ratio fluctuates based on addition/ removal of MTRG from staking. Annual Inflation and Staking Ratio is available on scan.meter.io homepage.

> As on June 27, 2022: Staking Ratio — 48.31%, Annual Inflation — 5%
>
> Staking Returns — 10.35%

#### How long can I stake? <a href="#id-36ff" id="id-36ff"></a>

Staking is non-custodial and the user can stake as long as he wishes. Staked tokens are locked. The tokens can be unlocked through the ‘unbound’ process in 1 week

### Prerequisites

#### What is the minimum number of MTRG required for Staking? <a href="#id-84c0" id="id-84c0"></a>

100 MTRG

#### How much MTR is required for staking transactions? <a href="#id-97f3" id="id-97f3"></a>

Around 0.3 MTR should suffice for over 8–10 staking transactions

#### I do not have MTR for transaction fees, is there a faucet? <a href="#id-0a80" id="id-0a80"></a>

Users can perform gasless swap on Meter Mainnet using ‘wallet.meter.io/swap’

### Bridging

#### I have MTRG on Ethereum/ Binance Smart Chain, How can I stake? <a href="#id-5931" id="id-5931"></a>

Transfer the funds through passport.meter.io to stake on Meter Mainnet. User can leverage the guide here — [How to bridge](https://docs.voltswap.finance/how-to-bridge-funds/meter-mainnet)

### Wallets

#### Which wallets are supported for staking <a href="#id-9a53" id="id-9a53"></a>

Web Wallets — MetaMask, Wallet Connect

Application — Meter Desktop Wallet

#### Does staking support Cold wallets? <a href="#id-210a" id="id-210a"></a>

Staking through MetaMask can be done through cold wallets like Ledger. Meter Desktop Wallet does not support cold wallets.

### Staking

#### How do I choose a candidate? <a href="#c21d" id="c21d"></a>

Typical criteria for choosing candidates is uptime or commission. All candidates on Meter have had historically very high uptime. User can choose any candidate from the list of available candidates. A good practice would be to get rewards notifications from Meter Validator bot to keep an eye on the rewards received every 24 epochs.

#### Do we enable Auto-bid? <a href="#id-7e90" id="id-7e90"></a>

Yes, Enable Auto-bid provides users with MTRG as staking rewards. When Auto-bid is not enabled, users receive MTR (Metastable gas token) as staking rewards.

#### What is ‘Enable Auto-bid? <a href="#b5a0" id="b5a0"></a>

Daily emitted MTRG through 5% Network inflation are distributed to the stakers through the on-chain auction process. (See [Meter Docs](https://docs.meter.io/overview-of-meter/on-chain-auctions) for more information).

### Staking Rewards

#### How often does one get staking rewards? <a href="#id-7034" id="id-7034"></a>

Staking rewards are distributed every 24 epochs (typically 1 day) to the address staking on the Meter Mainnet.

#### Do I receive MTR or MTRG as staking rewards? <a href="#c90f" id="c90f"></a>

This depends on whether “Enable Auto-bid” has been checked on the Vote ID or not. Users receive MTRG when “Enable Auto-bid” is checked, else they will receive MTR (Metastable gas token)

#### How do I check the MTRG earned through staking? <a href="#f5d4" id="f5d4"></a>

Users can DM “/staking (wallet address)” to @MeterValidatorBot on Telegram to get daily messages when your wallet receives the staking rewards

#### How are staking rewards calculated? <a href="#id-1d11" id="id-1d11"></a>

Staking rewards can be approximately calculated as below;

**Annual:**

Number of MTRG staked x Annual Inflation / Staking Ratio x (1 minus Candidate Commission rate)

For e.g.: 1000 MTRG x 5% /48.31% x (1 minus 10%) = 93.15 MTRG

**Daily:**

Annual Staking Rewards / 365

For e.g.: 93.15 MTRG / 365 = 0.26 MTRG

#### Does Meter Mainnet support auto-compounding of rewards? <a href="#id-8e34" id="id-8e34"></a>

No, Meter Mainnet currently does not support auto-compounding. Next best option is to use the “Add More” option on the existing Vote ID periodically to increase the rewards.

#### Can I lose staking rewards? <a href="#id-677e" id="id-677e"></a>

Yes, delegators can lose potential staking rewards if the candidate they delegated to is jailed. Validators typically bail out the nodes from the jail after fixing issues so that they can continue earning staking rewards. If your validator has not bailed out, user can “undelegate” from current candidate to choose a new candidate.

### Vote ID/ Buckets

#### What are bonus votes on my Vote ID? <a href="#id-0cc0" id="id-0cc0"></a>

Bonus votes increase at the rate of 8% per annum and incentivize long term staking. The weight of user stake increases by the bonus votes during staking rewards distribution.

#### Can I multiple Vote IDs (buckets) on the same account/ address? <a href="#id-2daf" id="id-2daf"></a>

Yes, you can create multiple Vote IDs (buckets) on the same account adhering to the constraint of 100 MTRG per Vote ID. Users looking to diversify their stake against loss of staking rewards from jailed nodes can use the option. Almost all nodes on Meter Network have very high uptime.

### 'Vote More'

#### Is there minimum number of MTRG that I can add to an existing Vote ID? <a href="#a523" id="a523"></a>

No, there is no minimum no. of MTRG that the user can add to an existing Vote ID. User can add any amount to the Vote ID up to the MTRG available in the wallet.

### 'Undelegate' and 'Unbound'

#### Do I need to undelegate before unbounding? <a href="#id-5de0" id="id-5de0"></a>

No. Unbounding without Undelegating will enable users earn staking rewards during the unbound period of 1 week.

#### The unbound timer says ‘Matured x minutes ago’ but MTRG is still locked, should I unbound again? <a href="#e16d" id="e16d"></a>

No, MTRG is locked in staking until the end of current epoch when the unbound timer ends. This may take up to 1 hr depending on when the unbound timer has ended. Please wait until end of epoch to get the MTRG unlocked. Clicking ‘Unbound’ again will reset the timer to 7 days.


# Running a Full Node on Meter Mainnet

## Overview

Meter is a hybrid PoW and PoS blockchain system with dual chain structure. All the accounts and transactions are recorded on the PoS chain while PoW chain (currently a modified version of Bitcoin starting from the same genesis of Bitcoin) just maintains the crypto puzzles for mining. The PoW chain submits the solutions for the crypto puzzles to the PoS chain and the winning miners receive reward on their accounts on the PoS chain.

**Epoch:**

Meter operates on epochs, which are signaled by k-blocks (regular blocks are called m-blocks). At the end of epoch, the committee nodes vote on the longest PoW chain and distribute mining rewards to all the PoW miners, it also pass the information to the PoW chain and all the PoW miners will have to start mining for the stamped PoW block. To create a k-block, the PoW chain typically has to have more than 60 blocks. Since the average PoW block period is 1 minute, each epoch is therefore around 1 hour (currently the time for epoch is completely decided by PoW, but we will implement cross interactions for epoch adjustments in the future). All system financial related activities like reward distribution, entering and exiting the delegate node pool only happen at k-blocks.

It is also required to run both PoS and PoW processes on the same physical or virtual machine to ensure security.

In Meter, there are several types of full nodes in the network:

1. **Regular full node:** They sync for each block and can support interactions with wallets
2. **Delegate nodes:** These nodes are candidates for the committee nodes and have opportunity to propose and sign blocks. To become a delegate node, the top N (N is a protocol parameter) staked full nodes(including both self staking and votes from other stakers) are the delegate nodes.
3. **Committee nodes:** A random subset of the delegate nodes are selected for every epoch. These nodes form a committee quorum and perform consensus. The committee nodes take turns to propose blocks. If a proposed block receives endorsement signatures from 2/3 of nodes in the committee, the signatures form a QC (Quorum Certificate). Each newly proposed block carries QC for the previous block. Once the newly proposed block obtains a QC, the previous block is considered as confirmed and finalized.

In the initial launch of the main net. The number of Delegate Nodes will be the same as the number of the committee nodes, which are set at 500.

Requirements for running a delegate/committee node: To achieve the full performance of the Meter network, the recommended hardware configuration is more than 8 compute optimized vCPU, 16GB of memory, and 200GB of SSD (AWS c5.2xlarge instance or better). The maximum block size in Meter is around 1.3MB. It is also recommended to have data center class 1Gbps to 10Gbps internet connection. However the Meter consensus protocol is capable of adapting to transaction load, network, and node processing speed to some extent by varying the block period from 2 sec to up to 30 sec. The minimum requirement is 2 vCPU and 8GB of memory. Currently, the average monthly block data is around 1.7GB.

## Tutorials (Community Version)

This [step by step tutorial](https://medium.com/@Paolo_G/step-by-step-guide-to-creating-a-node-in-meter-mainnet-4cdde1085fbb) on how to setup a full node and validator for Meter was created by a community member. The following guide is officially maintained.

This [setup tool](https://github.com/daveodwyer/meter-node-creator) is created by the community for doing everything for you on a Ubuntu Linux machine.  There is also a [telegram group](https://t.me/joinchat/as-AgBXmUAxjMDA0) with automatic alerts and helps from the community.

## Setting up Docker

Since Meter full node consists of multiple processes, we packaged the entire node to a docker container image. The following instructions assume Ubuntu Linux.  It is recommended to use the latest Ubuntu LTS version for building the node.  If you are using Windows, you could [install WSL2](https://docs.microsoft.com/en-us/windows/wsl/install-win10) with an Ubuntu image. Please refer to [Ubuntu Docker Installation Guide](https://phoenixnap.com/kb/how-to-install-docker-on-ubuntu-18-04) for adding Docker support on Ubuntu.  **The current docker image release requires docker version higher than  20.10.12 (default in fully updated Ubuntu 20 or Ubuntu 22).**

On Ubuntu, you could use the following commands to install docker

```
sudo apt update
sudo apt install docker.io
```

By default, if you installed docker through apt install, it requires root user privilege to run. However, this may introduce security concerns. It is actually pretty simple to run Docker as non-root user.

Setup Docker usergroup to run Docker as non-root user. We assumed the non-root user that will be running docker is "ubuntu", please change the commands accordingly if you are using a different user.

```
sudo groupadd docker
sudo usermod -aG docker ubuntu
```

After this, please logout and log back in to refresh the user group setting and you will be ready to go.

## Setting up a full node

1. Download the latest [desktop wallet](https://www.meter.io/wallets/)
2. Prepare host working directory for Meter Docker container It is recommended to have a host working directory for the container to save important keys and block database, so we could retain them in future upgrades. We will create a directory called meter-data and set its path to and environment variable called **METER\_MAIN\_DATA\_PATH** (you will have to modify accordingly if you have a different directory structure) and map it to the /pos directory inside the container.
3. Prepare a clean working directory

```
$ mkdir meter_main_data
$ cd meter_main_data/
$ echo export "METER_MAIN_DATA_PATH=$PWD" >> ~/.bashrc
$ source ~/.bashrc
```

1. Launch the Meter container

**The following instructions assume the user operates in METER\_MAIN\_DATA\_PATH. Please pay attention to the parameters in the commands and replace the path accordingly to your environment, especially the path after -v in docker run commands**.

```
docker run --network host --name meter_main --restart always -e NETWORK="main" -v $METER_MAIN_DATA_PATH:/pos -d meterio/mainnet:latest
```

1. Check that container is actually working

```
docker container ls -a
```

The output will be like the following:

```
CONTAINER ID        IMAGE                      COMMAND                  CREATED             STATUS              PORTS               NAMES
260bbd571d1a        meterio/mainnet           "/usr/bin/supervisord"   23 hours ago        Up 23 hours                             meter_main
```

```
docker container stop meter_main              //stop the container
docker container start meter_main             //start the container
docker container rm meter_main                //remove the container
docker image ls
docker image rm [image ID]                   //remove the container image, will trigger redownloading the image at the next docker run, it is recommended to do this every time we upgrade the testnet
docker container exec -it meter_main bash     //launch a bash in the container
```

The log files can be located inside the container, under /var/log/supervisor directory. If you file any bugs, please remember to attach the logs for PoS (both the stderr and stdout) in the bug. You could either copy and paste the log or use

```
docker cp meter_main:/var/log/supervisor/[LogFileNameHere]     //replace with the log file name
```

After confirming the node is running properly through the log, you could then connect the desktop wallet to your own full node.

## Fast Syncing from a snapshot

The previous commands will start a full node syncing from scratch which may take several days.  The fully synced node contains entire history of the Meter blockchain and is an achieved node.  If you want to sync faster and reduce the usage of your hard disk or if you are running a validator node and running low on disk space, you could sync from a snapshot using the following commands (this requires taking the node offline for about 1 hour depending on your network connection speed):

```
$ sudo docker container stop meter_main  //stop the meter container to replace the database
$ cd $METER_MAIN_DATA_PATH  //enter the meter_main_data directory
$ sudo rm -rf instance-e695c63b238f5e52  //remove the database directory
$ wget https://snapshot.meter.io/instance-pruned-mainnet-63742946.tar.gz  //this is a prebuilt snapshot of the pruned database
$ tar -xvf instance-pruned-mainnet-63742946.tar.gz
$ rm instance-pruned-mainnet-63742946.tar.gz
$ sudo docker container start meter_main  //restart the meter container
```

## Pruning the database

If you are running low on diskspace and could not expand the disk volume easily, you could choose to prune the Meter blockchain database to reduce the disk usage.  The pruning process however will require taking the node offline and may take a few days if you are pruning from the genesis of the blockchain.  It maybe faster to copy from a snapshot using the instructions in the previous section.

```
$ sudo docker container stop meter_main  //stop the meter container to replace the database
$ sudo docker run --network host --name meter_pruning -it -v $METER_MAIN_DATA_PATH:/pos --entrypoint=/usr/bin/meter -d meterio/mainnet --network main --data-dir /pos --enable-pruning --no-discover 
// To check if pruning completes
$ sudo docker logs --tail=100 -f meter_pruning  
//once pruning completes, you should see "state pruning loop completed"
$ sudo docker container stop meter_pruning  //stop pruning container
$ sudo docker container start meter_main //restart meter container
```

## Track node sync status

You can compare the height of your running node with the [Explorer](http://scan.meter.io/) maintained by the team

1. Use <http://IPaddrOfYourNode:8670/probe> to check the current sync status and configurations of your node.  Compare "bestBlock" with the most recent block number in the [Explorer](https://scan.meter.io).
2. If you installed the [Meter desktop wallet](https://meter.io/wallets), you could point it to your own full node: In the settings of the wallet, under node, you could and connect add your own full node by adding <http://IPaddrOfYourNode:8669> . The icon in the left of the address bar should turn green if everything is running properly. You could use the explorer inside the wallet to look at the status of the block productions.&#x20;

[![Adding Your Node in Wallet Settings](https://github.com/meterio/mainnet_docs/raw/master/addnode.png)](https://github.com/meterio/mainnet_docs/blob/master/addnode.png) [![Connecting to Your Node](https://github.com/meterio/mainnet_docs/raw/master/connectnode.png)](https://github.com/meterio/mainnet_docs/blob/master/connectnode.png)

Please make sure the block height in the wallet is the same as the [official block explorer](https://scan.meter.io).

## Upgrade a full node automatically

Since the mainnet just launches, we expect there could be urgent upgrades from time to time. To ease the node operator's work, we have provided an automatic upgrade service called watchtower. It periodically pulls the docker container image releases and upgrades accordingly. For non-professional validators who can not monitor the node 24/7, **we highly recommend using the watchtower service.**

```
sudo docker rm -f watchtower  #remove the old watchtower version if you had it running
sudo docker run -d --name watchtower --restart always -v /var/run/docker.sock:/var/run/docker.sock nickfedor/watchtower:latest --include-stopped --revive-stopped --enable-lifecycle-hooks --interval 10 --cleanup meter_main
```

## Upgrade a full node manually

Stop and remove the current CONTAINER

```
docker container rm -f meter_main
```

Pull the latest container image

```
docker pull meterio/mainnet:latest
```

Start the new image

```
docker run --network host --name meter_main --restart always -e NETWORK="main" -v $METER_MAIN_DATA_PATH:/pos -d meterio/mainnet:latest
```


# Configure the Full Node to Validator Node

After you Successfully starting a full node, you may want to run a validator node on the network.  **Please make sure the block height on your node (<http://IPofYourNode:8670/probe>) is the same as the** [**official block explorer**](https://scan.meter.io) **before proceeding.**  It may take a long time to sync all the data on the mainnet depending on your network bandwidth and CPU power.

## Become a delegate (Validator) node

Becoming a delegate node requires staking MTRG tokens. You will also need a little MTR to pay for transaction fees.

1. **Configure network ports for your node.**&#x20;

It is recommended to have a public IP address if you want to become a delegate node and have the following ports open for inbound TCP connections on your firewall or cloud network security group.

| Port Range | Functions                              |
| ---------- | -------------------------------------- |
| 9209       | PoW P2P (required)                     |
| 8332       | PoW API                                |
| 8669       | Wallet RESTful API                     |
| 8670-8671  | PoW/PoS Messages (required)            |
| 55555      | Discovery Server                       |
| 11235      | PoS P2P (required)                     |
| 8545       | Ethereum Compatible http RPC interface |
| 8546       | Ethereum Compatible ws RPC interface   |
| 9100       | node explorers                         |

&#x20; **2. Elect your node to be a candidate In Meter Wallet**

In the [Staking portal](https://staking.meter.io), you could self-elect to be a candidate for delegate node by creating a "New Candidate" and stake at least 2000 MTRG tokens.  The "New Candidate" dialogue box collects all the required information for your node. You will have to name your validator, put in the IP address of your node, select whether you want to system to automatically participate in the on-chain MTRG auction (enable autobid) and also submit the public key used to sign the block proposals (**this is the BLS key for the node running the validator, you could find the key in $METER\_MAIN\_DATA\_PATH/public.key** file, its corresponding private key is in the master.key file)&#x20;

At launch, there is a 500 delegator nodes limit, which means only the top 500 candidate nodes will be selected as delegates to participate in the consensus.  You could have other accounts delegate their votes to you as well to increase the chance of becoming a delegate node. The candidate transaction is recorded immediately and the node could start to receive votes. However, the votes won't be counted until the next k-block even with enough votes. You could check the list of candidate nodes through the [Staking Portal](https://staking.meter.io) or [Meter scan](https://scan.meter.io).

The votes for each validator automatically increase at 5% annualized rate to encourage validators to stay in long term. if you uncandidate and recandidate, you will lose these bonus votes. Whenever you uncandidate or unbound, it will take one week before the tokens become unbounded and transferrable.

Please be aware that the public.key file in the docker container is generated when the container is launched. If you start a container from scratch, the public.key will be different from the one you used for the "Candidate" transaction. You could either "Uncandidate" and "Candidate" again with the new public key or change the public key to the one you used before.

Your node will automatically pick up by our [Meter Scan](https://scan.meter.io) once you successfully become a candidate.

**Please be aware that the candidate transaction requires tokens that are not staked**. Please use the Update button in the candidate tab for changes.  If you uncandidate your node, the staked token will be unbounded and available for withdraw after 7 days.

If a candidate receives enough votes and ranked in the top 500, it will become a delegate node. You could find the list of delegates at <http://mainnet.meter.io/staking/delegates>

## Jailing

Meter has a variable block period with a minimum of 2 seconds.  For every block, a validator node in the active consensus committee is selected randomly to be the leader to propose and gather votes.  If the node fails to propose the block, the committee will fall to the next node.  Therefore, a misbehaving node may introduce a time out in the network.  To remove misbehaving nodes from the consensus group, we introduced a jailing mechanism.  If a node misses more than two proposals in 2 epochs in the past 8 epochs, double signs or fail to start an epoch, it will be jailed (or removed from the consensus group).  The cost of bailing out a node on the main net is 10 MTRG. &#x20;

You could bail out a candidate from the [staking portal](https://staking.meter.io), select the jailed candidate and then find "Bail Out" from the three dots on your candidate row.  You could only bail out a candidate from the candidate's own wallet.

## Uncandidate

If you no longer want to validate in the network, you will have to choose Uncandidate in the Meter wallet first.  **Keep the node running until the end of an epoch (about 1 hour) before turning it off to avoid impacting the network performance.**


# Meter Incentive Programs to promote decentralization

The year 2022 served as a stark reminder to the pressing need of decentralization and decentralized finance — the heart of web3 ecosystem!

At Meter, the Meter Foundation strongly believes in creating a decentralized Meter network and have taken concrete steps to fulfil this obligation to our community through numerous incentive programs. &#x20;

**The incentive programs are aimed to;**

1. **Promote higher decentralization to ensure liveness and security of the Meter ecosystem thereby cementing our claim of the most decentralized side-chain scaling solution**
2. **Showcase the efficacy of the ‘HotStuff Consensus’ by maintaining the speed and performance of the ecosystem while supporting a higher number of nodes**

## Meter Ecosystem - Roadmap to 500 Nodes

Program Link: <https://forum.meter.io/t/meter-ecosystem-roadmap-to-500-nodes/190>

Under this program, Meter Foundation provides MTRG delegations to every node setup until we reach the first milestone of 500 nodes.

&#x20;

<figure><img src="/files/d90NPKawxi6VPbmLqJTs" alt=""><figcaption></figcaption></figure>

This program was critical in increasing the validator node count from 150 to over 280 in 2022.

### Actual Returns of a node

Below are the actual returns of a node with 22,500 MTRG Delegation and with a Tesla NFT delegation of 50,000 MTRG.&#x20;

<figure><img src="/files/ABvVH9hqL23bZJ9wprda" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/3hbpRgusGKTbIy0psce4" alt=""><figcaption></figcaption></figure>

**IMPORTANT UPDATE**

Tesla Validator NFTs are moved to Meter Network post this announcement - [TESLA Founding Validator NFTs returning to Meter Network! ](https://medium.com/meter-io/tesla-founding-validator-nfts-returning-to-meter-network-efdafa30476d)

<figure><img src="/files/Lz6mFpd9FyyVwCdNOdPF" alt=""><figcaption></figcaption></figure>

<mark style="color:red;">**Post 30 April 2023, Tesla Founding Validator NFTs on Ethereum Network will cease to have utility or value.**</mark>

## MIP: Incentivizing TVL and Node Operations through Meter Foundation Node Delegation

Program Link: <https://forum.meter.io/t/mip-incentivizing-tvl-and-node-operations-through-meter-foundation-node-delegation/309>

Meter Node Operators are the core community and the strongest supporters of the Meter Ecosystem. With this proposal, we aim to generate higher TVL on the network through our core community while providing adequate incentives to do so.

<figure><img src="/files/XmAA7C7uaYxT3ZamlCOJ" alt=""><figcaption></figcaption></figure>

## Leveraging DeFI Ecosystem to benefit from Incentive Programs

DeFI users can leverage Meter DeFI ecosystem to benefit from Node Incentive programs without diluting their stablecoin positions.

<figure><img src="/files/NtFBfCP64sStOY8oIONl" alt=""><figcaption></figcaption></figure>

Detailed interest gap strategy can be found on Medium: '[**METER UP your Stablecoin yield**](https://medium.com/meter-io/meter-up-your-stablecoin-yield-on-meter-network-3e382ca10699)**'**


# Meter Mining Guide

In the Meter ecosystem, MTR is created by SHA256 based PoW mining similar to Bitcoin.  Therefore miners are always facing the dilemma of whether it makes more economic sense to mine MTR or mine BTC and use the BTC to buy MTR instead.  To help miners make such decisions, we created a cost-parity and made it available on the [PoW page of Meter Explorer](https://scan.meter.io/pow).   The cost parity uses the current Bitcoin hashrate and market price to calculate the break-even price for MTR for PoW mining.  In reality, you will also have to consider the amount of MTR you were trying to obtain and the market depth to make an intelligent decision.

## How to Mine

Generally speaking, miners may choose to operate their own SHA256 mining equipment, and gain all the rewards for their efforts, or join together with others in a mining pool and share the rewards (see [What is a Mining Pool](/mining/meter-mining-guide#what-is-a-mining-pool)). In some cases people can subscribe to a pool and gain some of the rewards, but without owning any equipment of their own. This is called cloud mining. Each has its own benefits and drawbacks, and it is up to each person to determine which approach suits them best.

## What is a Mining Pool?

When miners group together to use their combined processing power, this is called a mining pool. The rewards from mining are split proportionally according to the amount of hash power miners contribute to the pool.

Mining pools can be split into both public and private. Public pools will generally charge a fee.

Mining is strictly voluntary, and as such miners can opt to switch their mining capabilities whenever they choose, according to their own objectives or criteria. For example, if a miner that traditionally was in a Bitcoin mining pool decided to divert some or all processing power to mine another blockchain, such as Meter, it is simply a case of making a few minor configuration changes to point the mining equipment to the new pool.

## Mining Hardware

ASIC miners are specialized hardware machines that are required to efficiently mine Meter.

Since Meter uses SHA256, the same as Bitcoin, miners can use the same hardware for mining both coins, and the mining setup for the two is very similar.

#### Hardware Setup Guide <a href="#hardware-setup-guide" id="hardware-setup-guide"></a>

Meter uses an account-based system, rather than the UTXO based method that Bitcoin uses. However, this difference only amounts to a small change that needs to be made in the configuration.

Follow [this guide](https://www.bitcoin.com/get-started/how-to-setup-a-bitcoin-asic-miner-and-what-they-are) on installing and configuring your ASICs.

## The Meter Solo Mining Pool

Meter is actively working with mining pool providers for future mining support. We have provided a [mining pool sample implementation](https://github.com/meterio/meter-nomp). This implementation can be used for solo mining, but is by no means a general purpose mining pool as it doesn't have reward distribution mechanism.

The following are the rough production parameters for different mining hardware on the Meter testnet, tuned to 1 meter = 10 kwh for a miner with 53 W/T energy efficiency. The system has a built-in smooth curve that will reduce this parameter by half every 18months. Daily MTR production per TH/s is 0.123 when the mainnet launches initially and will go down each day.

The adaption speed to hash rate changes is still relatively slow on the testnet. However, closer to the mainnet launch, parameters will be tuned to more efficient mining hardware and faster response speed.

The Meter mining pool status statistics can be viewed at <http://pool\\_ip:8088/stats>.

### Miner Configurations

To configure a miner to join the mining pool, the following fields in the `Miner configuration` tab of the ASIC's web panel needs to be set:

![S9 Configuration](/files/-MM2kpgv3DPNLwvCFFmr)

Where:

* `URL` is the address of the mining pool.
* `Worker` is the Meter wallet address.
* `Password` is the password associated with the wallet.

## Shared Mining Pool&#x20;

The meter team has setup a test mining pool on the Meter mainnet.  A user could set the miner URL to; \
\
<http://pool.meter.io:3256>\
\
The pool pays out every 24 hours if the mining proceeds are greater than the transaction fees.  The pool charges 3% commission. &#x20;

## Running a Private Mining Pool on the Meter Network

An example implementation of the Meter mining pool is available on [GitHub](https://github.com/meterio/meter-nomp), based on the open source nomp Bitcoin mining pool. This code has been provided to show the changes needed compared to standard bitcoin mining pools, and is not intended to be used in a production environment.

### Requirements

There are three things required to run Meter nomp:&#x20;

1. Node.js
2. A database (Redis),&#x20;
3. A connection to a coin daemon on the Meter Network, which is a Meter full node that monitors transactions on both the Meter PoW and PoS chains.

Normally a pool operator would operate a full node for stability and availability.

In Ubuntu, you could use the following command to install nodejs and Redis:

```
$ sudo apt install npm
$ sudo apt install nodejs
$ sudo apt install redis
```

**Important Warning!** It is always a good idea to learn about and understand any software that you are using. An important security measure to implement for nomp is to secure the database so it cannot be accessed externally. An easy way to do this for Redis is to include `bind 127.0.0.1` in your `redis.conf` file, and use a firewall with strict rules in place to only allow accessing Redis locally. For more information please read [Security](http://redis.io/topics/security). Another good place to start for additional information about using Redis for nomp is [Data Persistence](http://redis.io/topics/persistence).

### Downloading & Installing

Clone the repository and run `npm update` for all the dependencies to be installed:

```
git clone https://github.com/meterio/meter-nomp.git
cd meter-nomp
npm install
```

### Pool Configuration

There is a json config file `meter.json` in the `pool_configs` sub-directory. Make sure to configure the appropriate fields in this file, especially the `rewardBeneficiary` and the `daemon`/`daemons` fields.

In the sample meter.json file, the pool owner's Meter address is 0x0a05c2d862ca051010698b69b54278cbaf945ccb, which is configured as `rewardBeneficiary` . In addition, the mining pool has to connect to a coin daemon (full node) which is configured in the `daemons` section:

```
[
    {
        "host": "c04.meter.io",
        "port": 8332,
        "user": "testuser",
        "password": "testpass"
    }
]
```

c04.meter.io is a node we provided for testing only, its availability is not guaranteed. If you are running a pool, you should be running a full node on Meter mainnet (Please refer to the mainnet full node tutorial on Github).

There are many other fields in `meter.json`. We could ignore them for now as only limited functions were ported in the current Nomp implementation for Meter.

For more information on these configuration options see the [pool module documentation](https://github.com/meterio/meter-stratum-pool/blob/master/README.md#module-usage).

### Start the Portal

After all the configuration files have been set up, it is time to start the mining pool.

If everything is installed locally on the host, initiate using the following:

```
$ node init.js
```

The pool should now start running and we could see the status of the pool from the log and <http://pool\\_ip:8080/stats>.

###


# Meter Community NFTs

Nikola Tesla Foundation Validators

100 in Total.  Serves as acceleration cards for future liquidity mining.

![Nikola Test Founding Validators](/files/-MXs3V38GCFabtRsyiqY)

{% file src="/files/-MXs3IfVOBe4y8Nmyx6G" %}


# Meter Developer Incentives

Meter takes a holistic approach towards incentivizing developers deploying on the Meter Network.

| Program                            | Type of Grant                           | Program Budget                           | Program Duration                                 | Key Performance Criteria                                                                                                      |
| ---------------------------------- | --------------------------------------- | ---------------------------------------- | ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------- |
| **Meter Developer Grant Program**  | Approval based Grant                    | 10 Million USD                           | NA                                               | <p>Generate Transaction Volume </p><p></p><p>Attract TVL </p><p></p><p>Attract new users </p><p></p><p>Fill Ecosystem Gap</p> |
| **Meter TVL Incentive Program**    | Open for all Projects which support TVL | Currently uncapped                       | Review post 25 Million TVL or 1 year post launch | TVL                                                                                                                           |
| **Meter Gas Monetization Program** | Gas Rebates, Open for all Projects      | Currently uncapped                       | Review 1 year post launch                        | Generate Transaction Volume                                                                                                   |
| **Meter Co-Marketing Program**     | Monthly Approval based Grant            | Budget based on Social Footprint of dapp | No limit. Subject to change based on efficacy    | NA                                                                                                                            |
| **Meter DAPP Referral Program**    | Milestone based grant for community     | Currently uncapped                       | No limit. Subject to change based on efficacy    | NA                                                                                                                            |

{% content-ref url="/pages/f56hZ85JPKYkaUjLO9c8" %}
[Meter Developer Grant Program](/developer-documentation/meter-developer-incentives/meter-developer-grant-program)
{% endcontent-ref %}

{% content-ref url="/pages/Zq5WU15y1TGzOYs3EOQR" %}
[Meter TVL Incentive Program](/developer-documentation/meter-developer-incentives/meter-tvl-incentive-program)
{% endcontent-ref %}

{% content-ref url="/pages/WhfX641hZGrcxIB7g4O4" %}
[Meter Gas Monetization Program](/developer-documentation/meter-developer-incentives/meter-gas-monetization-program)
{% endcontent-ref %}

{% content-ref url="/pages/HbtdaWPcqSe0eIYiCKtI" %}
[Meter Co-marketing Program](/developer-documentation/meter-developer-incentives/meter-co-marketing-program)
{% endcontent-ref %}

{% content-ref url="/pages/1PKTp0GLKMcuC5mycRwL" %}
[Meter DAPP Referral Program](/developer-documentation/meter-developer-incentives/meter-dapp-referral-program)
{% endcontent-ref %}


# Meter Developer Grant Program

[Apply here.](https://forms.gle/qnJ2eNagGCRefwQ17)

* [x] This program is an approval based Grant.
* [x] This program can be leveraged in conjunction with 'Meter TVL Incentive Program'
* [x] This program can be leveraged in conjunction with 'Meter Gas Monetization Program'

## Core Objective

The core objective of the Meter Developer Grant program is growth and adoption of Meter Network as a public goods platform.&#x20;

## Key Performance Criteria to choose a recipient

The key performance indicators that drive the decision-making in providing grant to a project/ recipient are;

1. Ability to generate transaction volume on Meter Network
2. Ability to attract TVL on Meter Network
3. Ability to attract new user to Meter Network
4. Fill gap in the current Meter Ecosystem needs

## Overall Budget for the Program

The overall budget for the ‘Meter Developer Grant Program’ is 10 Million USD in its current phase. The funding for the program will be sourced from MTRG reserved for ecosystem and future products ([Tokenomics paper](https://docsend.com/view/pubkivhipjgsqdn8)).&#x20;

## Key Categories

The overarching goal of the Grant Program is adoption of Meter Network and increase in network activity. We would review any project which fits the overarching goal.&#x20;

In cognizance of the current state of Meter Ecosystem, Meter Foundation is more inclined to below categories of projects;

1. DeFI Protocols (Derivatives, Lending, Stablecoin Solutions, Insurance, Yield Optimizers, Reserve Currency)
2. Gaming (P2E, Move to Earn, Metaverse, GameFI etc.)
3. NFT (Collections, Mint tooling, Marketplace etc.)
4. DEX (AMMs with farms)
5. IDO Application
6. DAO and DAO Tooling (Voting tools, tokenized gates, investment tools)
7. Tooling, Infrastructure and Integrations

Meter Foundation will support any type of deployment through the grant program (New development, Port from Other Network, Fork of established protocol)

## Grant Estimate across Key Categories

Meter foundation is primarily interested in projects that align to the key performance criteria mentioned earlier. Based on our experience, below are the key performance criteria and grant estimates across different categories (detailed above):

| Key Category                             | Performance Criteria | Grant Estimate   | Additional Incentives                          |
| ---------------------------------------- | -------------------- | ---------------- | ---------------------------------------------- |
| DeFI Protocols                           | TVL                  | Up to 50,000 USD | 3 months of liquidity incentives (MTRG)        |
| Gaming                                   | MAU                  | Up to 50,000 USD | 3 months of user acquisition incentives (MTRG) |
| NFT                                      | Unique Address Mints | Up to 10,000 USD | Past Success on other ecosystems               |
| DEX (AMMs with farms)                    | TVL                  | Up to 50,000 USD | 3 months of liquidity incentives (MTRG)        |
| IDO Application                          | Launches             | Up to 50,000 USD | -                                              |
| DAO and DAO Tooling                      | MAU                  | Up to 20,000 USD | -                                              |
| Tooling, Infrastructure and Integrations | Ecosystem Gap        | Up to 20,000 USD | -                                              |

## Requirements

Please fill out this application form diligently - <https://forms.gle/qnJ2eNagGCRefwQ17>

If you have not heard from us in 30 days, please reach out to @xiaohanzhu or @sg\_meter on Telegram.


# Meter TVL Incentive Program

[Register here.](https://forms.gle/TcLb1gnEdtaibgmx8)

Forum Discussion: [Link](https://forum.meter.io/t/meter-up-tvl-incentive-program-on-meter-network/315)

Governance Proposal: [Link](https://snapshot.org/#/meter-mainnet.eth/proposal/0x73820a0fd8e6e3af7fe4827f65267e82d6c15fbe973c136ff5548df2921d7980)

* [x] This program is a non-approval based incentive program.
* [x] This program can be leveraged in conjunction with 'Meter Developer Grant Program'
* [x] This program cannot be used in conjunction with 'Meter Gas Monetization Program'

## Core Objective

As with the ‘Meter Developer Grant Program’, the core objective of the Meter Up TVL Incentive program is growth and adoption of Meter Network as a public goods platform.&#x20;

## Key Performance Criteria to choose a recipient

We at Meter Foundation understand that success of Meter Network is a byproduct of the success of the dApps deployed on the Network. This program aims to share the burden of adoption by incentivizing TVL ON ALL DAPPS (meeting operational requirements specified below) deployed on the network.&#x20;

## Program Incentives

| TVL                                                            | APR  | TVL Source | Method                                           |
| -------------------------------------------------------------- | ---- | ---------- | ------------------------------------------------ |
| MTRG pairs with Blue chip Assets (Top 30 assets by market cap) | 10%  | Defillama  | Time weighted average of TVL over the past month |
| All Other TVL                                                  | 7.5% | Defillama  | Time weighted average of TVL over the past month |

Builders can use the rewards to internalize profits or use as liquidity incentives back to users.&#x20;

As all rewards are directly correlated to TVL, we anticipate users to be fairly incentivized by the dApps. MTRG incentives will be over and above any incentives provided by the dApps.

## Program Terms and Eligibility

1. Register their protocol with DeFi Llama (<https://defillama.com/>) to track the TVL. Only TVL mentioned on Defillama will be used. Usage will be calculated by the time-weighted total value locked (TVL) of the protocol.
   * In case of change in key contracts, it is the responsibility of the project team to update the information on Defillama. Requests to consider TVL not updated on Defillama will not be reviewed. We will make no exception to this rule to reduce operational overheads
   * To ensure builders do not game the program, we reserve the right to waive incentives for non-qualified TVL.&#x20;
2. Project should be deployed on the Meter Network at the time of the monthly distribution
3. Projects should have a minimum TVL of US$10,000 at the time of distribution

## Overall Duration for the Program

The MTRG incentives will be reviewed when the total TVL reaches 25 Million or at the end of 1 year post launch of the program (whichever is earlier).

## Key Categories

As the program incentivizes TVL on the network; naturally, categories of dApps supporting TVL are only applicable. They are;

1. DeFI Protocols (Derivatives, Lending, Stablecoin Solutions, Insurance, Yield Optimizers, Reserve Currency)
2. Gaming (P2E, Move to Earn, Metaverse, GameFI etc.) – where applicable&#x20;
3. DEX (AMMs with farms)

Categories not mentioned but supporting TVL would also be incentivized.

## MTRG Incentive Distribution

1. MTRG Rewards are distributed at the end of every month to each protocol’s \`Deployer Address’ submitted in the ‘Meter Up’ Registration Form ([Link](https://forms.gle/TcLb1gnEdtaibgmx8)).
2. Incentives will be distributed in the beginning of the month based on TVL reported

### Example

**Projected Rewards** = Project time-weighted-average TVL of MTRG pairs with blue chip assets x 10% + Project time-weighted-average TVL x 7.5%

Project time-weighted-average TVL of MTRG pairs with blue chip assets = $2,000,000

All other Project time-weighted-average TVL = $5,000,000

**Projected Annual Rewards** = 2 Million USD x 10% + 5 Million USD x 7.5% = 0.575 Million USD

**Projected Monthly Rewards** = 47,920 USD

**Rewards may vary based on the price of MTRG**. Builders can use the rewards to internalize profits or use as liquidity incentives back to users.

## Requirements

‘Meter Up’ TVL Incentive Program Registration Form - <https://forms.gle/TcLb1gnEdtaibgmx8>&#x20;

If you have not heard from us in 5 days, please reach out to @xiaohanzhu or @sg\_meter on Telegram.


# Meter Gas Monetization Program

[Register here.](https://docs.google.com/forms/d/e/1FAIpQLSfmrwF0beI3ULUS2RxbnWfmfVZih9OEqDtkErCHA97SeXj5PA/viewform)

Forum Discussion: [Link](https://forum.meter.io/t/mip-meter-gas-monetization-program/319)

Governance Proposal: [Link](https://snapshot.org/#/meter-mainnet.eth/proposal/0xf4961989316151e2f11051681998d60917f9650b56f49c407dbf0773b49c2496)

* [x] This program is a non-approval based incentive program.
* [x] This program can be leveraged in conjunction with 'Meter Developer Grant Program'
* [x] This program cannot be used in conjunction with 'Meter TVL Incentive Program'

## Core Objective

As an extension to the TVL Incentive Program, the Gas Monetization Program aims to support 2 other key network adoption metrics for Meter – Transaction Volume and User base!

## Key Performance Criteria to choose a recipient

The Gas Monetization Program is open to all applications which have more than minimum gas rebate specified for the program of 100 MTR.

## Program Incentives

The gas monetization incentive program will reimburse a PORTION of all gas fees incurred on the Meter Network by the dApp smart contracts.

<figure><img src="/files/dWcYAkA7g2xGuzuhPrQq" alt="" width="398"><figcaption></figcaption></figure>

Builders can use the rewards to internalize profits or use as incentives back to users.&#x20;

### Important Considerations

1. Fee reimbursements will be done monthly based on on-chain contract data
2. The DAU and transaction count will be averaged over the previous month to distribute the rewards
   * e.g. Monthly Unique Accounts interacting with the dApp = 15,000. Thus Daily Average = 500
3. The metrics will be summed over all the contracts deployed by the dApp
4. All payments will be done in MTRG based on exchange rate (MTR to MTRG) on the date of distribution

## Program Terms and Eligibility

1. The dApp should be deployed on Meter Network for >1 month.
   * e.g. If the dApp is deployed on May 11, it will be eligible for the program on June 30 distribution
2. The dev team of the dApp should fill out the google form to specify all contracts related to the dApp
   * [Meter Gas Monetization Program](https://forms.gle/DcsS7SKT5efwuXms7)
3. dApps can apply for one of the 2 programs but not both:
   * METER UP TVL Incentive Program or
   * Meter Gas Monetization Program
4. dApps enjoying benefit of grant for gasless transactions (in future) will not be eligible for the Gas Monetization program

This program is still in nascency across the blockchain ecosystem, the Meter Foundation reserves the right to halt any payment stream indefinitely for any reason, including if fraudulent user activity is suspected or if the Foundation believes it is in the best interests of the Meter ecosystem.

The program will also be reviewed periodically for efficacy.

## Overall Duration for the Program

The Gas Monetization incentives will be reviewed periodically over the 1 year post launch of the program for efficacy. Any change will go through governance process.

## Key Categories

The program incentivizes transaction Volume and user base on the network. Though the program is more relevant to GameFI dapps, all categories can leverage the program.

1. DeFI Protocols (Derivatives, Lending, Stablecoin Solutions, Insurance, Yield Optimizers, Reserve Currency)
2. Gaming (P2E, Move to Earn, Metaverse, GameFI etc.)&#x20;
3. DEX (AMMs with farms)

## MTRG Incentive Distribution

1. MTRG Rewards are distributed at the end of every month to each protocol’s \`Deployer Address’ submitted in the Registration Form.
2. Incentives will be distributed in the beginning of the month based on on-chain transaction data&#x20;

### Example

<figure><img src="/files/jd2YssMU7i0CW4K3fsFa" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/4Lhm5pltT12UQSTdlRUR" alt="" width="360"><figcaption></figcaption></figure>

**Note:** The example assumes a certain average gas cost. Actual gas costs will determine the extent of gas monetization.

If you have not heard from us in 5 days, please reach out to @xiaohanzhu or @sg\_meter on Telegram.


# Meter Co-marketing Program

Reach out to @ALOMETER on Telegram for more info and support&#x20;

Blog: [Link](https://medium.com/meter-io/meter-co-marketing-program-for-ecosystem-partners-33fa61df24af)

* [x] This program is a approval based incentive program.
* [x] Unutilized Monthly budget is not carried forward.
* [x] Distribution is solely to users directly from Meter based on allocated budget

## Core Objective

To combine the expertise, resources of Meter and its ecosystem partners to propel our shared vision forward, enabling us to jointly amplify our brand presence and foster our community.

## Program Incentives

The program aims **to empower our ecosystem partners to engage our communities collectively** through a monthly earmarked budget based on their social footprint.

<figure><img src="/files/CBT42P6T7BzXh8RbXTAQ" alt=""><figcaption></figcaption></figure>

The budget is exclusively for the community.

## Potential Ideas

Some of the incentivized strategies with the potential to amplify community engagement at Meter could be:

* Community generated educational content
* Social media campaigns, quizzes, learning series
* Collaborative marketing with other dApps
* Community events — AMAs, Twitter spaces

Our ecosystem partners have the liberty to develop more co-marketing activities that resonate with your community and align with our shared goals.

## Program Eligibility

Deployment on Meter Mainnet for >1 month and Twitter Footprint as mentioned earlier.

## Key Milestones for marketing events <a href="#b575" id="b575"></a>

1. Ecosystem partner should inform Meter Foundation about the scheduled event and portion of budget allocation to the event
2. Events should be publicized/ marketed **at least a week in advance**

> All comarketing campaigns should tag Meter appropriately across the social footprint of the campaign.

The Meter Foundation reserves the right to halt any payment stream indefinitely for any reason, including if the Foundation believes it is in the best interests of the Meter ecosystem.

## MTRG Incentive Distribution

1. Budget will be released to participating community members directly on completion of the event based on input from ecosystem partner

## Other Important Aspects

### Engagement Rate <a href="#id-8690" id="id-8690"></a>

Though we are aware that engagement cannot be guaranteed, we expect our ecosystem partners to make the best efforts to engage + recall. Meter will help amplify the event.

### Comarketing beyond campaign events <a href="#id-493a" id="id-493a"></a>

We believe in collective growth of both Meter and our ecosystem partner. We are committed to amplify our partners communications beyond this program with the exception of competitive partnerships. We would appreciate our ecosystem partners demonstrating a similar commitment.


# Meter DAPP Referral Program

Blog: [Link](https://medium.com/meter-io/meter-dapp-referral-program-7b2ff08e2923)

* [x] This program is a milestone based incentive program.
* [x] The incentives are result of referred DAPP getting a grant from 'Meter Developer Grant Program'

## Core Objective

To leverage the untapped potential of Meter Community by incentivizing the community to participate in onboarding DAPPs on to the Meter Network.

## Program Incentives

Any DAPP referred by the Community members or developers will be screened for eligibility for '[Meter Developer Grant Program](/developer-documentation/meter-developer-incentives/meter-developer-grant-program)'. Community member will receive referral incentives if DAPP is deemed eligible for the grant.

Incentives for DAPP referrals by the Meter Community will be;

> Minimum of:
>
> 750 USD or 5% of DAPP Upfront and Milestone Based Grant

The overall incentive is **capped to 3,000 USD** (or 60,000 USD project grant).

## Program Eligibility

The current focus of the program is limited to categories mentioned in the ‘Meter Developer Grant Program’ here — [Key Categories](https://docs.meter.io/developer-documentation/meter-developer-incentives/meter-developer-grant-program#key-categories).

## Key Milestones <a href="#b575" id="b575"></a>

1. Introduce the DAPP to Meter Foundation (setup Telegram or Discord Chat)
2. Meter Foundation evaluates the Grant prospects of the DAPP to reach to an agreement on the quantum of grant
3. The DAPP deploys on Meter Network
4. Meter Foundation releases the grant which is either Upfront Grant or Milestone Based Grant or Both
5. Meter Foundation releases referral grant to the community member

The Meter Foundation reserves the right to halt any payment stream indefinitely for any reason, including if the Foundation believes it is in the best interests of the Meter ecosystem.

## MTRG Incentive Distribution

1. The referral grant will be released along with the release of grant to the DAPP (upfront or milestone based)

All payments will be in MTRG based on exchange date on the date of distribution.


# Introduction to Developer Documentation

Meter is a DeFi infrastructure with a built-in, crypto-native, metastable currency called MTR. You can use Meter as a Layer 1 blockchain to build DeFi apps on top of, or as a highly-decentralized, high-performance side chain for Ethereum and other public chains.

**The current Ethereum version on Meter is 1.10.17**

There are two primary methods of interacting with Meter: Ethereum compatible RPC or Meter Native Restful APIs. This section describes the Ethereum compatible RPC interface and native Restful APIs are detailed [here](/developer-documentation/meterify-api).

## **1. Ethereum RPC**

In order to better support existing Ethereum dApp developers, we developed an Ethereum emulation mode for Meter. Through an addon module called webgear Meter nodes are able to understand Ethereum transaction format and support the standard Ethereum RPC interface. It is like using the Apple M1 silicon to run x86 applications with a 100x performance improvement. Developers are even able to use their preferred Ethereum development tools like `Remix`, `ethers.js` and `web3.js` to interact with Meter. Due to the limitations of the Ethereum RPC, not all Meter functionality is available in Ethereum emulation mode. In this mode, MTRG must be treated as a special ERC20 token via a system contract.

The other difference between Meter and Ethereum is that Meter removed the sequential nonce concept in Ethereum and uses a random number as nonce instead. The Ethereum emulation layer will automatically generate the random nonce, you will not be able to replace a transaction with the same nonce.

When interacting with Meter you must use "Injected Web3" in Remix alongside Metamask.

### **Testnet:**

Warringstakes Testnet Endpoints:

RPC: <https://rpctest.meter.io>

Websocket: [<mark style="color:blue;">wss://wstest.meter.io</mark>](wss://wstest.meter.io)

ChainID: 83

Currency Symbol: MTR

Explorer: <https://scan-warringstakes.meter.io>

*ERC20 System Interface:*

MTRG: 0x8a419ef4941355476cf04933e90bf3bbf2f73814

MTR: 0x4cb6cef87d8cadf966b455e8bd58fff32aba49d1

*Useful Contracts:*

Multi-call3(Official Deployment): 0xcA11bde05977b3631167028862bE2a173976CA11

WMTR: 0xfAC315d105E5A7fe2174B3EB1f95C257A9A5e271

**Faucet for Testnet:**

<https://faucet-warringstakes.meter.io/>

### **Mainnet:**

RPC Endpoint:

RPC:

Providers with high quality API key access:

<https://blockpi.io/> (<https://meter.blockpi.network/v1/rpc/public>)

<https://nownodes.io/meter-mtr>&#x20;

<https://pokt.network>

Free rate limited access:

<https://rpc.meter.io> (port 8545 on the mainnet docker)

<https://rpc-meter.jellypool.xyz> (community maintained)

Websocket:

[<mark style="color:blue;">wss://ws.meter.io</mark> ](wss://ws.meter.io)(port 8546 on the mainnet docker)

<https://blockpi.io/>&#x20;

<https://nownodes.io/meter-mtr>&#x20;

ChainID: 82

Currency Symbol: MTR

Explorer: <https://scan.meter.io>

*ERC20 System Interface:*

-MTRG: 0x228ebBeE999c6a7ad74A6130E81b12f9Fe237Ba3

-MTR (Optional): 0x687A6294D0D6d63e751A059bf1ca68E4AE7B13E2

*Useful Contracts:*

Multi-call3 (Official Deployment): 0xcA11bde05977b3631167028862bE2a173976CA11

WMTR: 0x160361ce13ec33C993b5cCA8f62B6864943eb083

List of Common ERC20 Tokens on Meter mainnet:

<https://github.com/meterio/token-list/blob/master/generated/meter-tokens.json>

## **2. Source Code Verification**

Meter explorer uses [Sourcify](https://github.com/ethereum/sourcify) to verify the onchain contracts' byte code is exactly the same as the source code. Verifying contracts also allows the explorer to properly decode smart contract transactions. There are various tools (for example Remix plugins) that help developers to verify on Sourcify.

The submission for source code can be either done through [Meter Explorer](https://scan.meter.io) or [Sourcify Portal](https://sourcify.dev/).&#x20;

Typically the fastest way to verify a solidity project build with Hardhat is to zip all the json files under the artifacts/build-info/ directory, upload the zip files to the [Sourcify Portal](https://sourcify.dev/), and select all the contracts to be verified.  If a contract is verified through the [Sourcify Portal](https://sourcify.dev/), you may have to interact with the contract tab on the explorer under the contract address page to force the Meter explorer to sync the verification status from Sourcify, otherwise it may take a few hours for the explorer to automatically pick up the information.

There are two levels of verification: 1. source code match and 2. both source code, metadata match. Source code match is considered the minimum for contract verification purposes.

The main difference between Sourcify and Etherscan verification is that Sourcify requires metadata to be uploaded for verification in addition to source code and byte code. Information on finding the metadata file is available in [Sourcify Documents](https://docs.sourcify.dev/docs/metadata/). Both the Meter Explorer and Sourcify website allow uploading zip file. If your file is too large, we recommend directly using the Sourcify website to upload multiple files. If you are using Truffle, sometimes after you upload the json file, Sourcify complains not able to find the corresponding find .sol files in your local file path. You could try zip all the contract source code in a file and upload to Sourcify website. It will typically resolve the issue. From time to time, Sourcify may have problem recognizing files uploaded from Windows computers. You could try using a Mac to upload the files.

## **3. Multisig Wallet**

Meter team has deployed a forked UI of Gnosis Safe multsig wallet on the Meter mainnet. The smart contracts for the multsig were officially deployed by the Gnosis team. It can be found at:

{% embed url="<https://safe.meter.io>" %}
Meter Multsig Wallet
{% endembed %}

## **4. Graph Node**

The meter foundation maintains two separate graph nodes for the Meter Testnet and mainnet for dApp developers. They are for testing purposes only. If you need production-level graph nodes on Meter mainnet, please reach out to the team on Discord or Telegram. We are happy to host the subgraph on our production graph nodes.

**On testnet:**

In the package.json file for your subgraph:

```
"create-test": "graph create --node http://graphtest.meter.io:8020/ [graph-name]",
"remove-test": "graph remove --node http://graphtest.meter.io:8020/ [graph-name]",
"deploy-test": "graph deploy --node http://graphtest.meter.io:8020/ --ipfs http://graphtest.meter.io:50
```

In the subgraph.yaml file for your subgraph:

<pre><code><strong>network:metertest
</strong></code></pre>

**On Mainnet:**

In the package.json file for your subgraph:

<pre><code><strong>"create-mainnet": "graph create --node http://graph.meter.io:8020/ [graph-name]",
</strong>"remove-mainnet": "graph remove --node http://graph.meter.io:8020/ [graph-name]",
"deploy-mainnet": "graph deploy --node http://graph.meter.io:8020/ --ipfs http://graph.meter.io:5001 [graph-name]",
</code></pre>

In the subgraph.yaml file for your subgraph:

<pre><code><strong>network:meter
</strong></code></pre>

## **5. APIs and Indexers**

1. Thirdweb.com provides RPC endpoints, tools, smart contract libraries, and APIs for developers to launch dApp quickly:

{% embed url="<https://thirdweb.com/meter>" %}

{% embed url="<https://thirdweb.com/meter-testnet>" %}

2. covalenthq.com provides data analytics APIs on the Meter mainnet.

{% embed url="<https://www.covalenthq.com/docs/networks/meter/>" %}

3. [SubQuery](/developer-documentation/subquery) is a leading blockchain data indexer that provides developers with fast, flexible, universal, open source and decentralised APIs for web3 projects. Another one of SubQuery's competitive advantages is the ability to aggregate data not only within a chain but across multiple blockchains all within a single project.

## **6. Bridges**

[Layer 0](https://layerzero.network/) connects Meter Mainnet and Testnet to more than 20 other chains. The documentation can be found at <https://layerzero.gitbook.io/docs/technical-reference/mainnet/supported-chain-ids> and <https://layerzero.gitbook.io/docs/technical-reference/testnet/testnet-addresses>

Meter Passport provides connection to 8 different chains. To add ERC20 or NFT tokens to the supported list, please make a pull request based on the instructions here: <https://github.com/meterio/token-list>

## **7. Oracles**

[Band Protocol](https://docs.bandchain.org/develop/supported-blockchains/) and [Witnet](https://feeds.witnet.io/meter) are providing price feeds to the Meter mainnet and testnet. Detailed documentation can be found on their respective websites.&#x20;

[Pyth Network](https://docs.pyth.network/documentation/pythnet-price-feeds/evm) provides real-time data in an on-demand-based push model. Meter Foundation is currently running a price pusher for USDC/USDT/ETH/MTRG/MTR/BTC/WBTC on the Meter mainnet and testnet. In addition, Pyth network allows any developer to run additional price pushers permissionlessly.&#x20;

[Supra](https://supra.com/) provides decentralized oracle price feeds that can be used for on-chain and off-chain use-cases such as spot and perpetual DEXes, lending protocols, and payments protocols. Supra’s oracle chain and consensus algorithm makes it the fastest-to-finality oracle provider, with layer-1 security guarantees. The pull oracle has a sub-second response time.  The list of push based data available on Meter can be found [here](https://supra.com/data/networks/meter?nid=128\&networkType=mainnet).  The developer docs are available [here](https://supra.com/docs/overview/).

## **8. Important Things to Pay Attention to:**

1. **Currently, there is a limitation that MTR and MTRG can only be sent to a contract address through smart contract interactions. For example, if you want to send MTR to a contract address manually, you will have to use the above ERC20 system interface.**
2. **Meter network now requires all transactions to contain chainID. Please make sure to configure your deployment script properly.**
3. **The minimum gas price on Meter is currently 100gwei (Use eth\_estimateGas to obtain the gas price). Even if a lower gas price is specified, the network will still charge 100gwei silently. Make sure you have enough MTR in the account.**
4. **Meter network is front-running resistant. It does not order transactions by the gas price specified. Transactions are ordered by the time the proposing node receives them. By default, if a transaction is not processed within 320 blocks after the network receives it, it will automatically expire.**
5. **Meter does not require sequential nonce for each account. If you want to deploy your contract to a specified address, please use the** [**deterministic deployment method for Ethereum.**](https://github.com/Zoltu/deterministic-deployment-proxy) **If you want to use an EOA address and specific nonce to create a deterministic contract address, you will have to force the nonce of your transaction (for example in MetaMask) instead of relying on the random nonce returned from the RPC. As long as the nonce has not been used, the transaction will be processed and the same contract address can be created.**
6. **If you use Ethereum RPC to obtain the next nonce, you will receive a random number. In fact, you could use any nonce when sending a transaction on Meter. However, transactions from the same account with duplicated nonce will not be executed. Precomputed Ethereum tx hash is also guaranteed to be the same as on-chain hash.**


# Developing with Remix, Ethers.js and Web3.js

Ethereum developers are able to use Remix to compile and debug code for Meter. The current EVM version for Meter is **Istanbul**. MTR is used instead of ETH in Ethereum.

### Remix:

Use "Injected Web3" in Remix and [configure Metamask](/wallet-setup/interacting-with-meter-mainnet-using-metamask) properly to deploy on Meter.

Meter also supports ethers.js and web3.js through the RPC endpoints.

## Using Ethers.js

In order to get started with the ethers.js library we first need to install it using the following command:

```
npm install ethers
```

Once this has been completed the simplest way to start using the library and its' methods is as follows:

```
const ethers = require('ethers');

// Variables definition
const privKey = '0xPRIVKEY';

// Define Provider
let provider = new ethers.providers.JsonRpcProvider('RPC_URL');

// Create Wallet
let wallet = new ethers.Wallet(privKey, provider);
```

Please remember to replace the PRIVKEY and RPC\_URL with the correct values.

### Using Web3.js

You can get started with the web3.js library by installing it with the following command:

```
npm install web3
```

Once this has been completed the simplest way to start using the library and its' methods is as follows:

```
const Web3 = require('web3');

//Create web3 instance
const web3 = new Web3('RPC_URL');
```

Please remember to set the `RPC_URL` to the correct RPC endpoint.

### RPC End Points

Mainnet: `https://rpc.meter.io`

Warringstakes Testnet: `https://rpctest.meter.io`

Private Node: `http://`*`node_ip`*`:8545`


# Index Data with SubQuery

## Intro

SubQuery is a leading blockchain data indexer that provides developers with fast, flexible, universal, open source and decentralised APIs for web3 projects. SubQuery SDK allows developers to get rich indexed data and build intuitive and immersive decentralised applications in a faster and more efficient way. SubQuery supports 100+ ecosystems including Meter, Ethereum, Polygon, Polkadot, Algorand, NEAR, and Avalanche.

Another one of SubQuery's competitive advantages is the ability to aggregate data not only within a chain but across multiple blockchains all within a single project. This allows the creation of feature-rich dashboard analytics and multi-chain block scanners.

Other advantages include superior performance with multiple RPC endpoint configurations, multi-worker capabilities and a configurable caching architecture. To find out more, visit our [documentation](https://academy.subquery/).

**Useful resources**:

* SubQuery Docs: [SubQuery Academy (Documentation)](https://academy.subquery.network/)
* Intro Quick Start Guide: [1. Create a New Project](https://academy.subquery.network/quickstart/quickstart.html)
* [Meter Quick Start Guide](https://academy.subquery.network/quickstart/quickstart_chains/meter.html)

## Getting Started

Take a look at this SubQuery Starter Project that introduces SubQuery's Meter support by indexing [Meter](https://github.com/subquery/ethereum-subql-starter/tree/main/Meter/meter-starter).

You can also follow along this [step by step guide](https://academy.subquery.network/quickstart/quickstart.html) to get familiar with SubQuery.

## Running and Hosting your Meter SubQuery APIs

SubQuery is open-source, meaning you have the freedom to run it in the following three ways:

* Locally on your own computer (or a cloud provider of your choosing), [view the instructions on how to run SubQuery Locally](https://academy.subquery.network/run_publish/run.html).
* You can publish it to SubQuery's enterprise-level [Managed Service](https://managedservice.subquery.network/), where we'll host your SubQuery project in production ready services for mission critical data with zero-downtime blue/green deployments. There even is a generous free tier. [Find out how](https://academy.subquery.network/run_publish/publish.html).
* You can publish it to the decentralised [SubQuery Network](https://subquery.network/network), the most open, performant, reliable, and scalable data service for dApp developers. The SubQuery Network indexes and services data to the global community in an incentivised and verifiable way and supports Meter from launch.


# Meter Native TX RESTful APIs

RESTful API (Ignore if you prefer Ethereum RPC toolchains) This is the native interface (the tx format is slightly different from Ethereum tx and supports enhanced features like parallel transactions

## **RESTful API (Ignore if you use Ethereum RPC toolchains)**

This is the native interface (the tx format is slightly different from Ethereum tx and supports enhanced features like parallel sending and etc.) for Meter and is directly supported by Meter node on port 8669. There is an additional mainnet endpoint at [https://mainnet.meter.io ](https://mainnet.meter.io:8667)

You are able to access all of our functionality and create Meter native transactions through this interface. We have implemented an Ethereum web3 compatible interface library called meterify.&#x20;

In order to install Meterify run the following commands:

```
npm install meterify
```

Using the code below you can create a web3 instance. You are then able to use the Ethereum web3 interfaces to interact with the Meter mainnet.

```
const meterify = require(“meterify”).meterify;
const Web3 = require(“web3");
const web3 = meterify(new Web3(), “https://mainnet.meter.io”);
```

### **API Documentation**

The [API documentation](/developer-documentation/meterify-api-documentation) focuses on the use of the `meterify` library to develop DApps for the Meter blockchain through the native RESTful API interface.  The RESTful API uses the native Meter TX format instead of the Ethereum TX format and is not compatible with existing Ethers.js, Web3.js, or web3j libraries.  Therefore `meterify`was created to bridge the gap.  Similarly, there is a [Meter-SDK4j](https://github.com/meterio/meter-sdk4j) library that is similar to web3j library for integrating with Java clients.

`meterify` is a node.js package.  It provides interfaces almost the same as the well-known `web3.js`library and much of its relevant open-source documentation have been merged with information more specific to Meter.  Using `meterify` generates native Meter transactions and is more direct than using `web3.js` through the RESTful interface. &#x20;

The meterify.js library uses the http restful API.  You could either use your own node or interact with a full node on the Meter mainnet/testnet. &#x20;

Restful API endpoints:

Local: `http://node_ip:8669`

Mainnet: `https://mainnet.meter.io`

Testnet: `https://testnet.meter.io`

To get started with the `meterify.js` library, we first need to install it using the following command:

```
npm install meterify
```

Once done, the simplest setup to start using the library and its methods is the following:

```
const meterify = require("meterify").meterify;
const Web3 = require("web3");
const web3 = meterify(new Web3(), "RPC_URL");
```

### Guides and Tutorials <a href="#guides-and-tutorials" id="guides-and-tutorials"></a>

Several guides and tutorials have been written to explain how to work with the Meter blockchain through `meterify`. They cover development topics, such as [how to build DApps and work with smart contracts](/developer-documentation/meter-dapp-tutorials).

### Other Resources <a href="#other-resources" id="other-resources"></a>

* [Request test tokens](http://faucet-warringstakes.meter.io/)
* [Read the whitepaper](https://docsend.com/view/6gebiph)
* [Meterify web3 GitHub repository](https://github.com/meterio/meterify)
* [Java library for Native TX Meter-SDK4j](https://github.com/meterio/meter-sdk4j)


# Meterify API Documentation

The `meterify` package is a wrapper to house all Meter-related modules, and depends on the `web3.js` library. If you are writing applications or scripts executing in Node.js or a browser environment, you should use Meterify.

| Property     | Type     | Description                                  |
| ------------ | -------- | -------------------------------------------- |
| web3Instance | `object` | A `web3` instance                            |
| host         | `string` | The Meter host URL (and port, if applicable) |
| timeout      | `number` | Request timeout value                        |

Parameters of the `meterify` return object

| Property         | Type        | Description                                                 |
| ---------------- | ----------- | ----------------------------------------------------------- |
| BatchRequest     | `function`  | Sets a `RequestManager` object and initiates batch requests |
| currentProvider  | `function`  | Get or set the current provider.                            |
| timeout          | `number`    | Request timeout value                                       |
| eth              | `object`    | An Eth object (see: eth (insert link))                      |
| extension        | `extension` |                                                             |
| givenProvider    | `object`    | Return the given provider object.                           |
| providers        | `object`    | A list of providers.                                        |
| provider         | `object`    | The current provider object.                                |
| \_requestManager | `object`    | A RequestManager object.                                    |
| setProvider      | `function`  | Set the current provider.                                   |
| utils            | `object`    | A `utils` object (see: (insert link))                       |

## Example

This code...

```javascript
const meter = require("meterify").meterify;
const Web3 = require("web3");
const meterify = meter(new Web3(), "https://testnet.meter.io");
```

...returns an object:

```javascript
{
  eth: {
    _requestManager: RequestManager,
    givenProvider: MetamaskInpageProvider,
    providers: {…},
    _provider: MeterProvider, 
    …
  },
  givenProvider: {
    mux: ObjectMultiplex,
    publicConfigStore: ObservableStore,
    rpcEngine: RpcEngine,
    send: ƒ
  },
  providers: {
    WebsocketProvider: ƒ,
    HttpProvider: ƒ,
    IpcProvider: ƒ
  },
  utils: {
    _fireError: ƒ,
    _jsonInterfaceMethodToString: ƒ,
    _flattenTypes: ƒ,
    randomHex: ƒ,
    _: ƒ, 
    …
  },
  version: "1.0.0-beta.37",
  _provider: {
    _events: Events,
    _eventsCount: 1,
    RESTHost: "https://test.meter.io",
    WSHost: "wss://wstest.meter.io",
    timeout: 0, 
    …
  },
  _requestManager: {
    provider: MeterProvider,
    providers: {…},
    subscriptions: {…}
  }
  ...
}
```

## Notes on `meterify` and `web3`

The RESTful API of Meter differs from Ethereum's JSON-RPC, and there are some methods in `web3` are not supported by `meterify`.

*Supported Web3 Methods*

web3 instance\
├── eth\
│ ├── getBlockNumber\
│ ├── getBalance\
│ ├── getStorageAt\
│ ├── getCode\
│ ├── getBlock\
│ ├── getTransaction\
│ ├── getTransactionReceipt\
│ ├── sendTransaction\
│ ├── sendSignedTransaction\
│ ├── call\
│ ├── estimateGas\
│ ├── getPastLogs\
│ ├── subscribe\
│ ├── clearSubscriptions\
│ ├── getEnergy\
│ ├── getChainTag\
│ ├── getBlockRef\
│ ├── accounts\
│ └── Contract\
│ ├── Constructor(new Contract())\
│ ├── clone\
│ ├── deploy\
│ ├── methods\
│ ├── methods.myMethod.call\
│ ├── methods.myMethod.send\
│ ├── methods.myMethod.estimateGas\
│ ├── methods.myMethod.encodeABI\
│ ├── events\
│ ├── once\
│ ├── events.myEvent\
│ ├── events.allEvents\
│ └── getPastEvents\
└── utils<br>

## MODULES <a href="#modules" id="modules"></a>

### eth <a href="#eth" id="eth"></a>

For `meterify.eth` see the [`eth`](/developer-documentation/meterify-api-documentation/meterify.eth) reference documentation.

### utils <a href="#utils" id="utils"></a>

For `meterify.utils` see the [`utils`](/developer-documentation/meterify-api-documentation/meterify.utils) reference documentation.

### module.options <a href="#module-options" id="module-options"></a>

A module does provide several options for configuring the transaction confirmation workflow, or for defining default values.

For the currently available option properties on a module: see the [`options`](/developer-documentation/meterify-api-documentation/meterify.module.options) reference documentation.


# meterify.eth

This module allows you to interact with a Meter blockchain and any deployed smart contracts on it.

Although the `meterify.eth` module inherits from `web.eth`, there are some feature differences between the two. The following is a list of extended features in `meterify.eth`

## Extended Properties

* currentProvider
* givenProvider

## Extended Methods

* getBlockRef
* getBlockUncleCount
* getChainTag
* getEnergy

## Note on checksum addresses

All addresses returned by functions of this package are returned as checksum addresses. This means some letters are uppercase and some are lowercase. Based on that it will calculate a checksum for the address and prove its correctness. Incorrect checksum addresses will throw an error when passed into functions. If you want to circumvent the checksum check you can make an address all lower- or uppercase.

**Checksum Example:**

```javascript
    meterify.eth.getAccounts(console.log);
```

```javascript
    > ["0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe" ,"0x85F43D8a49eeB85d32Cf465507DD71d507100C1d"]
```

## Contract

For `meterify.eth.Contract` see the [`Contract`](/developer-documentation/meterify-api-documentation/meterify.eth.contract) reference documentation.

## accounts

For `meterify.eth.accounts` see the [`accounts`](/developer-documentation/meterify-api-documentation/meterify.eth.accounts) reference documentation.

## options

For `meterify.eth.options` see the [`options`](/developer-documentation/meterify-api-documentation/meterify.module.options) reference documentation.

## getProtocolVersion

```javascript
    meterify.eth.getProtocolVersion([callback])
```

Returns the protocol version of the node.

**Example:**

```javascript
    meterify.eth.getProtocolVersion().then(console.log);
    > "63"
```

**Returns:**

| Type              | Description           |
| ----------------- | --------------------- |
| `Promise<string>` | The protocol version. |

## isSyncing

```javascript
    meterify.eth.isSyncing([callback])
```

Checks if the node is currently syncing and returns either a syncing object, or `false`.

**Returns:**

| Type                     | Description |
| ------------------------ | ----------- |
| Promise \<objectboolean> |             |

| Property        | Type     | Description                                                                 |
| --------------- | -------- | --------------------------------------------------------------------------- |
| `startingBlock` | `Number` | The block number where the sync started.                                    |
| `currentBlock`  | `Number` | The block number where at which block the node currently synced to already. |
| `highestBlock`  | `Number` | The estimated block number to sync to.                                      |
| `knownStates`   | `Number` | The estimated states to download                                            |
| `pulledStates`  | `Number` | The already downloaded states                                               |

**Example:**

```javascript
meterify.eth.isSyncing()
    .then(console.log);

    > {
        startingBlock: 100,
        currentBlock: 312,
        highestBlock: 512,
        knownStates: 234566,
        pulledStates: 123455
    }
```

## getCoinbase   &#x20;

```javascript
meterify.eth.getCoinbase([callback])
```

Returns the Coinbase address to which mining rewards will go.

**Returns:**

| Type              | Description                                              |
| ----------------- | -------------------------------------------------------- |
| `Promise<string>` | The Coinbase address set in the node for mining rewards. |

**Example:**

```javascript
meterify.eth.getCoinbase().then(console.log);  
> "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe"  
```

## isMining   &#x20;

```javascript
meterify.eth.isMining([callback])
```

Checks whether the node is mining or not.

**Returns:**

| Type               | Description                                              |
| ------------------ | -------------------------------------------------------- |
| `Promise<boolean>` | Returns `true` if the node is mining, otherwise `false`. |

**Example:**   &#x20;

```javascript
meterify.eth.isMining().then(console.log);    
> true
```

## getHashrate   &#x20;

```javascript
meterify.eth.getHashrate([callback])
```

Returns the number of hashes per second that the node is mining with.

**Returns:**

| Type              | Description                      |
| ----------------- | -------------------------------- |
| `Promise<number>` | The number of hashes per second. |

**Example:**   &#x20;

```javascript
meterify.eth.getHashrate().then(console.log);    
> 493736
```

## getGasPrice

```javascript
meterify.eth.getGasPrice([callback])
```

Returns the current gas price oracle. The gas price is determined by the last few blocks median gas price. GasPrice is the wei per unit of gas.

**Returns:**

| Type              | Description                                      |
| ----------------- | ------------------------------------------------ |
| `Promise<string>` | Number string of the current gas price in `wei.` |

See the [A note on dealing with big numbers in JavaScript](/developer-documentation/meterify-api-documentation/meterify.utils#bn).

**Example:**

```javascript
    meterify.eth.getGasPrice().then(console.log);
    > "20000000000"
```

## getAccounts

```javascript
    meterify.eth.getAccounts([callback])
```

Will return a list of the unlocked accounts in the Web3 wallet or it will return the accounts from the currently connected node.

This means you can add accounts with [`meterify.eth.accounts.create()`](/developer-documentation/meterify-api-documentation/meterify.eth.accounts#create) and you will get them returned here.

**Returns:**

| Type             | Description                               |
| ---------------- | ----------------------------------------- |
| `Promise<Array>` | An array of addresses controlled by node. |

**Example:**

```javascript
    meterify.eth.getAccounts().then(console.log);
    > ["0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", "0xDCc6960376d6C6dEa93647383FfB245CfCed97Cf"]
```

## getBlockNumber

```javascript
    meterify.eth.getBlockNumber([callback])
```

Returns the current block number.

**Returns:**

| Type              | Description                          |
| ----------------- | ------------------------------------ |
| `Promise<number>` | The number of the most recent block. |

**Example:**

```javascript
    meterify.eth.getBlockNumber().then(console.log);
    > 2744
```

## getBalance

```javascript
    meterify.eth.getBalance(address [, defaultBlock] [, callback])
```

Get the Meter MTRG balance of an address at a given block.

| Property     | Type                 | Description                                                                                                                                                                                               |
| ------------ | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| address      | `String`             | The address to get the balance of.                                                                                                                                                                        |
| defaultBlock | `Number` or `String` | (optional) If you pass this parameter it will not use the default block set with [`meterify.eth.defaultBlock`](/developer-documentation/meterify-api-documentation/meterify.module.options#defaultblock). |
| callback     | `Function`           | (optional) Optional callback, returns an error object as first parameter and the result as second.                                                                                                        |

**Returns:**

| Type              | Description                                               |
| ----------------- | --------------------------------------------------------- |
| `Promise<string>` | The current Meter balance for the given address in `wei`. |

See the [\`A note on dealing with big numbers in JavaScript'](/developer-documentation/meterify-api-documentation/meterify.utils#bn).

**Example:**

```javascript
    meterify.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log);
    > "1000000000000"
```

## getEnergy

```javascript
    meterify.eth.getEnergy(address [, defaultBlock] [, callback])
```

Get the Meter MTR (energy) balance of an address at a given block.

| Property     | Type                 | Description                                                                                                                                                                                               |
| ------------ | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| address      | `String`             | The address to get the balance of.                                                                                                                                                                        |
| defaultBlock | `Number` or `String` | (optional) If you pass this parameter it will not use the default block set with [`meterify.eth.defaultBlock`](/developer-documentation/meterify-api-documentation/meterify.module.options#defaultblock). |
| callback     | `Function`           | (optional) Optional callback, returns an error object as first parameter and the result as second.                                                                                                        |

**Returns:**

| Type              | Description                                                                 |
| ----------------- | --------------------------------------------------------------------------- |
| `Promise<string>` | The current Meter MTR balance for the given address in `wei <what-is-wei>`. |

See the [A note on dealing with big numbers in JavaScript](/developer-documentation/meterify-api-documentation/meterify.utils#bn).

**Example:**

```javascript
    meterify.eth.getEnergy("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log);
    > "1000000000000"
```

## getStorageAt

```javascript
    meterify.eth.getStorageAt(address, position [, defaultBlock] [, callback])
```

Get the storage at a specific position of an address.

**Parameters:**

| Property     | Type                 | Description                                                                                                                                                                                               |
| ------------ | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| address      | `String`             | The address to get the storage from.                                                                                                                                                                      |
| position     | `Number`             | The index position of the storage.                                                                                                                                                                        |
| defaultBlock | `Number` or `String` | (optional) If you pass this parameter it will not use the default block set with [`meterify.eth.defaultBlock`](/developer-documentation/meterify-api-documentation/meterify.module.options#defaultblock). |
| callback     | `Function`           | (optional) Optional callback, returns an error object as first parameter and the result as second.                                                                                                        |

**Returns:**

| Type              | Description                                 |
| ----------------- | ------------------------------------------- |
| `Promise<string>` | The value in storage at the given position. |

**Example:**

```javascript
    meterify.eth.getStorageAt("0x407d73d8a49eeb85d32cf465507dd71d507100c1", 0).then(console.log);
    > "0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234"
```

## getCode

```javascript
    meterify.eth.getCode(address [, defaultBlock] [, callback])
```

Get the code at a specific address.

**Parameters:**

| Property     | Type                 | Description                                                                                                                                                                                               |
| ------------ | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| address      | `String`             | The address to get the code from.                                                                                                                                                                         |
| defaultBlock | `Number` or `String` | (optional) If you pass this parameter it will not use the default block set with [`meterify.eth.defaultBlock`](/developer-documentation/meterify-api-documentation/meterify.module.options#defaultblock). |
| callback     | `Function`           | (optional) Optional callback, returns an error object as first parameter and the result as second.                                                                                                        |

**Returns:**

| Type              | Description                          |
| ----------------- | ------------------------------------ |
| `Promise<string>` | The data at given address `address`. |

**Example:**

```javascript
    meterify.eth.getCode("0xd5677cf67b5aa051bb40496e68ad359eb97cfbf8").then(console.log);
    > "0x600160008035811a818181146012578301005b601b6001356025565b8060005260206000f25b600060078202905091905056"
```

## getBlock

```javascript
     meterify.eth.getBlock(blockHashOrBlockNumber [, returnTransactionObjects] [, callback])
```

Returns a block matching the block number or block hash.

**Parameters:**

| Property                 | Type                 | Description                                                                                                                                                                           |
| ------------------------ | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| blockHashOrBlockNumber   | `String` or `Number` | The block number or block hash. Or the string `"genesis"`, `"latest"` or `"pending"` as in the [`default block parameter`](https://docs.meter.io/meterify.eth.html#eth-defaultblock). |
| returnTransactionObjects | `Boolean`            | (optional, default `false`) If `true`, the returned block will contain all transactions as objects, if `false` it will only contains the transaction hashes.                          |
| callback                 | `Function`           | (optional) Optional callback, returns an error object as first parameter and the result as second.                                                                                    |

**Returns:**

| Type              | Description       |
| ----------------- | ----------------- |
| `Promise<object>` | The block object. |

**The block object:**

| Property                    | Type                 | Description                                                                                                                                                                                          |
| --------------------------- | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `number`                    | `Number`             | The block number. `null` when its pending block.                                                                                                                                                     |
| `hash` 32 Bytes             | `String`             | Hash of the block. `null` when its pending block.                                                                                                                                                    |
| `parentHash` 32 Bytes       | `String`             | Hash of the parent block.                                                                                                                                                                            |
| `nonce` 8 Bytes             | `String`             | Hash of the generated proof-of-work. `null` when its pending block.                                                                                                                                  |
| `sha3Uncles` 32 Bytes       | `String`             | SHA3 of the uncles data in the block.                                                                                                                                                                |
| `logsBloom` 256 Bytes       | `String`             | The bloom filter for the logs of the block. `null` when its pending block.                                                                                                                           |
| `transactionsRoot` 32 Bytes | `String`             | The root of the transaction trie of the block                                                                                                                                                        |
| `stateRoot` 32 Bytes        | `String`             | The root of the final state trie of the block.                                                                                                                                                       |
| `receiptsRoot` 32 Bytes     | `String`             | Transaction receipts are used to store the state after a transaction has been executed and are kept in an index-keyed trie. The hash of its root is placed in the block header as the receipts root. |
| `miner`                     | `String`             | The address of the beneficiary to whom the mining rewards were given.                                                                                                                                |
| `difficulty`                | `String`             | Integer of the difficulty for this block.                                                                                                                                                            |
| `totalDifficulty`           | `String`             | Integer of the total difficulty of the chain until this block.                                                                                                                                       |
| `extraData`                 | `String`             | The "extra data" field of this block.                                                                                                                                                                |
| `size`                      | `Number`             | Integer the size of this block in bytes.                                                                                                                                                             |
| `gasLimit`                  | `Number`             | The maximum gas allowed in this block.                                                                                                                                                               |
| `gasUsed`                   | `Number`             | The total used gas by all transactions in this block.                                                                                                                                                |
| `timestamp`                 | `Number` or `String` | The unix timestamp for when the block was collated (returns a string if a overflow got detected).                                                                                                    |
| `transactions`              | `Array`              | Array of transaction objects, or 32 Bytes transaction hashes depending on the `returnTransactionObjects` parameter.                                                                                  |
| `uncles`                    | `Array`              | Array of uncle hashes.                                                                                                                                                                               |

**Example:**

```javascript
    meterify.eth.getBlock(3150).then(console.log);
    > {
        "number": 3,
        "hash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
        "parentHash": "0x2302e1c0b972d00932deb5dab9eb2982f570597d9d42504c05d9c2147eaf9c88",
        "nonce": "0xfb6e1a62d119228b",
        "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
        "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
        "transactionsRoot": "0x3a1b03875115b79539e5bd33fb00d8f7b7cd61929d5a3c574f507b8acf415bee",
        "stateRoot": "0xf1133199d44695dfa8fd1bcfe424d82854b5cebef75bddd7e40ea94cda515bcb",
        "receiptsRoot": '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421',
        "miner": "0x8888f1f195afa192cfee860698584c030f4c9db1",
        "difficulty": '21345678965432',
        "totalDifficulty": '324567845321',
        "size": 616,
        "extraData": "0x",
        "gasLimit": 3141592,
        "gasUsed": 21662,
        "timestamp": 1429287689,
        "transactions": [
            "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b"
        ],
        "uncles": []
    }
```

## getBlockTransactionCount

```javascript
    meterify.eth.getBlockTransactionCount(blockHashOrBlockNumber [, callback])
```

Returns the number of transaction in a given block.

**Parameters:**

| Property               | Type                 | Description                                                                                                                                                                     |
| ---------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| blockHashOrBlockNumber | `String` or `Number` | The block number or hash. Or the string `"genesis"`, `"latest"` or `"pending"` as in the [`default block parameter`](https://docs.meter.io/meterify.eth.html#eth-defaultblock). |
| callback               | `Function`           | (optional) Optional callback, returns an error object as first parameter and the result as second.                                                                              |

**Returns:**

| Type              | Description                                    |
| ----------------- | ---------------------------------------------- |
| `Promise<number>` | The number of transactions in the given block. |

**Example:**

```javascript
    meterify.eth.getBlockTransactionCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log);
    > 1
```

## getUncle

```javascript
    meterify.eth.getUncle(blockHashOrBlockNumber, uncleIndex [, callback])
```

Returns a blocks uncle by a given uncle index position.

**Parameters:**

| Property               | Type                 | Description                                                                                                                                                                     |
| ---------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| blockHashOrBlockNumber | `String` or `Number` | The block number or hash. Or the string `"genesis"`, `"latest"` or `"pending"` as in the [`default block parameter`](https://docs.meter.io/meterify.eth.html#eth-defaultblock). |
| uncleIndex             | `Number`             | The index position of the uncle.                                                                                                                                                |
| callback               | `Function`           | (optional) Optional callback, returns an error object as first parameter and the result as second.                                                                              |

**Returns:**

| Type              | Description                                                                                                                   |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `Promise<object>` | The returned uncle. For a return value see [`meterify.eth.getBlock()`](https://docs.meter.io/meterify.eth.html#eth-getblock). |

Note: An uncle doesn't contain individual transactions.

**Example:**

```javascript
    meterify.eth.getUncle(500, 0).then(console.log);
    > // see meterify.eth.getBlock
```

## getTransaction

```javascript
    meterify.eth.getTransaction(transactionHash [, callback])
```

Returns a transaction matching the given transaction hash.

**Parameters:**

| Property        | Type       | Description                                                                                        |
| --------------- | ---------- | -------------------------------------------------------------------------------------------------- |
| transactionHash | `String`   | The transaction hash.                                                                              |
| callback        | `Function` | (optional) Optional callback, returns an error object as first parameter and the result as second. |

**Returns:**

| Type              | Description                                      |
| ----------------- | ------------------------------------------------ |
| `Promise<object>` | A transaction object its hash `transactionHash`: |

**The object:**

| Property             | Type     | Description                                                                       |
| -------------------- | -------- | --------------------------------------------------------------------------------- |
| `hash` 32 Bytes      | `String` | Hash of the transaction.                                                          |
| `nonce`              | `Number` | The number of transactions made by the sender prior to this one.                  |
| `blockHash` 32 Bytes | `String` | Hash of the block where this transaction was in. `null` when its pending.         |
| `blockNumber`        | `Number` | Block number where this transaction was in. `null` when its pending.              |
| `transactionIndex`   | `Number` | Integer of the transactions index position in the block. `null` when its pending. |
| `from`               | `String` | Address of the sender.                                                            |
| `to`                 | `String` | Address of the receiver. `null` when its a contract creation transaction.         |
| `value`              | `String` | Value transferred in `wei`.                                                       |
| `gasPrice`           | `String` | The wei per unit of gas provided by the sender in `wei`.                          |
| `gas`                | `Number` | Gas provided by the sender.                                                       |
| `input`              | `String` | The data sent along with the transaction.                                         |

**Example:**

```javascript
    meterify.eth.getTransaction('0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b§234').then(console.log);
    > {
        "hash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
        "nonce": 2,
        "blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
        "blockNumber": 3,
        "transactionIndex": 0,
        "from": "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b",
        "to": "0x6295ee1b4f6dd65047762f924ecd367c17eabf8f",
        "value": '123450000000000000',
        "gas": 314159,
        "gasPrice": '2000000000000',
        "input": "0x57cb2fc4"
    }
```

## getPendingTransactions

```javascript
    meterify.eth.getPendingTransactions([, callback])
```

Returns a list of pending transactions.

**Parameters:**

| Property | Type       | Description                                                                                        |
| -------- | ---------- | -------------------------------------------------------------------------------------------------- |
| callback | `Function` | (optional) Optional callback, returns an error object as first parameter and the result as second. |

**Returns:**

| Type                | Description                    |
| ------------------- | ------------------------------ |
| `Promise<object[]>` | Array of pending transactions: |

**The object:**

| Property             | Type     | Description                                                                       |
| -------------------- | -------- | --------------------------------------------------------------------------------- |
| `hash` 32 Bytes      | `String` | Hash of the transaction.                                                          |
| `nonce`              | `Number` | The number of transactions made by the sender prior to this one.                  |
| `blockHash` 32 Bytes | `String` | Hash of the block where this transaction was in. `null` when its pending.         |
| `blockNumber`        | `Number` | Block number where this transaction was in. `null` when its pending.              |
| `transactionIndex`   | `Number` | Integer of the transactions index position in the block. `null` when its pending. |
| `from`               | `String` | Address of the sender.                                                            |
| `to`                 | `String` | Address of the receiver. `null` when its a contract creation transaction.         |
| `value`              | `String` | Value transferred in `wei`.                                                       |
| `gasPrice`           | `String` | The wei per unit of gas provided by the sender in `wei`.                          |
| `gas`                | `Number` | Gas provided by the sender.                                                       |
| `input`              | `String` | The data sent along with the transaction.                                         |

**Example:**

```javascript
    meterify.eth.getPendingTransactions().then(console.log);
    >  [
        {
            hash: '0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b',
            nonce: 2,
            blockHash: '0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46',
            blockNumber: 3,
            transactionIndex: 0,
            from: '0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b',
            to: '0x6295ee1b4f6dd65047762f924ecd367c17eabf8f',
            value: '123450000000000000',
            gas: 314159,
            gasPrice: '2000000000000',
            input: '0x57cb2fc4'
            v: '0x3d',
            r: '0xaabc9ddafffb2ae0bac4107697547d22d9383667d9e97f5409dd6881ce08f13f',
            s: '0x69e43116be8f842dcd4a0b2f760043737a59534430b762317db21d9ac8c5034'
        },....,{
            hash: '0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b',
            nonce: 3,
            blockHash: '0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46',
            blockNumber: 4,
            transactionIndex: 0,
            from: '0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b',
            to: '0x6295ee1b4f6dd65047762f924ecd367c17eabf8f',
            value: '123450000000000000',
            gas: 314159,
            gasPrice: '2000000000000',
            input: '0x57cb2fc4'
            v: '0x3d',
            r: '0xaabc9ddafffb2ae0bac4107697547d22d9383667d9e97f5409dd6881ce08f13f',
            s: '0x69e43116be8f842dcd4a0b2f760043737a59534430b762317db21d9ac8c5034'
        }
   ]
```

## getTransactionFromBlock

```javascript
    getTransactionFromBlock(hashStringOrNumber, indexNumber [, callback])
```

Returns a transaction based on a block hash or number and the transactions index position.

**Parameters:**

| Property           | Type       | Description                                                                                                                                                                   |
| ------------------ | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| hashStringOrNumber | `String`   | A block number or hash. Or the string `"genesis"`, `"latest"` or `"pending"` as in the [`default block parameter`](https://docs.meter.io/meterify.eth.html#eth-defaultblock). |
| indexNumber        | `Number`   | The transactions index position.                                                                                                                                              |
| callback           | `Function` | (optional) Optional callback, returns an error object as first parameter and the result as second.                                                                            |

**Returns:**

| Type              | Description                                                                                                                 |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `Promise<object>` | A transaction object, see[`meterify.eth.getTransaction`](https://docs.meter.io/meterify.eth.html#eth-gettransaction-return) |

**Example:**

```javascript
    const transaction = meterify.eth.getTransactionFromBlock('0x4534534534', 2).then(console.log);
    > // see meterify.eth.getTransaction
```

## getTransactionReceipt

```javascript
    meterify.eth.getTransactionReceipt(hash [, callback])
```

Returns the receipt of a transaction by transaction hash.

Note: The receipt is not available for pending transactions and returns `null`.

**Parameters:**

| Property | Type       | Description                                                                                        |
| -------- | ---------- | -------------------------------------------------------------------------------------------------- |
| hash     | `String`   | The transaction hash.                                                                              |
| callback | `Function` | (optional) Optional callback, returns an error object as first parameter and the result as second. |

**Returns:**

| Type                       | Description                                                        |
| -------------------------- | ------------------------------------------------------------------ |
| `Promise` returns `Object` | A transaction receipt object, or `null` when no receipt was found: |

**The object:**

| Property                   | Type      | Description                                                                                 |
| -------------------------- | --------- | ------------------------------------------------------------------------------------------- |
| `status`                   | `Boolean` | `TRUE` if the transaction was successful, `FALSE`, if the EVM reverted the transaction.     |
| `blockHash` 32 Bytes       | `String`  | Hash of the block where this transaction was in.                                            |
| `blockNumber`              | `Number`  | Block number where this transaction was in.                                                 |
| `transactionHash` 32 Bytes | `String`  | Hash of the transaction.                                                                    |
| `transactionIndex`         | `Number`  | Integer of the transactions index position in the block.                                    |
| `from`                     | `String`  | Address of the sender.                                                                      |
| `to`                       | `String`  | Address of the receiver. `null` when its a contract creation transaction.                   |
| `contractAddress`          | `String`  | The contract address created, if the transaction was a contract creation, otherwise `null`. |
| `cumulativeGasUsed`        | `Number`  | The total amount of gas used when this transaction was executed in the block.               |
| `gasUsed`                  | `Number`  | The amount of gas used by this specific transaction alone.                                  |
| `logs`                     | `Array`   | Array of log objects, which this transaction generated.                                     |

**Example:**

```javascript
    const receipt = meterify.eth.getTransactionReceipt('0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b')
                            .then(console.log);
    > {
      "status": true,
      "transactionHash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
      "transactionIndex": 0,
      "blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
      "blockNumber": 3,
      "contractAddress": "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe",
      "cumulativeGasUsed": 314159,
      "gasUsed": 30234,
      "logs": [{
             // logs as returned by getPastLogs, etc.
         }, ...]
    }
```

## getTransactionCount

```javascript
    meterify.eth.getTransactionCount(address [, defaultBlock] [, callback])
```

Get the numbers of transactions sent from this address.

**Parameters:**

| Property     | Type                 | Description                                                                                                                                                                                               |
| ------------ | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| address      | `String`             | The address to get the numbers of transactions from.                                                                                                                                                      |
| defaultBlock | `Number` or `String` | (optional) If you pass this parameter it will not use the default block set with [`meterify.eth.defaultBlock`](/developer-documentation/meterify-api-documentation/meterify.module.options#defaultblock). |
| callback     | `Function`           | (optional) Optional callback, returns an error object as first parameter and the result as second.                                                                                                        |

**Returns:**

| Type              | Description                                             |
| ----------------- | ------------------------------------------------------- |
| `Promise<number>` | The number of transactions sent from the given address. |

**Example:**

```javascript
    meterify.eth.getTransactionCount("0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe").then(console.log);
    > 1
```

## sendTransaction   &#x20;

```javascript
meterify.eth.sendTransaction(transactionObject [, callback])
```

Sends a transaction to the network.

**Parameters:**

| Property          | Type       | Description                                                                                        |
| ----------------- | ---------- | -------------------------------------------------------------------------------------------------- |
| transactionObject | `Object`   | The transaction object to send.                                                                    |
| callback          | `Function` | (optional) Optional callback, returns an error object as first parameter and the result as second. |

**The `transactionObject`**

| Property   | Type                                     | Description                                                                                                                                                                                                                                                                                                               |
| ---------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `from`     | `String` or `Number`                     | The address for the sending account. Uses the [`meterify.eth.defaultAccount`](https://docs.meter.io/meterify.eth.html#eth-defaultaccount) property, if not specified. Or an address or index of a local wallet in [`meterify.eth.accounts.wallet`](https://docs.meter.io/meterify.eth.accounts.html#eth_accounts_wallet). |
| `to`       | `String`                                 | (optional) The destination address of the message, left undefined for a contract-creation transaction.                                                                                                                                                                                                                    |
| `value`    | `Number`, `String`, `BN`, or `BigNumber` | (optional) The value transferred for the transaction in `wei`, also the endowment if it's a contract-creation transaction.                                                                                                                                                                                                |
| `gas`      | `Number`                                 | (optional, default: To-Be-Determined) The amount of gas to use for the transaction (unused gas is refunded).                                                                                                                                                                                                              |
| `gasPrice` | `Number`, `String`, `BN`, or `BigNumber` | (optional) The price of gas for this transaction in `wei`, defaults to [`meterify.eth.gasPrice`](https://docs.meter.io/meterify.eth.html#eth-gasprice).                                                                                                                                                                   |
| `data`     | `String`                                 | (optional) Either a `ABI byte string <http://solidity.readthedocs.io/en/latest/abi-spec.html>`\_ containing the data of the function call on a contract, or in the case of a contract-creation transaction the initialization code.                                                                                       |
| `nonce`    | `Number`                                 | (optional) Integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce.                                                                                                                                                                                                            |

Note: The `from` property can also be an address or index from the [`meterify.eth.accounts.wallet`](/developer-documentation/meterify-api-documentation/meterify.eth.accounts#wallet). It will then sign locally using the private key of that account, and send the transaction via [`meterify.eth.sendSignedTransaction()`](/developer-documentation/meterify-api-documentation/meterify.eth#sendsignedtransaction).

**Returns:**

The **callback** will return the 32 bytes transaction hash.

| Name         | Description                                                                                                                                                                                                                                                                                                              |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `PromiEvent` | A [promise combined event emitter](/developer-documentation/meterify-api-documentation/callbacks-promises-events#promievent). Will be resolved when the transaction [`receipt`](https://docs.meter.io/meterify.eth.html#eth-gettransactionreceipt-return) is available. Additionally the following events are available: |

| Event               | Returns            | Description                                                                                                                                                                                                                                                                                                     |
| ------------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `"transactionHash"` | `String`           | Is fired right after the transaction is sent and a transaction hash is available.                                                                                                                                                                                                                               |
| `"receipt"`         | `Object`           | Is fired when the transaction receipt is available.                                                                                                                                                                                                                                                             |
| `"confirmation"`    | `Number`, `Object` | Is fired for every confirmation up to the 12th confirmation. Receives the confirmation number as the first and the [receipt](/developer-documentation/meterify-api-documentation/meterify.eth#gettransactionreceipt) as the second argument. Fired from confirmation 0 on, which is the block where it's mined. |
| `"error"`           | `Error`            | Is fired if an error occurs during sending. If a out of gas error, the second parameter is the receipt.                                                                                                                                                                                                         |

**Example:**   &#x20;

```javascript
// compiled solidity source code using https://remix.ethereum.org
    const code = "603d80600c6000396000f3007c01000000000000000000000000000000000000000000000000000000006000350463c6888fa18114602d57005b6007600435028060005260206000f3";

    // using the callback
    meterify.eth.sendTransaction({
        from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe',
        data: code // deploying a contract
    }, function(error, hash){
        ...
    });

    // using the promise
    meterify.eth.sendTransaction({
        from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe',
        to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe',
        value: '1000000000000000'
    })
    .then(function(receipt){
        ...
    });

    // using the event emitter
    meterify.eth.sendTransaction({
        from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe',
        to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe',
        value: '1000000000000000'
    })
    .on('transactionHash', function(hash){
        ...
    })
    .on('receipt', function(receipt){
        ...
    })
    .on('confirmation', function(confirmationNumber, receipt){ ... })
    .on('error', console.error); // If a out of gas error, the second parameter is the receipt.
```

## sendSignedTransaction   &#x20;

```javascript
meterify.eth.sendSignedTransaction(signedTransactionData [, callback])
```

Sends an already signed transaction, generated for example using [`meterify.eth.accounts.signTransaction`](/developer-documentation/meterify-api-documentation/meterify.eth#signtransaction).

**Parameters:**

| Property              | Type       | Description                                                                                        |
| --------------------- | ---------- | -------------------------------------------------------------------------------------------------- |
| signedTransactionData | `String`   | Signed transaction data in HEX format                                                              |
| callback              | `Function` | (optional) Optional callback, returns an error object as first parameter and the result as second. |

**Returns:**

| Name         | Returns                                                                                                                      | Description                                                                                                                                             |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `PromiEvent` | A [promise combined event emitter](/developer-documentation/meterify-api-documentation/callbacks-promises-events#promievent) | Will be resolved when the transaction [`receipt`](/developer-documentation/meterify-api-documentation/meterify.eth#gettransactionreceipt) is available. |

Please see the return values for [`meterify.eth.sendTransaction`](/developer-documentation/meterify-api-documentation/meterify.eth#sendtransaction) for details.

**Example:**

```javascript
    const Tx = require('ethereumjs-tx');
    const privateKey = new Buffer('e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', 'hex')

    const rawTx = {
      nonce: '0x00',
      gasPrice: '0x09184e72a000',
      gasLimit: '0x2710',
      to: '0x0000000000000000000000000000000000000000',
      value: '0x00',
      data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057'
    }

    const tx = new Tx(rawTx);
    tx.sign(privateKey);

    const serializedTx = tx.serialize();

    // console.log(serializedTx.toString('hex'));
    // 0xf889808609184e72a00082271094000000000000000000000000000000000000000080a47f74657374320000000000000000000000000000000000000000000000000000006000571ca08a8bbf888cfa37bbf0bb965423625641fc956967b81d12e23709cead01446075a01ce999b56a8a88504be365442ea61239198e23d1fce7d00fcfc5cd3b44b7215f

    meterify.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
    .on('receipt', console.log);

    > // see eth.getTransactionReceipt() for details
```

## sign

```javascript
    meterify.eth.sign(dataToSign, address [, callback])
```

Signs data using a specific account. This account needs to be unlocked.

**Parameters:**

| Property   | Type                 | Description                                                                                                                                                                                |
| ---------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| dataToSign | `String`             | Data to sign. If String it will be converted using [`meterify.utils.utf8ToHex`](/developer-documentation/meterify-api-documentation/meterify.utils#utf-8-tohex).                           |
| address    | `String` or `Number` | Address to sign data with. Or an address or index of a local wallet in [`meterify.eth.accounts.wallet`](/developer-documentation/meterify-api-documentation/meterify.eth.accounts#wallet). |
| callback   | `Function`           | (optional) Optional callback, returns an error object as first parameter and the result as second.                                                                                         |

Note: The 2. `address` parameter can also be an address or index from the [`meterify.eth.accounts.wallet`](/developer-documentation/meterify-api-documentation/meterify.eth.accounts#wallet). It will then sign locally using the private key of this account.

**Returns:**

| Type              | Description    |
| ----------------- | -------------- |
| `Promise<string>` | The signature. |

**Example:**

```javascript
    meterify.eth.sign("Hello world", "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe")
    .then(console.log);
    > "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"

    // the below is the same
    meterify.eth.sign(meterify.utilsutf8ToHex("Hello world"), "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe")
    .then(console.log);
    > "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"
```

## signTransaction

```javascript
    meterify.eth.signTransaction(transactionObject [, address,] [, callback])
```

Signs a transaction with the private key of the given address. If the given address is a local unlocked account, the transaction will be signed locally.

**Parameters:**

| Property          | Type       | Description                                                                                                                                                 |
| ----------------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| transactionObject | `Object`   | The transaction data to sign [`meterify.eth.sendTransaction()`](/developer-documentation/meterify-api-documentation/meterify.eth#sendtransaction) for more. |
| address           | `string`   | The address of the account.                                                                                                                                 |
| callback          | `Function` | (optional) Optional callback, returns an error object as first parameter and the result as second.                                                          |

**Returns:**

| Type              | Description                                                                                                                                                                                                               |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Promise<object>` | The RLP encoded transaction. The `raw` property can be used to send the transaction using [`meterify.eth.sendSignedTransaction`](/developer-documentation/meterify-api-documentation/meterify.eth#sendsignedtransaction). |

**Example:**

```javascript
    meterify.eth.signTransaction({
        from: "0xEB014f8c8B418Db6b45774c326A0E64C78914dC0",
        gasPrice: "20000000000",
        gas: "21000",
        to: '0x3535353535353535353535353535353535353535',
        value: "1000000000000000000",
        data: ""
    }).then(console.log);
    > {
        raw: '0xf86c808504a817c800825208943535353535353535353535353535353535353535880de0b6b3a76400008025a04f4c17305743700648bc4f6cd3038ec6f6af0df73e31757007b7f59df7bee88da07e1941b264348e80c78c4027afc65a87b0a5e43e86742b8ca0823584c6788fd0',
        tx: {
            nonce: '0x0',
            gasPrice: '0x4a817c800',
            gas: '0x5208',
            to: '0x3535353535353535353535353535353535353535',
            value: '0xde0b6b3a7640000',
            input: '0x',
            v: '0x25',
            r: '0x4f4c17305743700648bc4f6cd3038ec6f6af0df73e31757007b7f59df7bee88d',
            s: '0x7e1941b264348e80c78c4027afc65a87b0a5e43e86742b8ca0823584c6788fd0',
            hash: '0xda3be87732110de6c1354c83770aae630ede9ac308d9f7b399ecfba23d923384'
        }
    }
```

## call

```javascript
    meterify.eth.call(callObject [, defaultBlock] [, callback])
```

Executes a message call transaction, which is directly executed in the VM of the node, but never mined into the blockchain.

**Parameters:**

| Property     | Type                 | Description                                                                                                                                                                                                              |
| ------------ | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| callObject   | `Object`             | A transaction object see [`meterify.eth.sendTransaction`](/developer-documentation/meterify-api-documentation/meterify.eth#sendtransaction), with the difference that for calls the `from` property is optional as well. |
| defaultBlock | `Number` or `String` | (optional) If you pass this parameter it will not use the default block set with [`meterify.eth.defaultBlock`](/developer-documentation/meterify-api-documentation/meterify.eth).                                        |
| callback     | `Function`           | (optional) Optional callback, returns an error object as first parameter and the result as second.                                                                                                                       |

**Returns:**

| Type              | Description                                                                  |
| ----------------- | ---------------------------------------------------------------------------- |
| `Promise<string>` | The returned data of the call, e.g. a smart contract functions return value. |

**Example:**

```javascript
    meterify.eth.call({
        to: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", // contract address
        data: "0xc6888fa10000000000000000000000000000000000000000000000000000000000000003"
    }).then(console.log);
    > "0x000000000000000000000000000000000000000000000000000000000000000a"
```

## estimateGas

```
    meterify.eth.estimateGas(callObject [, callback])
```

Executes a message call or transaction and returns the amount of the gas used.

**Parameters:**

| Property   | Type       | Description                                                                                                                                                                                                              |
| ---------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| callObject | `Object`   | A transaction object see [`meterify.eth.sendTransaction`](/developer-documentation/meterify-api-documentation/meterify.eth#sendtransaction), with the difference that for calls the `from` property is optional as well. |
| callback   | `Function` | (optional) Optional callback, returns an error object as first parameter and the result as second.                                                                                                                       |

**Returns:**

| Type              | Description                                      |
| ----------------- | ------------------------------------------------ |
| `Promise<number>` | The used gas for the simulated call/transaction. |

**Example:**

```javascript
    meterify.eth.estimateGas({
        to: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe",
        data: "0xc6888fa10000000000000000000000000000000000000000000000000000000000000003"
    }).then(console.log);
    > "0x0000000000000000000000000000000000000000000000000000000000000015"
```

## getPastLogs

```javascript
    meterify.eth.getPastLogs(options [, callback])
```

Gets past logs, matching the given options.

**Parameters:**

| Property | Type       | Description                    |
| -------- | ---------- | ------------------------------ |
| options  | `Object`   | The filter options as follows: |
| callback | `Function` | (optional) Optional callback,  |

**The `options` object:**

| Property    | Type                 | Description                                                                                                                                                                                                                                                             |
| ----------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `fromBlock` | `Number` or `String` | The number of the earliest block (`"latest"` may be given to mean the most recent and `"pending"` currently mining, block). By default `"latest"`.                                                                                                                      |
| `toBlock`   | `Number` or `String` | The number of the latest block (`"latest"` may be given to mean the most recent and `"pending"` currently mining, block). By default `"latest"`.                                                                                                                        |
| `address`   | `String` or `Array`  | An address or a list of addresses to only get logs from particular account(s).                                                                                                                                                                                          |
| `topics`    | `Array`              | An array of values which must each appear in the log entries. The order is important, if you want to leave topics out use `null`, e.g. `[null, '0x12...']`. You can also pass an array for each topic with options for that topic e.g. `[null, ['option1', 'option2']]` |

**Returns:**

| Type             | Description           |
| ---------------- | --------------------- |
| `Promise<Array>` | Array of log objects. |

**The structure of the returned event `Object` in the `Array` looks as follows:**

| Name                       | Type     | Description                                                                           |
| -------------------------- | -------- | ------------------------------------------------------------------------------------- |
| `address`                  | `String` | From which this event originated from.                                                |
| `data`                     | `String` | The data containing non-indexed log parameter.                                        |
| `topics`                   | `Array`  | An array with max 4 32 Byte topics, topic 1-3 contains indexed parameters of the log. |
| `logIndex`                 | `Number` | Integer of the event index position in the block.                                     |
| `transactionIndex`         | `Number` | Integer of the transaction's index position, the event was created in.                |
| `transactionHash` 32 Bytes | `String` | Hash of the transaction this event was created in.                                    |
| `blockHash` 32 Bytes       | `String` | Hash of the block where this event was created in. `null` when its still pending.     |
| `blockNumber`              | `Number` | The block number where this log was created in. `null` when still pending.            |

**Example:**

```javascript
    meterify.eth.getPastLogs({
        address: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe",
        topics: ["0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234"]
    }).then(console.log);
    > [{
        data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
        topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
        logIndex: 0,
        transactionIndex: 0,
        transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
        blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
        blockNumber: 1234,
        address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
    },{...}]
```

## getWork

```javascript
    meterify.eth.getWork([callback])
```

Gets work for miners to mine on. Returns the hash of the current block, the seedHash, and the boundary condition to be met ("target").

**Parameters:**

| Property | Type       | Description                                                                                        |
| -------- | ---------- | -------------------------------------------------------------------------------------------------- |
| callback | `Function` | (optional) Optional callback, returns an error object as first parameter and the result as second. |

**Returns:**

| Type             | Description                                   |
| ---------------- | --------------------------------------------- |
| `Promise<Array>` | The mining work with the following structure: |

| Type                               | Description                                            |
| ---------------------------------- | ------------------------------------------------------ |
| `String` 32 Bytes - at **index 0** | current block header pow-hash                          |
| `String` 32 Bytes - at **index 1** | the seed hash used for the DAG.                        |
| `String` 32 Bytes - at **index 2** | the boundary condition ("target"), 2^256 / difficulty. |

**Example:**

```javascript
    meterify.eth.getWork().then(console.log);
    > [
      "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
      "0x5EED00000000000000000000000000005EED0000000000000000000000000000",
      "0xd1ff1c01710000000000000000000000d1ff1c01710000000000000000000000"
    ]
```

## submitWork

```
    meterify.eth.submitWork(nonce, powHash, digest, [callback])
```

Used for submitting a proof-of-work solution.

**Parameters:**

| Property | Type              | Description                                                                                        |
| -------- | ----------------- | -------------------------------------------------------------------------------------------------- |
| nonce    | `String` 8 Bytes  | The nonce found (64 bits)                                                                          |
| powHash  | `String` 32 Bytes | The header's pow-hash (256 bits)                                                                   |
| digest   | `String` 32 Bytes | The mix digest (256 bits)                                                                          |
| callback | `Function`        | (optional) Optional callback, returns an error object as first parameter and the result as second. |

**Returns:**

| Type               | Description                                                        |
| ------------------ | ------------------------------------------------------------------ |
| `Promise<boolean>` | Returns `true` if the provided solution is valid, otherwise false. |

**Example:**

```javascript
    meterify.eth.submitWork([
        "0x0000000000000001",
        "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
        "0xD1FE5700000000000000000000000000D1FE5700000000000000000000000000"
    ])
    .then(console.log);
    > true
```

## requestAccounts

```javascript
    meterify.eth.requestAccounts([callback])
```

This method will request/enable the accounts from the current environment it is running (Metamask, Status or Mist). It doesn't work if you're connected to a node with a default Web3.js provider (WebsocketProvider, HttpProvidder and IpcProvider). This method will only work if you're using the injected provider from an application like Status, Mist or Metamask.

For further information about the behavior of this method please read the EIP of it: [`EIP-1102`](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1102.md)

**Parameters:**

| Property | Type       | Description                                                                                        |
| -------- | ---------- | -------------------------------------------------------------------------------------------------- |
| callback | `Function` | (optional) Optional callback, returns an error object as first parameter and the result as second. |

**Returns:**

| Type             | Description                           |
| ---------------- | ------------------------------------- |
| `Promise<Array>` | Returns an array of enabled accounts. |

**Example:**

```javascript
    meterify.eth.requestAccounts().then(console.log);
    > ['0aae0B295369a9FD31d5F28D9Ec85E40f4cb692BAf', 0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe]
```

## getChainId

```javascript
    meterify.eth.getChainId([callback])
```

Returns the chain ID of the current connected node as described in [`EIP-695`](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-695.md).

**Returns:**

| Type              | Description       |
| ----------------- | ----------------- |
| `Promise<Number>` | Returns chain ID. |

**Example:**

```javascript
    meterify.eth.getChainId().then(console.log);
    > 61
```

## getNodeInfo

```javascript
    meterify.eth.getNodeInfo([callback])
```

**Returns:**

| Type              | Description                 |
| ----------------- | --------------------------- |
| `Promise<String>` | The current client version. |

**Example:**

```javascript
    meterify.eth.getNodeInfo().then(console.log);
    > "Mist/v0.9.3/darwin/go1.4.1"
```

## getProof

```javascript
    meterify.eth.getProof(address, storageKey, blockNumber, [callback])
```

Returns the account and storage-values of the specified account including the Merkle-proof as described in [`EIP-1186`](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1186.md).

**Parameters:**

| Property    | Type                                               | Description                                                                                                                                                                   |
| ----------- | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| address     | `String` 20 Bytes                                  | The Address of the account or contract.                                                                                                                                       |
| storageKey  | `Array` 32 Bytes                                   | Array of storage-keys which should be proofed and included. See [`meterify.eth.getStorageAt`](/developer-documentation/meterify-api-documentation/meterify.eth#getstorageat). |
| blockNumber | `Number` or `String` or `"latest"` or `"earliest"` | Integer block number, or the string "latest" or "earliest".                                                                                                                   |
| callback    | `Function`                                         | (optional) Optional callback, returns an error object as first parameter and the result as second.                                                                            |

**Returns:**

| Type              | Description       |
| ----------------- | ----------------- |
| `Promise<Object>` | A account object. |

**The account object:**

| Property       | Description                                                                                                                                            |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `balance`      | The balance of the account. See [`meterify.eth.getBalance`](/developer-documentation/meterify-api-documentation/meterify.eth#getbalance).              |
| `codeHash`     | Hash of the code of the account. For a simple Account without code it will return "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470" |
| `nonce`        | Nonce of the account.                                                                                                                                  |
| `storageHash`  | SHA3 of the StorageRoot. All storage will deliver a MerkleProof starting with this rootHash.                                                           |
| `accountProof` | Array of rlp-serialized MerkleTree-Nodes, starting with the stateRoot-Node, following the path of the SHA3 (address) as key.                           |
| `storageProof` | Array of storage-entries as requested.                                                                                                                 |
| `key`          | The requested storage key.                                                                                                                             |
| `value`        | The storage value.                                                                                                                                     |

**Example:**

```javascript
    meterify.eth.getProof(
        "0x1234567890123456789012345678901234567890",
        ["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001"],
        "latest"
    ).then(console.log);
    > {
        "address": "0x1234567890123456789012345678901234567890",
        "accountProof": [
            "0xf90211a090dcaf88c40c7bbc95a912cbdde67c175767b31173df9ee4b0d733bfdd511c43a0babe369f6b12092f49181ae04ca173fb68d1a5456f18d20fa32cba73954052bda0473ecf8a7e36a829e75039a3b055e51b8332cbf03324ab4af2066bbd6fbf0021a0bbda34753d7aa6c38e603f360244e8f59611921d9e1f128372fec0d586d4f9e0a04e44caecff45c9891f74f6a2156735886eedf6f1a733628ebc802ec79d844648a0a5f3f2f7542148c973977c8a1e154c4300fec92f755f7846f1b734d3ab1d90e7a0e823850f50bf72baae9d1733a36a444ab65d0a6faaba404f0583ce0ca4dad92da0f7a00cbe7d4b30b11faea3ae61b7f1f2b315b61d9f6bd68bfe587ad0eeceb721a07117ef9fc932f1a88e908eaead8565c19b5645dc9e5b1b6e841c5edbdfd71681a069eb2de283f32c11f859d7bcf93da23990d3e662935ed4d6b39ce3673ec84472a0203d26456312bbc4da5cd293b75b840fc5045e493d6f904d180823ec22bfed8ea09287b5c21f2254af4e64fca76acc5cd87399c7f1ede818db4326c98ce2dc2208a06fc2d754e304c48ce6a517753c62b1a9c1d5925b89707486d7fc08919e0a94eca07b1c54f15e299bd58bdfef9741538c7828b5d7d11a489f9c20d052b3471df475a051f9dd3739a927c89e357580a4c97b40234aa01ed3d5e0390dc982a7975880a0a089d613f26159af43616fd9455bb461f4869bfede26f2130835ed067a8b967bfb80",
            "0xf90211a0395d87a95873cd98c21cf1df9421af03f7247880a2554e20738eec2c7507a494a0bcf6546339a1e7e14eb8fb572a968d217d2a0d1f3bc4257b22ef5333e9e4433ca012ae12498af8b2752c99efce07f3feef8ec910493be749acd63822c3558e6671a0dbf51303afdc36fc0c2d68a9bb05dab4f4917e7531e4a37ab0a153472d1b86e2a0ae90b50f067d9a2244e3d975233c0a0558c39ee152969f6678790abf773a9621a01d65cd682cc1be7c5e38d8da5c942e0a73eeaef10f387340a40a106699d494c3a06163b53d956c55544390c13634ea9aa75309f4fd866f312586942daf0f60fb37a058a52c1e858b1382a8893eb9c1f111f266eb9e21e6137aff0dddea243a567000a037b4b100761e02de63ea5f1fcfcf43e81a372dafb4419d126342136d329b7a7ba032472415864b08f808ba4374092003c8d7c40a9f7f9fe9cc8291f62538e1cc14a074e238ff5ec96b810364515551344100138916594d6af966170ff326a092fab0a0d31ac4eef14a79845200a496662e92186ca8b55e29ed0f9f59dbc6b521b116fea090607784fe738458b63c1942bba7c0321ae77e18df4961b2bc66727ea996464ea078f757653c1b63f72aff3dcc3f2a2e4c8cb4a9d36d1117c742833c84e20de994a0f78407de07f4b4cb4f899dfb95eedeb4049aeb5fc1635d65cf2f2f4dfd25d1d7a0862037513ba9d45354dd3e36264aceb2b862ac79d2050f14c95657e43a51b85c80",
            "0xf90171a04ad705ea7bf04339fa36b124fa221379bd5a38ffe9a6112cb2d94be3a437b879a08e45b5f72e8149c01efcb71429841d6a8879d4bbe27335604a5bff8dfdf85dcea00313d9b2f7c03733d6549ea3b810e5262ed844ea12f70993d87d3e0f04e3979ea0b59e3cdd6750fa8b15164612a5cb6567cdfb386d4e0137fccee5f35ab55d0efda0fe6db56e42f2057a071c980a778d9a0b61038f269dd74a0e90155b3f40f14364a08538587f2378a0849f9608942cf481da4120c360f8391bbcc225d811823c6432a026eac94e755534e16f9552e73025d6d9c30d1d7682a4cb5bd7741ddabfd48c50a041557da9a74ca68da793e743e81e2029b2835e1cc16e9e25bd0c1e89d4ccad6980a041dda0a40a21ade3a20fcd1a4abb2a42b74e9a32b02424ff8db4ea708a5e0fb9a09aaf8326a51f613607a8685f57458329b41e938bb761131a5747e066b81a0a16808080a022e6cef138e16d2272ef58434ddf49260dc1de1f8ad6dfca3da5d2a92aaaadc58080",
            "0xf851808080a009833150c367df138f1538689984b8a84fc55692d3d41fe4d1e5720ff5483a6980808080808080808080a0a319c1c415b271afc0adcb664e67738d103ac168e0bc0b7bd2da7966165cb9518080"
            ],
            "balance": 0,
            "codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470",
            "nonce": 0,
            "storageHash": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
            "storageProof": [
            {
                "key": "0x0000000000000000000000000000000000000000000000000000000000000000",
                "value": '0',
                "proof": []
            },
            {
                "key": "0x0000000000000000000000000000000000000000000000000000000000000001",
                "value": '0',
                "proof": []
            }
        ]
    }
```


# meterify.eth.Contract

The `meterify.eth.Contract` object makes it easy to interact with smart contracts on the Meter blockchain. When you create a new contract object, you give it the json interface of the respective smart contract and web3 will auto convert all calls into low level ABI calls over RPC for you.

This allows you to interact with smart contracts as if they were JavaScript objects.

**To use it standalone:**

```javascript


    import {Contract} from 'web3-eth-contract';
    import {Accounts} from 'web3-eth-accounts';

    const contract = new Contract(
        'ws://localhost:8546',
        new Accounts('ws://localhost:8546', options),
        abi,
        address,
        options
    );

    contract.methods.somFunc().send({from: ....}).on('receipt', () => {
        ...
    });
```

## meterify.eth.Contract <a href="#meterify-eth-contract-2" id="meterify-eth-contract-2"></a>

```javascript
    new meterify.eth.Contract(jsonInterface, address, options);
```

Creates a new contract instance with all its methods and events defined in its [`json interface`](/developer-documentation/meterify-api-documentation/json-interface) object.

**Example:**

```javascript

    const myContract = new meterify.eth.Contract([...], '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe', {
        defaultAccount: '0x1234567890123456789012345678901234567891', // default from address
        defaultGasPrice: '20000000000' // default gas price in wei, 20 gwei in this case
    });
```

**Parameters:**

1. `jsonInterface` - `Array`: The json interface for the contract to instantiate
2. `address` - `String` (optional): This address is necessary for transactions and call requests and can also be added later using `myContract.options.address = '0x1234..'.`
3. `options` - `Object` (optional): The options of the contract. Some are used as fallbacks for calls and transactions:
   * `data` - `String`: The byte code of the contract. Used when the contract gets [`deployed`](/developer-documentation/meterify-api-documentation/meterify.eth.contract#deploy).
   * `address` - `String`: The address where the contract is deployed. See [`address`](/developer-documentation/meterify-api-documentation/meterify.eth.contract#address).
   * [`defaultAccount`](/developer-documentation/meterify-api-documentation/meterify.module.options#defaultaccount)
   * [`defaultBlock`](/developer-documentation/meterify-api-documentation/meterify.module.options#defaultblock)
   * [`defaultGas`](/developer-documentation/meterify-api-documentation/meterify.module.options#defaultgas)
   * [`defaultGasPrice`](/developer-documentation/meterify-api-documentation/meterify.module.options#defaultgasprice)
   * [`transactionBlockTimeout`](/developer-documentation/meterify-api-documentation/meterify.module.options#transactionblocktimeout)
   * [`transactionConfirmationBlocks`](/developer-documentation/meterify-api-documentation/meterify.module.options#transactionconfirmationblocks)
   * [`transactionPollingTimeout`](/developer-documentation/meterify-api-documentation/meterify.module.options#transactionpollingtimeout)
   * [`transactionSigner`](/developer-documentation/meterify-api-documentation/meterify.module.options#transactionsigner)

**Returns:**

`Object`: The contract instance with all its methods and events.

## Properties <a href="#properties" id="properties"></a>

### options

The contract options object has the following properties:

* `data` - `String`: The contract bytecode.
* `address` - `String` (deprecated use `contract.address`): The address of the contract.

### address   &#x20;

```javascript
myContract.address
```

The address used for this contract instance.

**Example:**   &#x20;

```javascript
myContract.address;
> '0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae'

// set a new address
myContract.address = '0x1234FFDD...';
```

All transactions generated by web3.js from this contract will contain this address as the "to".

The address will be stored in lowercase.

**Property:**

`address` - `String` or null: The address for this contract, or `null` if it is not yet set.

### jsonInterface   &#x20;

```
myContract.jsonInterface
```

The [`json interface`](/developer-documentation/meterify-api-documentation/json-interface) object derived from the [ABI](https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI) of this contract.

Property

`jsonInterface` - `AbiModel`: The [`json interface`](/developer-documentation/meterify-api-documentation/json-interface) for this contract. Re-setting this will regenerate the methods and events of the contract instance.

## AbiModel <a href="#abimodel" id="abimodel"></a>

```javascript

    interface AbiModel {
        getMethod(name: string): AbiItemModel | false;
        getMethods(): AbiItemModel[];
        hasMethod(name: string): boolean;
        getEvent(name: string): AbiItemModel | false;
        getEvents(): AbiItemModel[];
        getEventBySignature(signature: string): AbiItemModel;
        hasEvent(name: string): boolean;
    }
```

## AbiItemModel <a href="#abiitemmodel" id="abiitemmodel"></a>

```javascript
    interface AbiItemModel {
        name: string;
        signature: string;
        payable: boolean;
        anonymous: boolean;
        getInputLength(): Number;
        getInputs(): AbiInput[];
        getIndexedInputs(): AbiInput[];
        getOutputs(): AbiOutput[];
        isOfType(): boolean;
    }
```

## AbiInput <a href="#abiinput" id="abiinput"></a>

```javascript
    interface AbiInput {
        name: string;
        type: string;
        indexed?: boolean;
        components?: AbiInput[];
    }
```

## AbiOutput <a href="#abioutput" id="abioutput"></a>

```javascript
    interface AbiOutput {
        name: string;
        type: string;
        components?: AbiOutput[];
    }
```

## Methods <a href="#methods" id="methods"></a>

### clone <a href="#clone" id="clone"></a>

```
myContract.clone()
```

Clones the current contract instance.

**Example:**

```javascript
    const contract1 = new eth.Contract(abi, address, {gasPrice: '12345678', defaultAccount: fromAddress});

    const contract2 = contract1.clone();
    contract2.address = address2;

    (contract1.address !== contract2.address);

Returns

    > true
```

**Parameters:**

none

**Returns:**

`Object`: The new contract instance.

### deploy   &#x20;

```
myContract.deploy(options)
```

Call this function to deploy the contract to the blockchain.

**Example:**

```javascript
myContract.deploy({
        data: '0x12345...',
        arguments: [123, 'My String']
    })
    .send({
        from: '0x1234567890123456789012345678901234567891',
        gas: 1500000,
        gasPrice: '30000000000000'
    }, (error, transactionHash) => { ... })
    .on('error', (error) => { ... })
    .on('transactionHash', (transactionHash) => { ... })
    .on('receipt', (receipt) => {
       console.log(receipt.contractAddress) // contains the new contract address
    })
    .on('confirmation', (confirmationNumber, receipt) => { ... })
    .then((newContractInstance) => {
        console.log(newContractInstance.options.address) // instance with the new contract address
    });

    // When the data is already set as an option to the contract itself
    myContract.options.data = '0x12345...';

    myContract.deploy({
        arguments: [123, 'My String']
    })
    .send({
        from: '0x1234567890123456789012345678901234567891',
        gas: 1500000,
        gasPrice: '30000000000000'
    })
    .then((newContractInstance) => {
        console.log(newContractInstance.options.address) // instance with the new contract address
    });


    // Simply encoding
    myContract.deploy({
        data: '0x12345...',
        arguments: [123, 'My String']
    })
    .encodeABI();
    > '0x12345...0000012345678765432'


    // Gas estimation
    myContract.deploy({
        data: '0x12345...',
        arguments: [123, 'My String']
    })
    .estimateGas((err, gas) => {
        console.log(gas);
    });
```

After successful deployment the promise will resolve with a new contract instance.

**Parameters:**

* `options` - `Object`: The options used for deployment.
* `data` - `String`: The byte code of the contract.
* `arguments` - `Array` (optional): The arguments which get passed to the constructor on deployment.

**Returns:**

`Object`: The transaction object:

* `Array` - arguments: The arguments passed to the method before. They can be changed.`Function` - `send`(#contract-send): Will deploy the contract. The promise will resolve with the new contract instance, instead of the receipt!
* `Function` - [`estimateGas`](https://docs.meter.io/meterify.eth.Contract.html#contract-estimateGas): Will estimate the gas used for deploying.
* `Function` - [`encodeABI`](https://docs.meter.io/meterify.eth.Contract.html#contract-encodeABI): Encodes the ABI of the deployment, which is contract data + constructor parameters

For details to the methods see the documentation below.

### methods

```javascript
myContract.methods.myMethod([param1[, param2[, ...]]])
```

Creates a transaction object for that method, which then can be [`called`](/developer-documentation/meterify-api-documentation/meterify.eth.contract#methods-mymethod-call), [`send`](/developer-documentation/meterify-api-documentation/meterify.eth.contract#methods-mymethod-send), [`estimated`](/developer-documentation/meterify-api-documentation/meterify.eth.contract#methods-mymethod-estimategas) or [`ABI encoded`](/developer-documentation/meterify-api-documentation/meterify.eth.contract#methods-mymethod-encodeabi).

The methods of this smart contract are available through:

* The name: `myContract.methods.myMethod(123)`
* The name with parameters: `myContract.methods['myMethod(uint256)'](123)`
* The signature: `myContract.methods['0x58cf5f10'](123)`

This allows calling functions with same name but different parameters from the JavaScript contract object.

**Example:**

```

    // calling a method

    myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}, (error, result) => {
        ...
    });

    // or sending and using a promise
    myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
    .then((receipt) => {
        // receipt can also be a new contract instance, when coming from a "contract.deploy({...}).send()"
    });

    // or sending and using the events

    myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
    .on('transactionHash', (hash) => {
        ...
    })
    .on('receipt', (receipt) => {
        ...
    })
    .on('confirmation', (confirmationNumber, receipt) => {
        ...
    })
    .on('error', console.error);
```

#### Parameters: <a href="#parameters-2" id="parameters-2"></a>

Parameters of any method depend on the smart contracts methods, defined in the [`json interface`](/developer-documentation/meterify-api-documentation/json-interface).

**Returns:**

`Object`: The Transaction Object:

* `Array` - arguments: The arguments passed to the method before. They can be changed.
* `Function` - [`call`](/developer-documentation/meterify-api-documentation/meterify.eth.contract#methods-mymethod-call): Will call the "constant" method and execute its smart contract method in the EVM without sending a transaction (Can't alter the smart contract state).
* `Function` - [`send`](/developer-documentation/meterify-api-documentation/meterify.eth.contract#methods-mymethod-send): Will send a transaction to the smart contract and execute its method (Can alter the smart contract state).
* `Function` - [`estimateGas`](/developer-documentation/meterify-api-documentation/meterify.eth.contract#methods-mymethod-estimategas): Will estimate the gas used when the method would be executed on chain.
* `Function` - [`encodeABI`](/developer-documentation/meterify-api-documentation/meterify.eth.contract#methods-mymethod-encodeabi): Encodes the ABI for this method. This can be send using a transaction, call the method or passing into another smart contracts method as argument.

For details to the methods see the documentation below.

### methods.myMethod.call   &#x20;

```javascript
myContract.methods.myMethod([param1[, param2[, ...]]]).call(transactionObject, blockNumber, callback])
```

Will call a "constant" method and execute its smart contract method in the EVM without sending any transaction. Note calling can not alter the smart contract state.

**Example:**

```javascript
// using the callback
    myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}, (error, result) => {
        ...
    });

    // using the promise
    myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
    .then((result) => {
        ...
    });


    // MULTI-ARGUMENT RETURN:

    // Solidity
    contract MyContract {
        function myFunction() returns(uint256 myNumber, string myString) {
            return (23456, "Hello!%");
        }
    }

    // meterify
    const MyContract = new meterify.eth.Contract(abi, address);
    MyContract.methods.myFunction().call()
    .then(console.log);
    > Result {
        myNumber: '23456',
        myString: 'Hello!%',
        0: '23456', // these are here as fallbacks if the name is not know or given
        1: 'Hello!%'
    }


    // SINGLE-ARGUMENT RETURN:

    // Solidity
    contract MyContract {
        function myFunction() returns(string myString) {
            return "Hello!%";
        }
    }

    // meterify
    const MyContract = new meterify.eth.Contract(abi, address);
    MyContract.methods.myFunction().call()
    .then(console.log);
    > "Hello!%"
```

**Parameters:**

* `options` - `Object` (optional): The options used for calling.
  * `transactionObject` \* `from` - `String` (optional): The address the call "transaction" should be made from. &#x20;
  * `gasPrice` - `String` (optional): The gas price in wei to use for this call "transaction". It is the wei per unit of gas.&#x20;
  * `gas` - `Number` (optional): The maximum gas provided for this call "transaction" (gas limit).&#x20;
* `blockNumber` - `Number`: The block number this log was created in. `null` when still pending.&#x20;
* `callback` - `Function` (optional): This callback will be fired with the result of the smart contract method execution as the second argument, or with an error object as the first argument.

**Returns:**

`Promise<any>` - The return value(s) of the smart contract method. If it returns a single value, it's returned as is. If it has multiple return values they are returned as an object with properties and indices.

### methods.myMethod.send   &#x20;

```javascript
myContract.methods.myMethod([param1[, param2[, ...]]]).send(options[, callback])
```

Will send a transaction to the smart contract and execute its method. Note this can alter the smart contract state.

**Example:**&#x20;

```javascript
// using the callback
    myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}, (error, transactionHash) => {
        ...
    });

    // using the promise
    myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
    .then((receipt) => {
        // receipt can also be a new contract instance, when coming from a "contract.deploy({...}).send()"
    });


    // using the event emitter
    myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
    .on('transactionHash', (hash) => {
        ...
    })
    .on('confirmation', (confirmationNumber, receipt) => {
        ...
    })
    .on('receipt', (receipt) => {
        // receipt example
        console.log(receipt);
        > {
            "transactionHash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
            "transactionIndex": 0,
            "blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
            "blockNumber": 3,
            "contractAddress": "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe",
            "cumulativeGasUsed": 314159,
            "gasUsed": 30234,
            "events": {
                "MyEvent": {
                    returnValues: {
                        myIndexedParam: 20,
                        myOtherIndexedParam: '0x123456789...',
                        myNonIndexParam: 'My String'
                    },
                    raw: {
                        data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
                        topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
                    },
                    event: 'MyEvent',
                    signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
                    logIndex: 0,
                    transactionIndex: 0,
                    transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
                    blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
                    blockNumber: 1234,
                    address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
                },
                "MyOtherEvent": {
                    ...
                },
                "MyMultipleEvent":[{...}, {...}] // If there are multiple of the same event, they will be in an array
            }
        }
    })
    .on('error', console.error); // If there's an out of gas error the second parameter is the receipt.
```

**Parameters:**

1. `options` - `Object`: The options used for sending.
   1. `from` - `String`: The address the transaction should be sent from.
   2. `gasPrice` - `String` (optional): The gas price in wei to use for this transaction.It is the wei per unit of gas.
   3. `gas` - `Number` (optional): The maximum gas provided for this transaction (gas limit).
   4. `value` - `Number|String|BN|BigNumber`(optional): The value transferred for the transaction in wei.
2. `callback` - `Function` (optional): This callback will be fired first with the "transactionHash", or with an error object as the first argument.

**Returns:**

The **callback** will return the 32 bytes transaction hash.

`PromiEvent`: A [`promise combined event emitter`](/developer-documentation/meterify-api-documentation/callbacks-promises-events#promievent). Will be resolved when the transaction *receipt* is available, OR if this `send()` is called from a `someContract.deploy()`, then the promise will resolve with the *new contract instance*. Additionally the following events are available:

* `"transactionHash"` returns `String`: is fired right after the transaction is sent and a transaction hash is available.
* `"receipt"` returns `Object`: is fired when the transaction *receipt* is available. Receipts from contracts will have no `logs` property, but instead an `events` property with event names as keys and events as properties. See [`getPastEvents return values`](/developer-documentation/meterify-api-documentation/meterify.eth.contract#events) for details about the returned event object.
* `"confirmation"` returns `Number`, `Object`: is fired for every confirmation up to the 24th confirmation. Receives the confirmation number as the first and the receipt as the second argument. Fired from confirmation 1 on, which is the block where it's mined.
* `"error"` returns `Error`: is fired if an error occurs during sending. If an out of gas error, the second parameter is the receipt.

### methods.myMethod.estimateGas  &#x20;

```javascript
myContract.methods.myMethod([param1[, param2[, ...]]]).estimateGas(options[, callback])
```

Will call estimate the gas a method execution will take when executed in the EVM without sending a transaction.

**Example:** &#x20;

```javascript
// using the callback
    myContract.methods.myMethod(123).estimateGas({gas: 5000000}, function(error, gasAmount){
        if(gasAmount == 5000000)
            console.log('Method ran out of gas');
    });

    // using the promise
    myContract.methods.myMethod(123).estimateGas({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
    .then(function(gasAmount){
        ...
    })
    .catch(function(error){
        ...
    });
```

**Parameters:**

1. `options` - `Object` (optional): The options used for calling.
   1. `from` - `String` (optional): The address the call "transaction" should be made from.
   2. `gas` - `Number` (optional): The maximum gas provided for this call "transaction" (gas limit). Setting a specific value helps to detect out of gas errors. If all gas is used it will return the same number.
   3. `value` - `Number|String|BN|BigNumber`(optional): The value transferred for the call "transaction" in wei.
2. `callback` - `Function` (optional): This callback will be fired with the result of the gas estimation as the second argument, or with an error object as the first argument.

**Returns:**

`Promise( Number`) - The gas amount estimated.

### methods.myMethod.encodeABI   &#x20;

```javascript
myContract.methods.myMethod([param1[, param2[, ...]]]).encodeABI()
```

Encodes the ABI for this method. This can be used to send a transaction, call a method, or pass it into another smart contracts method as arguments.

**Example:**  &#x20;

```javascript
myContract.methods.myMethod(123).encodeABI();
> '0x58cf5f1000000000000000000000000000000000000000000000000000000000000007B'
```

**Parameters:**

none

**Returns:**

`String`: The encoded ABI byte code to send via a transaction or call.

## Events

### once

```javascript
myContract.once(event[, options], callback)
```

**Example:**

```javascript
myContract.once('MyEvent', {
        filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23
        fromBlock: 0
    }, (error, event) => { console.log(event); });

    // event output example
    > {
        returnValues: {
            myIndexedParam: 20,
            myOtherIndexedParam: '0x123456789...',
            myNonIndexParam: 'My String'
        },
        raw: {
            data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
            topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
        },
        event: 'MyEvent',
        signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
        logIndex: 0,
        transactionIndex: 0,
        transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
        blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
        blockNumber: 1234,
        address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
    }
```

**Parameters:**

1. `event` - `String`: The name of the event in the contract, or `"allEvents"` to get all events.`options` - `Object` (optional): The options used for deployment.`filter` - `Object` (optional): Lets you filter events by indexed parameters, e.g. `{filter: {myNumber: [12,13]}}` means all events where "myNumber" is 12 or 13.`topics` - `Array` (optional): This allows you to manually set the topics for the event filter. If given the filter property and event signature, (topic\[0]) will not be set automatically.
2. `callback` - `Function`: This callback will be fired for the first *event* as the second argument, or an error as the first argument. See [`getPastEvents return values`](/developer-documentation/meterify-api-documentation/meterify.eth.contract#getpastevents) for details about the event structure.

**Returns:**

`undefined`

### events   &#x20;

```javascript
myContract.events.MyEvent([options][, callback])
```

Subscribe to an event.

**Example:**

```javascript
myContract.events.MyEvent({
        filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23
        fromBlock: 0
    }, (error, event) => { console.log(event); })
    .on('data', (event) => {
        console.log(event); // same results as the optional callback above
    })
    .on('changed', (event) => {
        // remove event from local database
    })
    .on('error', console.error);

    // event output example
    > {
        returnValues: {
            myIndexedParam: 20,
            myOtherIndexedParam: '0x123456789...',
            myNonIndexParam: 'My String'
        },
        raw: {
            data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
            topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
        },
        event: 'MyEvent',
        signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
        logIndex: 0,
        transactionIndex: 0,
        transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
        blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
        blockNumber: 1234,
        address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
    }
```

**Parameters:**

1. `options` - `Object` (optional): The options used for deployment.
   1. `filter` - `Object` (optional): Let you filter events by indexed parameters, e.g. `{filter: {myNumber: [12,13]}}` means all events where "myNumber" is 12 or 13.
   2. `fromBlock` - `Number` (optional): The block number from which to get events on.
   3. `topics` - `Array` (optional): This allows to manually set the topics for the event filter. If given the filter property and event signature, (topic\[0]) will not be set automatically.
2. `callback` - `Function` (optional): This callback will be fired for each *event* as the second argument, or an error as the first argument.

**Returns:**

`EventEmitter`: The event emitter has the following events:

1. `"data"` returns `Object`: Fires on each incoming event with the event object as argument.
2. `"changed"` returns `Object`: Fires on each event which was removed from the blockchain. The event will have the additional property `"removed: true"`.
3. `"error"` returns `Object`: Fires when an error in the subscription occurs.

**The structure of the returned event `Object` looks as follows:**

1. `event` - `String`: The event name.
2. `signature` - `String|Null`: The event signature, `null` if it's an anonymous event.
3. `address` - `String`: Address this event originated from.`returnValues` - `Object`: The return values coming from the event, e.g. `{myVar: 1, myVar2: '0x234...'}`.
4. `logIndex` - `Number`: Integer of the event index position in the block.
5. `transactionIndex` - `Number`: Integer of the transaction's index position the event was created in.
6. `transactionHash` 32 Bytes - `String`: Hash of the transaction this event was created in.
7. `blockHash` 32 Bytes - `String`: Hash of the block this event was created in. `null` when it's still pending.
8. `blockNumber` - `Number`: The block number this log was created in. `null` when still pending.
9. `raw.data` - `String`: The data containing non-indexed log parameter.
10. `raw.topics` - `Array`: An array with max 4 32 Byte topics, topic 1-3 contains indexed parameters of the event.events.

### allEvents   &#x20;

```javascript
myContract.events.allEvents([options][, callback])
```

Same as [`events`](/developer-documentation/meterify-api-documentation/meterify.eth.contract#events-1) but receives all events from this smart contract. Optionally the filter property can filter those events.

### getPastEvents <a href="#getpastevents" id="getpastevents"></a>

```javascript
    myContract.getPastEvents(event[, options][, callback])
```

Gets past events for this contract.

**Example:**

```javascript

    myContract.getPastEvents('MyEvent', {
        filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23
        fromBlock: 0,
        toBlock: 'latest'
    }, (error, events) => { console.log(events); })
    .then((events) => {
        console.log(events) // same results as the optional callback above
    });

    > [{
        returnValues: {
            myIndexedParam: 20,
            myOtherIndexedParam: '0x123456789...',
            myNonIndexParam: 'My String'
        },
        raw: {
            data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
            topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
        },
        event: 'MyEvent',
        signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
        logIndex: 0,
        transactionIndex: 0,
        transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
        blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
        blockNumber: 1234,
        address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
    },{
        ...
    }]
```

**Parameters:**

1. `event` - `String`: The name of the event in the contract, or `"allEvents"` to get all events.
2. `options` - `Object` (optional): The options used for deployment.
   * `filter` - `Object` (optional): Lets you filter events by indexed parameters, e.g. `{filter: {myNumber: [12,13]}}` means all events where "myNumber" is 12 or 13.
   * `fromBlock` - `Number` (optional): The block number from which to get events on.
   * `toBlock` - `Number` (optional): The block number to get events up to (Defaults to `"latest"`).
   * `topics` - `Array` (optional): This allows manually setting the topics for the event filter. If given the filter property and event signature, (topic\[0]) will not be set automatically.
3. `callback` - `Function` (optional): This callback will be fired with an array of event logs as the second argument, or an error as the first argument.

**Returns:**

`Promise` returns `Array`: An array with the past event `Objects`, matching the given event name and filter.

For the structure of a returned event `Object` see [`getPastEvents return values`](/developer-documentation/meterify-api-documentation/meterify.eth.contract#getpastevents).


# meterify.eth.accounts

The `meterify.eth.accounts` contains functions to generate Meter accounts and sign transactions and data.&#x20;

Note: Take precautions to clear memory properly, store the private keys safely, and test transaction receiving and sending functionality properly before using in production!

```javascript
import {Accounts} from 'web3-eth-accounts';

    // Passing in the eth or web3 package is necessary to allow retrieving chainId, gasPrice and nonce automatically
    // for accounts.signTransaction().
    const accounts = new Accounts('ws://wstest.meter.io', null, options);
```

## create   &#x20;

```
meterify.eth.accounts.create([entropy]);
```

Generates an account object with private key and public key.

**Examples:**

```javascript
meterify.eth.accounts.create();
    > {
        address: "0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01",
        privateKey: "0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709",
        signTransaction: function(tx){...},
        sign: function(data){...},
        encrypt: function(password){...}
    }

    meterify.eth.accounts.create('2435@#@#@±±±±!!!!678543213456764321§34567543213456785432134567');
    > {
        address: "0xF2CD2AA0c7926743B1D4310b2BC984a0a453c3d4",
        privateKey: "0xd7325de5c2c1cf0009fac77d3d04a9c004b038883446b065871bc3e831dcd098",
        signTransaction: function(tx){...},
        sign: function(data){...},
        encrypt: function(password){...}
    }

    meterify.eth.accounts.create(web3.utils.randomHex(32));
    > {
        address: "0xe78150FaCD36E8EB00291e251424a0515AA1FF05",
        privateKey: "0xcc505ee6067fba3f6fc2050643379e190e087aeffe5d958ab9f2f3ed3800fa4e",
        signTransaction: function(tx){...},
        sign: function(data){...},
        encrypt: function(password){...}
    }
```

**Parameters:**

1. `entropy` - `String`(optional): A random string to increase entropy. If given it should be at least 32 characters. If none is given a random string will be generated using [`randomhex`](/developer-documentation/meterify-api-documentation/meterify.utils#randomhex).

**Returns:**

`Object` - The account object with the following structure:

1. `address` - `String`: The account address.&#x20;
2. `privateKey` - `String`: The accounts private key. This should never be shared or stored unencrypted in local storage! Also make sure to `null` the memory after usage.&#x20;
3. `signTransaction(tx [, callback])` - `Function`: The function to sign transactions. See [`meterify.eth.accounts.signTransaction()`](/developer-documentation/meterify-api-documentation/meterify.eth.accounts#signtransaction) for more.&#x20;
4. `sign(data)` - `Function`: The function to sign transactions. See [`meterify.eth.accounts.sign()`](/developer-documentation/meterify-api-documentation/meterify.eth.accounts#sign) for more.

## privateKeyToAccount <a href="#privatekeytoaccount" id="privatekeytoaccount"></a>

```javascript
meterify.eth.accounts.privateKeyToAccount(privateKey);
```

Creates an account object from a private key.

#### Parameters <a href="#parameters-2" id="parameters-2"></a>

```javascript

    meterify.eth.accounts.privateKeyToAccount('0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709');
    > {
        address: '0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01',
        privateKey: '0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709',
        signTransaction: function(tx){...},
        sign: function(data){...},
        encrypt: function(password){...}
    }
```

**Parameters:**

1. `privateKey` - `String`: The private key hex string beginning with `0x`.

**Returns:**

`Object` - The account object with the [`structure seen here`](/developer-documentation/meterify-api-documentation/meterify.eth.accounts#create).

## signTransaction

```javascript
meterify.eth.accounts.signTransaction(tx, privateKey [, callback]);
```

Signs a Meter transaction with a given private key.

#### Parameters <a href="#parameters-2" id="parameters-2"></a>

```javascript
meterify.eth.accounts.signTransaction({
        to: '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55',
        value: '1000000000',
        gas: 2000000,
        gasPrice: '234567897654321',
        nonce: 0,
        chainId: 1
    }, '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318')
    .then(console.log);
```

#### Parameters <a href="#parameters-2" id="parameters-2"></a>

```javascript
> {
        messageHash: '0x6893a6ee8df79b0f5d64a180cd1ef35d030f3e296a5361cf04d02ce720d32ec5',
        r: '0x9ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9c',
        s: '0x440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428',
        v: '0x25',
        rawTransaction: '0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428',
        transactionHash: '0xd8f64a42b57be0d565f385378db2f6bf324ce14a594afc05de90436e9ce01f60'
    }
```

#### Parameters <a href="#parameters-2" id="parameters-2"></a>

1. `tx` - `Object`: The transaction's properties object as follows:
   1. `nonce` - `String`: (optional) The nonce to use when signing this transaction. Default will use [`meterify.eth.getTransactionCount()`](/developer-documentation/meterify-api-documentation/meterify.eth#gettransactioncount).
   2. `chainId` - `String`: (optional) The chain id to use when signing this transaction. Default will use [`meterify.eth.net.getChainId()`](/developer-documentation/meterify-api-documentation/meterify.eth#getchainid).
   3. `to` - `String`: (optional) The receiver of the transaction, can be empty when deploying a contract.
   4. `data` - `String`: (optional) The call data of the transaction, can be empty for simple value transfers.
   5. `value` - `String`: (optional) The value of the transaction in wei.
   6. `gasPrice` - `String`: (optional) The gas price set by this transaction. If empty, it will use [`meterify.eth.getGasPrice()`](/developer-documentation/meterify-api-documentation/meterify.eth#getgasprice)
   7. `gas` - `String`: The gas provided by the transaction.
2. `privateKey` - `String`: The private key to sign with.
3. `callback` - `Function`: (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

`Promise` returning `Object`: The signed data RLP encoded transaction, or if `returnSignature` is `true` the signature values as follows:&#x20;

1. `messageHash` - `String`: The hash of the given message.&#x20;
2. `r` - `String`: First 32 bytes of the signature
3. `s` - `String`: Next 32 bytes of the signature
4. `v` - `String`: Recovery value + 27
5. `rawTransaction` - `String`: The RLP encoded transaction, ready to be send using [`meterify.eth.sendSignedTransaction`](/developer-documentation/meterify-api-documentation/meterify.eth#sendsignedtransaction).
6. `transactionHash` - `String`: The transaction hash for the RLP encoded transaction.

## recoverTransaction <a href="#recovertransaction" id="recovertransaction"></a>

```javascript
    meterify.eth.accounts.recoverTransaction(rawTransaction);
```

Recovers the Meter address which was used to sign the given RLP encoded transaction.

**Example:**

```javascript
    meterify.eth.accounts.recoverTransaction('0xf86180808401ef364594f0109fc8df283027b6285cc889f5aa624eac1f5580801ca031573280d608f75137e33fc14655f097867d691d5c4c44ebe5ae186070ac3d5ea0524410802cdc025034daefcdfa08e7d2ee3f0b9d9ae184b2001fe0aff07603d9');
    > "0xF0109fC8DF283027b6285cc889F5aA624EaC1F55"
```

**Parameters:**

1. `signature` - `String`: The RLP encoded transaction.

**Returns:**

`String`: The Meter address used to sign this transaction.

## hashMessage <a href="#hashmessage" id="hashmessage"></a>

```javascript
    meterify.eth.accounts.hashMessage(message);
```

Hashes the given message to be passed [`meterify.eth.accounts.recover()`](/developer-documentation/meterify-api-documentation/meterify.eth.accounts#recover) function.&#x20;

The data will be UTF-8 HEX decoded and enveloped as follows: `"\x19Ethereum Signed Message:\n" + message.length + message` and hashed using keccak256.

**Example:**

```javascript

    meterify.eth.accounts.hashMessage("Hello World")
    > "0xa1de988600a42c4b4ab089b619297c17d53cffae5d5120d82d8a92d0bb3b78f2"

    // the below results in the same hash
    meterify.eth.accounts.hashMessage(web3.utils.utf8ToHex("Hello World"))
    > "0xa1de988600a42c4b4ab089b619297c17d53cffae5d5120d82d8a92d0bb3b78f2"
```

**Parameters:**

1. `message` - `String`: A message to hash, if it's HEX it will be UTF8 decoded before.

**Returns:**

`String`: The hashed message

## sign   &#x20;

```javascript
meterify.eth.accounts.sign(data, privateKey);
```

Signs arbitrary data. This data is before UTF-8 HEX decoded and enveloped as follows: `"\x19Ethereum Signed Message:\n" + message.length + message`.

#### Parameters <a href="#parameters-2" id="parameters-2"></a>

```javascript
meterify.eth.accounts.sign('Some data', '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318');
    > {
        message: 'Some data',
        messageHash: '0x1da44b586eb0729ff70a73c326926f6ed5a25f5b056e7f47fbc6e58d86871655',
        v: '0x1c',
        r: '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd',
        s: '0x6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a029',
        signature: '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a0291c'
    }
```

**Parameters:**

1. `data` - `String`: The data to sign.&#x20;
2. `privateKey` - `String`: The private key to sign with.

**Returns:**

`Object`: The signed data RLP encoded signature, or if `returnSignature` is `true` the signature values as follows:&#x20;

1. `message` - `String`: The the given message.&#x20;
2. `messageHash` - `String`: The hash of the given message.
3. `r` - `String`: First 32 bytes of the signature.
4. `s` - `String`: Next 32 bytes of the signature.
5. `v` - `String`: Recovery value + 27.

## recover   &#x20;

```javascript
meterify.eth.accounts.recover(signatureObject);    
meterify.eth.accounts.recover(message, signature [, preFixed]);    
meterify.eth.accounts.recover(message, v, r, s [, preFixed]);
```

Recovers the Meter address which was used to sign the given data.

#### Parameters <a href="#parameters-2" id="parameters-2"></a>

```javascript
meterify.eth.accounts.recover({
        messageHash: '0x1da44b586eb0729ff70a73c326926f6ed5a25f5b056e7f47fbc6e58d86871655',
        v: '0x1c',
        r: '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd',
        s: '0x6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a029'
    })
    > "0x2c7536E3605D9C16a7a3D7b1898e529396a65c23"

    // message, signature
    meterify.eth.accounts.recover('Some data', '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a0291c');
    > "0x2c7536E3605D9C16a7a3D7b1898e529396a65c23"

    // message, v, r, s
    meterify.eth.accounts.recover('Some data', '0x1c', '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd', '0x6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a029');
    > "0x2c7536E3605D9C16a7a3D7b1898e529396a65c23"
```

#### Parameters: <a href="#parameters-2" id="parameters-2"></a>

1. `message` or `signatureObject` - `String` or `Object`: Either signed message or hash, or the signature object as following values:
   1. `messageHash` - `String`: The hash of the given message already prefixed with `"\x19Ethereum Signed Message:\n" + message.length + message`.
   2. `r` - `String`: First 32 bytes of the signature.
   3. `s` - `String`: Next 32 bytes of the signature.
   4. `v` - `String`: Recovery value + 27
2. `signature` - `String`: The raw RLP encoded signature, OR parameter 2-4 as v, r, s values.
3. `preFixed` - `Boolean` (optional, default: `false`): If the last parameter is `true`, the given message will NOT automatically be prefixed with `"\x19Ethereum Signed Message:\n" + message.length + message`, and assumed to be already prefixed.

**Returns:**

`String`: The Meter address used to sign this data.

## encrypt   &#x20;

```javascript
meterify.eth.accounts.encrypt(privateKey, password);
```

Encrypts a private key to the web3 keystore v3 standard.

**Example:**

```javascript
meterify.eth.accounts.encrypt('0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318', 'test!')
    > {
        version: 3,
        id: '04e9bcbb-96fa-497b-94d1-14df4cd20af6',
        address: '2c7536e3605d9c16a7a3d7b1898e529396a65c23',
        crypto: {
            ciphertext: 'a1c25da3ecde4e6a24f3697251dd15d6208520efc84ad97397e906e6df24d251',
            cipherparams: { iv: '2885df2b63f7ef247d753c82fa20038a' },
            cipher: 'aes-128-ctr',
            kdf: 'scrypt',
            kdfparams: {
                dklen: 32,
                salt: '4531b3c174cc3ff32a6a7a85d6761b410db674807b2d216d022318ceee50be10',
                n: 262144,
                r: 8,
                p: 1
            },
            mac: 'b8b010fff37f9ae5559a352a185e86f9b9c1d7f7a9f1bd4e82a5dd35468fc7f6'
        }
    }
```

**Parameters:**

1. `privateKey` - `String`: The private key to encrypt.`password`&#x20;
2. `String`: The password used for encryption.

**Returns:**

`Object`: The encrypted keystore v3 JSON.

## decrypt   &#x20;

```javascript
meterify.eth.accounts.decrypt(keystoreJsonV3, password);
```

Decrypts a keystore v3 JSON, and creates the account.

**Example:**

```javascript
meterify.eth.accounts.decrypt({
        version: 3,
        id: '04e9bcbb-96fa-497b-94d1-14df4cd20af6',
        address: '2c7536e3605d9c16a7a3d7b1898e529396a65c23',
        crypto: {
            ciphertext: 'a1c25da3ecde4e6a24f3697251dd15d6208520efc84ad97397e906e6df24d251',
            cipherparams: { iv: '2885df2b63f7ef247d753c82fa20038a' },
            cipher: 'aes-128-ctr',
            kdf: 'scrypt',
            kdfparams: {
                dklen: 32,
                salt: '4531b3c174cc3ff32a6a7a85d6761b410db674807b2d216d022318ceee50be10',
                n: 262144,
                r: 8,
                p: 1
            },
            mac: 'b8b010fff37f9ae5559a352a185e86f9b9c1d7f7a9f1bd4e82a5dd35468fc7f6'
        }
    }, 'test!');
    > {
        address: "0x2c7536E3605D9C16a7a3D7b1898e529396a65c23",
        privateKey: "0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318",
        signTransaction: function(tx){...},
        sign: function(data){...},
        encrypt: function(password){...}
    }
```

**Parameters:**

1. `keystoreJsonV3` - `String`: The encrypted keystore v3 JSON.
2. `password` - `String`: The password used for encryption.

**Returns:**

`Object`: The decrypted account.

## wallet   &#x20;

```javascript
meterify.eth.accounts.wallet;
```

Contains an in memory wallet with multiple accounts. These accounts can be used when using [`meterify.eth.sendTransaction()`](/developer-documentation/meterify-api-documentation/meterify.eth#sendtransaction).

**Example:**

```javascript

    meterify.eth.accounts.wallet;
    > Wallet {
        0: {...}, // account by index
        "0xF0109fC8DF283027b6285cc889F5aA624EaC1F55": {...},  // same account by address
        "0xf0109fc8df283027b6285cc889f5aa624eac1f55": {...},  // same account by address lowercase
        1: {...},
        "0xD0122fC8DF283027b6285cc889F5aA624EaC1d23": {...},
        "0xd0122fc8df283027b6285cc889f5aa624eac1d23": {...},

        add: function(){},
        remove: function(){},
        save: function(){},
        load: function(){},
        clear: function(){},

        length: 2,
    }
```

### wallet.create <a href="#wallet-create" id="wallet-create"></a>

```javascript
meterify.eth.accounts.wallet.create(numberOfAccounts [, entropy]);
```

Generates one or more accounts in the wallet. If wallets already exist they will not be overridden.

**Example:**

```javascript

    meterify.eth.accounts.wallet.create(2, '54674321§3456764321§345674321§3453647544±±±§±±±!!!43534534534534');
    > Wallet {
        0: {...},
        "0xF0109fC8DF283027b6285cc889F5aA624EaC1F55": {...},
        "0xf0109fc8df283027b6285cc889f5aa624eac1f55": {...},
        ...
    }
```

**Parameters:**

1. `numberOfAccounts` - `Number`: Number of accounts to create. Leave empty to create an empty wallet.
2. `entropy` - `String`(optional): A string with random characters as additional entropy when generating accounts. If given it should be at least 32 characters.

**Returns:**

`Object`: The wallet object.

### wallet.add <a href="#wallet-add" id="wallet-add"></a>

```javascript
meterify.eth.accounts.wallet.add(account);
```

Adds an account using a private key or account object to the wallet.

**Example:**

```javascript

    meterify.eth.accounts.wallet.add('0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318');
    > {
        index: 0,
        address: '0x2c7536E3605D9C16a7a3D7b1898e529396a65c23',
        privateKey: '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318',
        signTransaction: function(tx){...},
        sign: function(data){...},
        encrypt: function(password){...}
    }

    meterify.eth.accounts.wallet.add({
        privateKey: '0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709',
        address: '0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01'
    });
    > {
        index: 0,
        address: '0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01',
        privateKey: '0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709',
        signTransaction: function(tx){...},
        sign: function(data){...},
        encrypt: function(password){...}
    }
```

**Parameters:**

1. `account` - `String` or `Object`: A private key or account object created with [`meterify.eth.accounts.create()`](/developer-documentation/meterify-api-documentation/meterify.eth.accounts#create).

**Returns:**

`Object`: The added account.

### wallet.remove <a href="#wallet-remove" id="wallet-remove"></a>

```javascript
    meterify.eth.accounts.wallet.remove(account);
```

Removes an account from the wallet.

**Example:**

```javascript

    meterify.eth.accounts.wallet;
    > Wallet {
        0: {...},
        "0xF0109fC8DF283027b6285cc889F5aA624EaC1F55": {...}
        1: {...},
        "0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01": {...}
        ...
    }

    meterify.eth.accounts.wallet.remove('0xF0109fC8DF283027b6285cc889F5aA624EaC1F55');
    > true

    meterify.eth.accounts.wallet.remove(3);
    > false
```

**Parameters:**

1. `account` - `String` or `Number`: The account address, or index in the wallet.

**Returns:**

`Boolean`: `true` if the wallet was removed. `false` if it couldn't be found.

### wallet.clear <a href="#wallet-clear" id="wallet-clear"></a>

```javascript
    meterify.eth.accounts.wallet.clear();
```

Securely empties the wallet and removes all its accounts.

**Example:**

```javascript

    meterify.eth.accounts.wallet.clear();
    > Wallet {
        add: function(){},
        remove: function(){},
        save: function(){},
        load: function(){},
        clear: function(){},

        length: 0
    }
```

**Parameters:**

none

**Returns:**

`Object`: The wallet object.

### wallet.encrypt <a href="#wallet-encrypt" id="wallet-encrypt"></a>

```javascript
    meterify.eth.accounts.wallet.encrypt(password);
```

Encrypts all wallet accounts to an array of encrypted keystore v3 objects.

**Example:**

```javascript

    meterify.eth.accounts.wallet.encrypt('test');
    > [ { version: 3,
        id: 'dcf8ab05-a314-4e37-b972-bf9b86f91372',
        address: '06f702337909c06c82b09b7a22f0a2f0855d1f68',
        crypto:
         { ciphertext: '0de804dc63940820f6b3334e5a4bfc8214e27fb30bb7e9b7b74b25cd7eb5c604',
           cipherparams: [Object],
           cipher: 'aes-128-ctr',
           kdf: 'scrypt',
           kdfparams: [Object],
           mac: 'b2aac1485bd6ee1928665642bf8eae9ddfbc039c3a673658933d320bac6952e3' } },
      { version: 3,
        id: '9e1c7d24-b919-4428-b10e-0f3ef79f7cf0',
        address: 'b5d89661b59a9af0b34f58d19138baa2de48baaf',
        crypto:
         { ciphertext: 'd705ebed2a136d9e4db7e5ae70ed1f69d6a57370d5fbe06281eb07615f404410',
           cipherparams: [Object],
           cipher: 'aes-128-ctr',
           kdf: 'scrypt',
           kdfparams: [Object],
           mac: 'af9eca5eb01b0f70e909f824f0e7cdb90c350a802f04a9f6afe056602b92272b' } }
    ]
```

**Parameters:**

1. `password` - `String`: The password which will be used for encryption.

**Returns:**

`Array`: The encrypted keystore v3.

### wallet.decrypt <a href="#wallet-decrypt" id="wallet-decrypt"></a>

```javascript
    meterify.eth.accounts.wallet.decrypt(keystoreArray, password);
```

Decrypts keystore v3 objects.

**Example:**

```javascript

    meterify.eth.accounts.wallet.decrypt([
      { version: 3,
      id: '83191a81-aaca-451f-b63d-0c5f3b849289',
      address: '06f702337909c06c82b09b7a22f0a2f0855d1f68',
      crypto:
       { ciphertext: '7d34deae112841fba86e3e6cf08f5398dda323a8e4d29332621534e2c4069e8d',
         cipherparams: { iv: '497f4d26997a84d570778eae874b2333' },
         cipher: 'aes-128-ctr',
         kdf: 'scrypt',
         kdfparams:
          { dklen: 32,
            salt: '208dd732a27aa4803bb760228dff18515d5313fd085bbce60594a3919ae2d88d',
            n: 262144,
            r: 8,
            p: 1 },
         mac: '0062a853de302513c57bfe3108ab493733034bf3cb313326f42cf26ea2619cf9' } },
       { version: 3,
      id: '7d6b91fa-3611-407b-b16b-396efb28f97e',
      address: 'b5d89661b59a9af0b34f58d19138baa2de48baaf',
      crypto:
       { ciphertext: 'cb9712d1982ff89f571fa5dbef447f14b7e5f142232bd2a913aac833730eeb43',
         cipherparams: { iv: '8cccb91cb84e435437f7282ec2ffd2db' },
         cipher: 'aes-128-ctr',
         kdf: 'scrypt',
         kdfparams:
          { dklen: 32,
            salt: '08ba6736363c5586434cd5b895e6fe41ea7db4785bd9b901dedce77a1514e8b8',
            n: 262144,
            r: 8,
            p: 1 },
         mac: 'd2eb068b37e2df55f56fa97a2bf4f55e072bef0dd703bfd917717d9dc54510f0' } }
    ], 'test');
    > Wallet {
        0: {...},
        1: {...},
        "0xF0109fC8DF283027b6285cc889F5aA624EaC1F55": {...},
        "0xD0122fC8DF283027b6285cc889F5aA624EaC1d23": {...}
        ...
    }
```

**Parameters:**

1. `keystoreArray` - `Array`: The encrypted keystore v3 objects to decrypt.
2. `password` - `String`: The password which will be used for encryption.

**Returns:**

`Object`: The wallet object.

### wallet.save <a href="#wallet-save" id="wallet-save"></a>

```javascript
    meterify.eth.accounts.wallet.save(password [, keyName]);
```

Stores the wallet encrypted and as string in local storage.

**Example:**

```javascript

    meterify.eth.accounts.wallet.save('test#!$');
    > true
```

Note: Browser only.

**Parameters:**

1. `password` - `String`: The password to encrypt the wallet.
2. `keyName` - `String`: (optional) The key used for the local storage position, defaults to `"web3js_wallet"`.

**Returns:**

`Boolean`

### wallet.load <a href="#wallet-load" id="wallet-load"></a>

```javascript
meterify.eth.accounts.wallet.load(password [, keyName]);
```

Loads a wallet from local storage and decrypts it.

**Example:**

```javascript

    meterify.eth.accounts.wallet.load('test#!$', 'myWalletKey');
    > Wallet {
        0: {...},
        1: {...},
        "0xF0109fC8DF283027b6285cc889F5aA624EaC1F55": {...},
        "0xD0122fC8DF283027b6285cc889F5aA624EaC1d23": {...}
        ...
    }
```

Note: Browser only.

**Parameters:**

1. `password` - `String`: The password to decrypt the wallet.
2. `keyName` - `String`: (optional) The key used for the local storage position, defaults to `"web3js_wallet"`.

**Returns:**

`Object`: The wallet object.


# meterify.utils

This package provides utility functions for dapps and other packages.

## randomHex

```javascript
    meterify.utils.randomHex(size)
```

The [randomHex](https://github.com/frozeman/randomHex) library to generate cryptographically strong pseudo-random HEX strings from a given byte size.

**Example:**

```javascript

    meterify.utils.randomHex(32)
    > "0xa5b9d60f32436310afebcfda832817a68921beb782fabf7915cc0460b443116a"

    meterify.utils.randomHex(4)
    > "0x6892ffc6"

    meterify.utils.randomHex(2)
    > "0x99d6"

    meterify.utils.randomHex(1)
    > "0x9a"

    meterify.utils.randomHex(0)
    > "0x"
```

**Parameters:**

1. `size` - `Number`: The byte size for the HEX string, e.g. `32` will result in a 32 bytes HEX string with 64 characters preficed with "0x".

**Returns:**

`String`: The generated random HEX string.

## BN   &#x20;

```
meterify.utils.BN(mixed)
```

The [BN.js](https://github.com/indutny/bn.js/) library for calculating with big numbers in JavaScript. See the [BN.js documentation](https://github.com/indutny/bn.js/) for details.

**Example:**

```javascript

    const BN = meterify.utils.BN;

    new BN(1234).toString();
    > "1234"

    new BN('1234').add(new BN('1')).toString();
    > "1235"

    new BN('0xea').toString();
    > "234"
```

Note: For safe conversion of many types, including [BigNumber.js](http://mikemcl.github.io/bignumber.js/), use [`utils.toBN`](/developer-documentation/meterify-api-documentation/meterify.utils#tobn).

**Parameters:**

1. `value` - `String|Number`: A number, number string or HEX string to convert to a BN object.

**Returns:**

`Object`: The [`BN.js`](https://github.com/indutny/bn.js/)\_ instance.

## isBN

```javascript

    meterify.utils.isBN(bn)
```

Checks if a given value is a [`BN.js`](https://github.com/indutny/bn.js/) instance.

**Example:**

```javascript

    const number = new BN(10);

    meterify.utils.isBN(number);
    > true
```

**Parameters:**

1. `bn` - `Object`: An [`BN.js`](https://github.com/indutny/bn.js/) instance.

**Returns:**

`Boolean`

## isBigNumber

```javascript
    meterify.utils.isBigNumber(bignumber)
```

Checks if a given value is a [BigNumber.js](http://mikemcl.github.io/bignumber.js/) instance.

**Example:**

```javascript

    const number = new BigNumber(10);

    meterify.utils.isBigNumber(number);
    > true
```

**Parameters:**

1. `BigNumber` - `Object`: A [BigNumber.js](http://mikemcl.github.io/bignumber.js/) instance.

**Returns:**

`Boolean`

## keccak256

```javascript

    meterify.utils.keccak256(string)
    meterify.utils.sha3(string) // ALIAS
```

Will calculate the keccak256 of the input.

**Example:**

```javascript

    meterify.utils.keccak256('234'); // taken as string
    > "0xc1912fee45d61c87cc5ea59dae311904cd86b84fee17cc96966216f811ce6a79"

    meterify.utils.keccak256(new BN('234'));
    > "0xbc36789e7a1e281436464229828f817d6612f7b477d66591ff96a9e064bcc98a"

    meterify.utils.keccak256(234);
    > null // can't calculate the hash of a number

    meterify.utils.keccak256(0xea); // same as above, just the HEX representation of the number
    > null

    meterify.utils.keccak256('0xea'); // will be converted to a byte array first, and then hashed
    > "0x2f20677459120677484f7104c76deb6846a2c071f9b3152c103bb12cd54d1a4a"
```

Note: To mimic the keccak256 behavior of Solidity, use [soliditySha3](/developer-documentation/meterify-api-documentation/meterify.utils#soliditysha3).

**Parameters:**

1. `string` - `String`: A string to hash.

**Returns:**

`String`: the result hash.

## soliditySha3   &#x20;

```javascript
meterify.utils.soliditySha3(param1 [, param2, ...])
```

Will calculate the sha3 of given input parameters in the same way solidity would. This means arguments will be ABI converted and tightly packed before being hashed.

**Example:**

```javascript
meterify.utils.soliditySha3('234564535', '0xfff23243', true, -10);
    // auto detects:        uint256,      bytes,     bool,   int256
    > "0x3e27a893dc40ef8a7f0841d96639de2f58a132be5ae466d40087a2cfa83b7179"

    meterify.utils.soliditySha3('Hello!%'); // auto detects: string
    > "0x661136a4267dba9ccdf6bfddb7c00e714de936674c4bdb065a531cf1cb15c7fc"

    meterify.utils.soliditySha3('234'); // auto detects: uint256
    > "0x61c831beab28d67d1bb40b5ae1a11e2757fa842f031a2d0bc94a7867bc5d26c2"

    meterify.utils.soliditySha3(0xea); // same as above
    > "0x61c831beab28d67d1bb40b5ae1a11e2757fa842f031a2d0bc94a7867bc5d26c2"

    meterify.utils.soliditySha3(new BN('234')); // same as above
    > "0x61c831beab28d67d1bb40b5ae1a11e2757fa842f031a2d0bc94a7867bc5d26c2"

    meterify.utils.soliditySha3({type: 'uint256', value: '234'})); // same as above
    > "0x61c831beab28d67d1bb40b5ae1a11e2757fa842f031a2d0bc94a7867bc5d26c2"

    meterify.utils.soliditySha3({t: 'uint', v: new BN('234')})); // same as above
    > "0x61c831beab28d67d1bb40b5ae1a11e2757fa842f031a2d0bc94a7867bc5d26c2"

    meterify.utils.soliditySha3('0x407D73d8a49eeb85D32Cf465507dd71d507100c1');
    > "0x4e8ebbefa452077428f93c9520d3edd60594ff452a29ac7d2ccc11d47f3ab95b"

    meterify.utils.soliditySha3({t: 'bytes', v: '0x407D73d8a49eeb85D32Cf465507dd71d507100c1'});
    > "0x4e8ebbefa452077428f93c9520d3edd60594ff452a29ac7d2ccc11d47f3ab95b" // same result as above

    meterify.utils.soliditySha3({t: 'address', v: '0x407D73d8a49eeb85D32Cf465507dd71d507100c1'});
    > "0x4e8ebbefa452077428f93c9520d3edd60594ff452a29ac7d2ccc11d47f3ab95b" // same as above, but will do a checksum check, if its multi case

    meterify.utils.soliditySha3({t: 'bytes32', v: '0x407D73d8a49eeb85D32Cf465507dd71d507100c1'});
    > "0x3c69a194aaf415ba5d6afca734660d0a3d45acdc05d54cd1ca89a8988e7625b4" // different result as above

    meterify.utils.soliditySha3({t: 'string', v: 'Hello!%'}, {t: 'int8', v:-23}, {t: 'address', v: '0x85F43D8a49eeB85d32Cf465507DD71d507100C1d'});
    > "0xa13b31627c1ed7aaded5aecec71baf02fe123797fffd45e662eac8e06fbe4955"
```

**Parameters:**

1. `paramX` - `Mixed`: Any type, or an object with `{type: 'uint', value: '123456'}` or `{t: 'bytes', v: '0xfff456'}`. Basic types are autodetected as follows:
   1. `String` non numerical UTF-8 string is interpreted as `string`.
   2. `String|Number|BN|HEX` positive number is interpreted as `uint256`.
   3. `String|Number|BN` negative number is interpreted as `int256`.&#x20;
   4. `Boolean` as `bool`.&#x20;
   5. `String` HEX string with leading `0x` is interpreted as `bytes`.&#x20;
   6. `HEX` HEX number representation is interpreted as `uint256`.

**Returns:**

`String`: the result hash.

## isHex   &#x20;

```javascript
meterify.utils.isHex(hex)
```

Checks if a given string is a HEX string.

**Example:**

```javascript
    meterify.utils.isHex('0xc1912');
    > true

    meterify.utils.isHex(0xc1912);
    > true

    meterify.utils.isHex('c1912');
    > true

    meterify.utils.isHex(345);
    > true // this is tricky, as 345 can be a a HEX representation or a number, be careful when not having a 0x in front!

    meterify.utils.isHex('0xZ1912');
    > false

    meterify.utils.isHex('Hello');
    > false
```

**Parameters:**

1. `hex` - `String|HEX`: The given HEX string.

**Returns:**

`Boolean`

## isHexStrict   &#x20;

```javascript
meterify.utils.isHexStrict(hex)
```

Checks if a given string is a HEX string. Difference to `meterify.utils.isHex()` is that it expects HEX to be prefixed with `0x`.

**Example:**

```javascript
    meterify.utils.isHexStrict('0xc1912');
    > true

    meterify.utils.isHexStrict(0xc1912);
    > false

    meterify.utils.isHexStrict('c1912');
    > false

    meterify.utils.isHexStrict(345);
    > false // this is tricky, as 345 can be a a HEX representation or a number, be careful when not having a 0x in front!

    meterify.utils.isHexStrict('0xZ1912');
    > false

    meterify.utils.isHex('Hello');
    > false
```

**Parameters:**

1. `hex` - `String|HEX`: The given HEX string.

**Returns:**

`Boolean`

## isAddress   &#x20;

```javascript
meterify.utils.isAddress(address,  [, chainId])
```

Checks if a given string is a valid Meter address. It will also check the checksum, if the address has upper and lowercase letters.

**Example:**

```javascript
    meterify.utils.isAddress('0xc1912fee45d61c87cc5ea59dae31190fffff232d');
    > true

    meterify.utils.isAddress('c1912fee45d61c87cc5ea59dae31190fffff232d');
    > true

    meterify.utils.isAddress('0XC1912FEE45D61C87CC5EA59DAE31190FFFFF232D');
    > true // as all is uppercase, no checksum will be checked

    meterify.utils.isAddress('0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d');
    > true

    meterify.utils.isAddress('0xC1912fEE45d61C87Cc5EA59DaE31190FFFFf232d');
    > false // wrong checksum

    meterify.utils.isAddress('0x5aaEB6053f3e94c9b9a09f33669435E7ef1bEAeD', 30);
    > true
```

**Parameters:**

1. `address` - `String`: An address string.
2. `chainId` - `number` (optional): Chain id where checksummed address should be valid, defaults to `null`. [RSKIP-60](https://github.com/rsksmart/RSKIPs/blob/master/IPs/RSKIP60.md) for details.

**Returns:**

`Boolean`

## toChecksumAddress

```javascript
    meterify.utils.toChecksumAddress(address[, chainId])
```

Will convert an upper or lowercase Meter address to a checksum address.

**Example:**

```javascript

    meterify.utils.toChecksumAddress('0xc1912fee45d61c87cc5ea59dae31190fffff232d');
    > "0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d"

    meterify.utils.toChecksumAddress('0XC1912FEE45D61C87CC5EA59DAE31190FFFFF232D');
    > "0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d" // same as above

    meterify.utils.toChecksumAddress('0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed', 30);
    > "0x5aaEB6053f3e94c9b9a09f33669435E7ef1bEAeD"
```

**Parameters:**

1. `address` - `String`: An address string.
2. `chainId` - `number` (optional): Chain id where checksummed address should be valid, defaults to `null`. [RSKIP-60](https://github.com/rsksmart/RSKIPs/blob/master/IPs/RSKIP60.md) for details.

**Returns:**

`String`: The checksum address.

## stripHexPrefix

```javascript
     meterify.utils.stripHexPrefix(address)
```

Removes the prefix `0x` from a given hex if it exists.

**Example:**

```javascript
      meterify.utils.stripHexPrefix('0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d');
     > "c1912fEE45d61C87Cc5EA59DaE31190FFFFf232d"
```

**Parameters:**

1. `hex` - `String`: Hex

**Returns:**

`String`: Hex without prefix.

## checkAddressChecksum

```javascript

    meterify.utils.checkAddressChecksum(address [, chainId])
```

Checks the checksum of a given address. Will also return false on non-checksum addresses.

**Example:**

```javascript

    meterify.utils.checkAddressChecksum('0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d');
    > true

    meterify.utils.checkAddressChecksum('0x5aAeb6053F3e94c9b9A09F33669435E7EF1BEaEd', 31);
    > true
```

**Parameters:**

1. `address` - `String`: An address string.
2. `chainId` - `number` (optional): Chain id where checksummed address should be valid, defaults to `null`. [RSKIP-60](https://github.com/rsksmart/RSKIPs/blob/master/IPs/RSKIP60.md) for details.

**Returns:**

`Boolean`: `true` when the checksum of the address is valid, `false` if its not a checksum address, or the checksum is invalid.

## toHex

```javascript

    meterify.utils.toHex(mixed)
```

Will auto convert any given value to HEX. Number strings will interpreted as numbers. Text strings will be interpreted as UTF-8 strings.

**Example:**

```javascript

    meterify.utils.toHex('234');
    > "0xea"

    meterify.utils.toHex(234);
    > "0xea"

    meterify.utils.toHex(new BN('234'));
    > "0xea"

    meterify.utils.toHex(new BigNumber('234'));
    > "0xea"

    meterify.utils.toHex('I have 100€');
    > "0x49206861766520313030e282ac"
```

**Parameters:**

1. `value` - `String|Number|BN|BigNumber`: The input to convert to HEX.

**Returns:**

`String`: The resulting HEX string.

## toBN   &#x20;

```
meterify.utils.toBN(number)
```

Will safely convert any given value (including [BigNumber.js](http://mikemcl.github.io/bignumber.js/) instances) into a [BN.js](https://github.com/indutny/bn.js/) instance, for handling big numbers in JavaScript.

**Example:**

```javascript

    meterify.utils.toBN(1234).toString();
    > "1234"

    meterify.utils.toBN('1234').add(meterify.utils.toBN('1')).toString();
    > "1235"

    meterify.utils.toBN('0xea').toString();
    > "234"
```

Note: For just the [BN.js](https://github.com/indutny/bn.js/) class use [utils.BN](https://docs.meter.io/meterify.utils.html#utils-bn).

**Parameters:**

1. `number` - `String|Number|HEX`: Number to convert to a big number.

**Returns:**

`Object`: The [BN.js](https://github.com/indutny/bn.js/) instance.

## hexToNumberString

```javascript
    meterify.utils.hexToNumberString(hex)
```

Returns the number representation of a given HEX value as a string.

**Example:**

```javascript
    meterify.utils.hexToNumberString('0xea');
    > "234"
```

**Parameters:**

1. `hexString` - `String|HEX`: A string to hash.

**Returns:**

`String`: The number as a string.

## hexToNumber

```javascript

    meterify.utils.hexToNumber(hex)
    meterify.utils.toDecimal(hex) // ALIAS, deprecated
```

Returns the number representation of a given HEX value.

**Example:**

```javascript

    meterify.utils.hexToNumber('0xea');
    > 234
```

Note: This is not useful for big numbers, use [utils.toBN](/developer-documentation/meterify-api-documentation/meterify.utils#tobn) instead.

**Parameters:**

1. `hexString` - `String|HEX`: A string to hash.

**Returns:**

`Number`

## numberToHex

```javascript

    meterify.utils.numberToHex(number)
    meterify.utils.fromDecimal(number) // ALIAS, deprecated
```

Returns the HEX representation of a given number value.

**Example:**

```javascript

    meterify.utils.numberToHex('234');
    > '0xea'
```

**Parameters:**

1. `number` - `String|Number|BN|BigNumber`: A number as string or number.

**Returns:**

`String`: The HEX value of the given number.

## hexToUtf8

```javascript

    meterify.utils.hexToUtf8(hex)
    meterify.utils.hexToString(hex) // ALIAS
    meterify.utils.toUtf8(hex) // ALIAS, deprecated
```

Returns the UTF-8 string representation of a given HEX value.

**Example:**

```javascript

    meterify.utils.hexToUtf8('0x49206861766520313030e282ac');
    > "I have 100€"
```

**Parameters:**

1. `hex` - `String`: A HEX string to convert to a UTF-8 string.

**Returns:**

`String`: The UTF-8 string.

## hexToAscii

```javascript

    meterify.utils.hexToAscii(hex)
    meterify.utils.toAscii(hex) // ALIAS, deprecated
```

Returns the ASCII string representation of a given HEX value.

**Example:**

```javascript

    meterify.utils.hexToAscii('0x4920686176652031303021');
    > "I have 100!"
```

**Parameters:**

1. `hex` - `String`: A HEX string to convert to a ASCII string.

**Returns:**

`String`: The ASCII string.

## utf8ToHex   &#x20;

```javascript
    meterify.utils.utf8ToHex(string)
    meterify.utils.stringToHex(string) // ALIAS
    meterify.utils.fromUtf8(string) // ALIAS, deprecated
```

Returns the HEX representation of a given UTF-8 string.

**Example:**

```javascript
    meterify.utils.utf8ToHex('I have 100€');
    > "0x49206861766520313030e282ac"
```

**Parameters:**

1. `string` - `String`: A UTF-8 string to convert to a HEX string.

**Returns:**

`String`: The HEX string.

## asciiToHex  &#x20;

```javascript
    meterify.utils.asciiToHex(string)
    meterify.utils.fromAscii(string) // ALIAS, deprecated
```

Returns the HEX representation of a given ASCII string. If you would like to transform an ASCII string into a valid `bytes4`, `bytes8` etc. value then please pass the correct length as the second parameter.

**Example:**

```javascript
    meterify.utils.asciiToHex('I have 100!');
    > "0x4920686176652031303021000000000000000000000000000000000000000000"

    // transforming to a bytes4 value:
    meterify.utils.asciiToHex('yes', 4);

    // transforming to a bytes8 value:
    meterify.utils.asciiToHex('yes', 8);

    //etc.
```

**Parameters:**

1. `string` - `String`: A ASCII string to convert to a HEX string.
2. `length` - `Number`: The length of the returned hex string. The default size is `32` e.g.: `bytes32`.

**Returns:**

`String`: The HEX string.

## hexToBytes   &#x20;

```javascript
meterify.utils.hexToBytes(hex)
```

Returns a byte array from the given HEX string.

**Example:**

```javascript
    meterify.utils.hexToBytes('0x000000ea');
    > [ 0, 0, 0, 234 ]

    meterify.utils.hexToBytes(0x000000ea);
    > [ 234 ]
```

**Parameters:**

`hex` - `String|HEX`: A HEX to convert.

**Returns:**

`Array`: The byte array.

## bytesToHex

```javascript
meterify.utils.bytesToHex(byteArray)
```

Returns a HEX string from a byte array.

**Example:**

```javascript
    meterify.utils.bytesToHex([ 72, 101, 108, 108, 111, 33, 36 ]);
    > "0x48656c6c6f2125"
```

**Parameters:**

`byteArray` - `Array`: A byte array to convert.

**Returns:**

`String`: The HEX string.

## toWei   &#x20;

```javascript
meterify.utils.toWei(number [, unit])
```

Converts a Meter value into `wei`.

**Example:**

```javascript
    meterify.utils.toWei('1', 'ether');
    > "1000000000000000000"

    meterify.utils.toWei('1', 'finney');
    > "1000000000000000"

    meterify.utils.toWei('1', 'szabo');
    > "1000000000000"

    meterify.utils.toWei('1', 'shannon');
    > "1000000000"
```

Note: `wei` are the smallest conversion unit, and you should always make calculations in `wei` and convert only for display reasons.

**Parameters:**

1. `number` - `String|BN`: The value.
2. `unit` - `String` (optional, defaults to `"ether"`): The ether to convert from. Possible units are:
   1. `noether`: '0'
   2. `wei`: '1'
   3. `kwei`: '1000'
   4. `Kwei`: '1000'
   5. `babbage`: '1000'
   6. `femtoether`: '1000'
   7. `mwei`: '1000000'
   8. `Mwei`: '1000000'
   9. `lovelace`: '1000000'
   10. `picoether`: '1000000'
   11. `gwei`: '1000000000'
   12. `Gwei`: '1000000000'
   13. `shannon`: '1000000000'
   14. `nanoether`: '1000000000'
   15. `nano`: '1000000000'
   16. `szabo`: '1000000000000'
   17. `microether`: '1000000000000'
   18. `micro`: '1000000000000'
   19. `finney`: '1000000000000000'
   20. `milliether`: '1000000000000000'
   21. `milli`: '1000000000000000'
   22. `ether`: '1000000000000000000'
   23. `kether`: '1000000000000000000000'
   24. `grand`: '1000000000000000000000'
   25. `mether`: '1000000000000000000000000'
   26. `gether`: '1000000000000000000000000000'
   27. `tether`: '1000000000000000000000000000000'

**Returns:**

`String|BN`: If a string is given it returns a number string, otherwise a [BN.js](https://github.com/indutny/bn.js/) instance.

## fromWei

```javascript
    meterify.utils.fromWei(number [, unit])
```

Converts any `wei` value into another value.

**Example:**

```javascript

    meterify.utils.fromWei('1', 'ether');
    > "0.000000000000000001"

    meterify.utils.fromWei('1', 'finney');
    > "0.000000000000001"

    meterify.utils.fromWei('1', 'szabo');
    > "0.000000000001"

    meterify.utils.fromWei('1', 'shannon');
    > "0.000000001"
```

Note: `wei` are the smallest conversion unit, and you should always make calculations in wei and convert only for display reasons.

**Parameters:**

1. `number` - `String|BN`: The value in wei.
2. `unit` - `String` (optional, defaults to `"ether"`): The ether to convert to. Possible units are:
   * `noether`: '0'
   * `wei`: '1'
   * `kwei`: '1000'
   * `Kwei`: '1000'
   * `babbage`: '1000'
   * `femtoether`: '1000'
   * `mwei`: '1000000'
   * `Mwei`: '1000000'
   * `lovelace`: '1000000'
   * `picoether`: '1000000'
   * `gwei`: '1000000000'
   * `Gwei`: '1000000000'
   * `shannon`: '1000000000'
   * `nanoether`: '1000000000'
   * `nano`: '1000000000'
   * `szabo`: '1000000000000'
   * `microether`: '1000000000000'
   * `micro`: '1000000000000'
   * `finney`: '1000000000000000'
   * `milliether`: '1000000000000000'
   * `milli`: '1000000000000000'
   * `ether`: '1000000000000000000'
   * `kether`: '1000000000000000000000'
   * `grand`: '1000000000000000000000'
   * `mether`: '1000000000000000000000000'
   * `gether`: '1000000000000000000000000000'
   * `tether`: '1000000000000000000000000000000'

**Returns:**

`String`: It always returns a string number.

## unitMap

```javascript

    meterify.utils.unitMap
```

Shows all possible values and their amount in `wei`.

**Example:**

```javascript

    meterify.utils.unitMap
    > {
        noether: '0',
        wei:        '1',
        kwei:       '1000',
        Kwei:       '1000',
        babbage:    '1000',
        femtoether: '1000',
        mwei:       '1000000',
        Mwei:       '1000000',
        lovelace:   '1000000',
        picoether:  '1000000',
        gwei:       '1000000000',
        Gwei:       '1000000000',
        shannon:    '1000000000',
        nanoether:  '1000000000',
        nano:       '1000000000',
        szabo:      '1000000000000',
        microether: '1000000000000',
        micro:      '1000000000000',
        finney:     '1000000000000000',
        milliether: '1000000000000000',
        milli:      '1000000000000000',
        ether:      '1000000000000000000',
        kether:     '1000000000000000000000',
        grand:      '1000000000000000000000',
        mether:     '1000000000000000000000000',
        gether:     '1000000000000000000000000000',
        tether:     '1000000000000000000000000000000'
    }
```

**Return value:**

* `Object` with the following properties:
  * `noether`: '0'
  * `wei`: '1'
  * `kwei`: '1000'
  * `Kwei`: '1000'
  * `babbage`: '1000'
  * `femtoether`: '1000'
  * `mwei`: '1000000'
  * `Mwei`: '1000000'
  * `lovelace`: '1000000'
  * `picoether`: '1000000'
  * `gwei`: '1000000000'
  * `Gwei`: '1000000000'
  * `shannon`: '1000000000'
  * `nanoether`: '1000000000'
  * `nano`: '1000000000'
  * `szabo`: '1000000000000'
  * `microether`: '1000000000000'
  * `micro`: '1000000000000'
  * `finney`: '1000000000000000'
  * `milliether`: '1000000000000000'
  * `milli`: '1000000000000000'
  * `ether`: '1000000000000000000'
  * `kether`: '1000000000000000000000'
  * `grand`: '1000000000000000000000'
  * `mether`: '1000000000000000000000000'
  * `gether`: '1000000000000000000000000000'
  * `tether`: '1000000000000000000000000000000'

## padLeft

```javascript

    meterify.utils.padLeft(string, characterAmount [, sign])
    meterify.utils.leftPad(string, characterAmount [, sign]) // ALIAS
```

Adds a padding on the left of a string. Useful for adding paddings to HEX strings.

**Example:**

```javascript

    meterify.utils.padLeft('0x3456ff', 20);
    > "0x000000000000003456ff"

    meterify.utils.padLeft(0x3456ff, 20);
    > "0x000000000000003456ff"

    meterify.utils.padLeft('Hello', 20, 'x');
    > "xxxxxxxxxxxxxxxHello"
```

**Parameters:**

1. `string` - `String`: The string to add padding on the left.
2. `characterAmount` - `Number`: The number of characters the total string should have.
3. `sign` - `String` (optional): The character sign to use, defaults to `"0"`.

**Returns:**

`String`: The padded string.

## padRight

```javascript

    meterify.utils.padRight(string, characterAmount [, sign])
    meterify.utils.rightPad(string, characterAmount [, sign]) // ALIAS
```

Adds a padding on the right of a string, Useful for adding paddings to HEX strings.

**Example:**

```javascript

    meterify.utils.padRight('0x3456ff', 20);
    > "0x3456ff00000000000000"

    meterify.utils.padRight(0x3456ff, 20);
    > "0x3456ff00000000000000"

    meterify.utils.padRight('Hello', 20, 'x');
    > "Helloxxxxxxxxxxxxxxx"
```

**Parameters:**

1. `string` - `String`: The string to add padding on the right.
2. `characterAmount` - `Number`: The number of characters the total string should have.
3. `sign` - `String` (optional): The character sign to use, defaults to `"0"`.

**Returns:**

`String`: The padded string.

## toTwosComplement

```javascript

    meterify.utils.toTwosComplement(number)
```

Converts a negative number into a two's complement.

**Example:**

```javascript

    meterify.utils.toTwosComplement('-1');
    > "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"

    meterify.utils.toTwosComplement(-1);
    > "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"

    meterify.utils.toTwosComplement('0x1');
    > "0x0000000000000000000000000000000000000000000000000000000000000001"

    meterify.utils.toTwosComplement(-15);
    > "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1"

    meterify.utils.toTwosComplement('-0x1');
    > "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
```

**Parameters:**

1. `number` - `Number|String|BigNumber`: The number to convert.

**Returns:**

`String`: The converted hex string.

## getSignatureParameters

```javascript

    meterify.utils.getSignatureParameters(string)
```

Gets the r, s and v values of an ECDSA signature

**Example**

```javascript

    meterify.utils.getSignatureParameters('0x5763ab346198e3e6cc4d53996ccdeca0c941cb6cb70d671d97711c421d3bf7922c77ef244ad40e5262d1721bf9638fb06bab8ed3c43bfaa80d6da0be9bbd33dc1b');
    > "{ r: '0x5763ab346198e3e6cc4d53996ccdeca0c941cb6cb70d671d97711c421d3bf792', s: '0x2c77ef244ad40e5262d1721bf9638fb06bab8ed3c43bfaa80d6da0be9bbd33dc', v: 27 }"
```

**Parameters:**

1. `string` - `String`: An ECDSA signature.

**Returns:**

`Object`: Object containing r,s,v values.


# meterify.module.options

A module provides several options for configuring the transaction confirmation workflow or for defining default values. This document describes the available option properties on a module.

**Example:**

```javascript
import Web3 from 'web3';

    const meterify = require("meterify").meterify;

    const options = {
        defaultAccount: '0x0',
        defaultBlock: 'latest',
        defaultGas: 1,
        defaultGasPrice: 0,
        transactionBlockTimeout: 50,
        transactionConfirmationBlocks: 24,
        transactionPollingTimeout: 480,
        transactionSigner: new CustomTransactionSigner()
    }

    const web3 = new Web3('https://testnet.meter.io', null, options);

    const meterify = meterify(web3, "https://testnet.meter.io");
```

## defaultBlock <a href="#defaultblock" id="defaultblock"></a>

```javascript
    web3.defaultBlock
    web3.eth.defaultBlock
    web3.shh.defaultBlock
    ...
```

```javascript
    web3.eth.getBalance();
    web3.eth.getCode();
    web3.eth.getTransactionCount();
    web3.eth.getStorageAt();
    web3.eth.call();
    new web3.eth.Contract() -> myContract.methods.myMethod().call();`
```

The default block is used for all methods which have a block parameter. You can override it by passing the block parameter if a block is required.

The `defaultBlock` property can return the following values:

| Value     | Type     | Description                                                |
| --------- | -------- | ---------------------------------------------------------- |
| a number  | `Number` | A block number                                             |
| `genesis` | `String` | The genesis block                                          |
| `latest`  | `String` | The latest block (current head of the blockchain)          |
| `pending` | `String` | The currently mined block (including pending transactions) |

Default is `latest`

## defaultAccount <a href="#defaultaccount" id="defaultaccount"></a>

```javascript
    web3.defaultAccount
    web3.eth.defaultAccount
    web3.shh.defaultAccount
    ...
```

This default address is used as the default `"from"` property, if no `"from"` property is specified.

**Returns:**

| Type                | Description                                                                                                                |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `String` - 20 Bytes | Any Ethereum address. You need to have the private key for that address in your node or keystore. (Default is `undefined`) |

## defaultGasPrice <a href="#defaultgasprice" id="defaultgasprice"></a>

```javascript
    web3.defaultGasPrice
    web3.eth.defaultGasPrice
    web3.shh.defaultGasPrice
    ...
```

The default gas price which will be used for a request.

**Returns:**

| Type                 | Description                                        |
| -------------------- | -------------------------------------------------- |
| `string` or `number` | The current value of the defaultGasPrice property. |

## defaultGas <a href="#defaultgas" id="defaultgas"></a>

```javascript
    web3.defaultGas
    web3.eth.defaultGas
    web3.shh.defaultGas
    ...
```

The default gas which will be used for a request.

**Returns:**

| Type                 | Description                                   |
| -------------------- | --------------------------------------------- |
| `string` or `number` | The current value of the defaultGas property. |

## transactionBlockTimeout <a href="#transactionblocktimeout" id="transactionblocktimeout"></a>

```javascript
    web3.transactionBlockTimeout
    web3.eth.transactionBlockTimeout
    web3.shh.transactionBlockTimeout
    ...
```

The `transactionBlockTimeout` will be used over a socket-based connection. This option does define the amount of new blocks it should wait until the first confirmation happens. This means the PromiEvent rejects with a timeout error when the timeout got exceeded.

**Returns:**

| Type     | Description                                  |
| -------- | -------------------------------------------- |
| `number` | The current value of transactionBlockTimeout |

## transactionConfirmationBlocks <a href="#transactionconfirmationblocks" id="transactionconfirmationblocks"></a>

```javascript
    web3.transactionConfirmationBlocks
    web3.eth.transactionConfirmationBlocks
    web3.shh.transactionConfirmationBlocks
    ...
```

This defines the number of blocks it requires until a transaction will be handled as confirmed.

**Returns:**

| Type     | Description                                        |
| -------- | -------------------------------------------------- |
| `number` | The current value of transactionConfirmationBlocks |

## transactionPollingTimeout <a href="#transactionpollingtimeout" id="transactionpollingtimeout"></a>

```javascript
    web3.transactionPollingTimeout
    web3.eth.transactionPollingTimeout
    web3.shh.transactionPollingTimeout
    ...
```

The `transactionPollingTimeout` will be used over a HTTP connection. This option does define the amount of polls (each second) it should wait until the first confirmation happens.

**Returns:**

| Type     | Description                                    |
| -------- | ---------------------------------------------- |
| `number` | The current value of transactionPollingTimeout |

## transactionSigner <a href="#transactionsigner" id="transactionsigner"></a>

```javascript
    web3.eth.transactionSigner
    ...
```

The `TransactionSigner` property does provide us the possibility to customize the signing process of the `Eth` module and the related sub-modules.

The interface of a `TransactionSigner`:

```javascript

    interface TransactionSigner {
        sign(txObject: Transaction): Promise<SignedTransaction>
    }

    interface SignedTransaction {
        messageHash: string,
        v: string,
        r: string,
        s: string,
        rawTransaction: string
    }
```

**Returns:**

| Type                | Description                                   |
| ------------------- | --------------------------------------------- |
| `TransactionSigner` | A JavaScript class of type TransactionSigner. |

## setProvider <a href="#setprovider" id="setprovider"></a>

```javascript

    web3.setProvider(myProvider)
    web3.eth.setProvider(myProvider)
    web3.shh.setProvider(myProvider)
    ...
```

Will change the provider for its module.

**Example:**

```javascript

    import Web3 from 'web3';

    const web3 = new Web3('http://localhost:8545');

    // or
    const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));

    // change provider
    web3.setProvider('ws://localhost:8546');
    // or
    web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:8546'));

    // Using the IPC provider in node.js
    const net = require('net');
    const web3 = new Web3('/Users/myuser/Library/Ethereum/geth.ipc', net); // mac os path

    // or
    const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Ethereum/geth.ipc', net)); // mac os path
    // on windows the path is: '\\\\.\\pipe\\geth.ipc'
    // on linux the path is: '/users/myuser/.ethereum/geth.ipc'
```

Note: When called on the umbrella package `web3` it will also set the provider for all sub modules `web3.eth`, `web3.shh`, etc.

**Parameters:**

| Type                 | Description                                                                            |
| -------------------- | -------------------------------------------------------------------------------------- |
| `Object` or `String` | `provider`: a valid provider                                                           |
| `Net`                | `net`: (optional) the node.js Net package. This is only required for the IPC provider. |

**Returns:**

`Boolean`

## providers <a href="#providers" id="providers"></a>

```javascript

    Web3.providers
    Eth.providers
    ...
```

**Example:**

```javascript

    const Web3 = require('web3');
    // use the given Provider, e.g in Mist, or instantiate a new websocket provider
    const web3 = new Web3(Web3.givenProvider || 'ws://localhost:8546');
    // or
    const web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider('ws://localhost:8546'));

    // Using the IPC provider in node.js
    const net = require('net');

    const web3 = new Web3('/Users/myuser/Library/Ethereum/geth.ipc', net); // mac os path
    // or
    const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Ethereum/geth.ipc', net)); // mac os path
    // on windows the path is: '\\\\.\\pipe\\geth.ipc'
    // on linux the path is: '/users/myuser/.ethereum/geth.ipc'
```

Contains the current available providers.

`Object` with the following providers:

| Property | Name                | Description                                                                                      |
| -------- | ------------------- | ------------------------------------------------------------------------------------------------ |
| `Object` | `HttpProvider`      | The HTTP provider is **deprecated**, as it will not work for subscriptions.                      |
| `Object` | `WebsocketProvider` | The Websocket provider is the standard for usage in legacy browsers.                             |
| `Object` | `IpcProvider`       | The IPC provider is used node dapps when running a local node. Gives the most secure connection. |

## givenProvider <a href="#givenprovider" id="givenprovider"></a>

```javascript
    Web3.givenProvider
    web3.eth.givenProvider
    web3.shh.givenProvider
    ...
```

**Example:**

```javascript

    web3.setProvider(Web3.givenProvider || 'ws://localhost:8546');
```

When using web3.js in an Ethereum compatible browser, it will set with the current native provider by that browser. Will return the given provider by the (browser) environment, otherwise `null`.

**Returns:**

| Type     | Description                        |
| -------- | ---------------------------------- |
| `Object` | The given provider set or `false`. |

## currentProvider <a href="#currentprovider" id="currentprovider"></a>

```javascript

    web3.currentProvider
    web3.eth.currentProvider
    web3.shh.currentProvider
    ...
```

Will return the current provider.

**Example:**

```javascript

    if (!web3.currentProvider) {
        web3.setProvider('http://localhost:8545');
    }
```

**Returns:**

| Type     | Description               |
| -------- | ------------------------- |
| `Object` | The current provider set. |

## BatchRequest <a href="#batchrequest" id="batchrequest"></a>

```javascript

    new web3.BatchRequest()
    new web3.eth.BatchRequest()
    new web3.shh.BatchRequest()
    ...
```

**Example:**

```javascript

    const contract = new web3.eth.Contract(abi, address);

    const batch = new web3.BatchRequest();
    batch.add(web3.eth.getBalance.request('0x0000000000000000000000000000000000000000', 'latest'));
    batch.add(contract.methods.balance(address).call.request({from: '0x0000000000000000000000000000000000000000'}));
    batch.execute().then(...);
```

Class to create and execute batch requests.

**Parameters:**

none

**Returns:**

| Type     | Description                     |
| -------- | ------------------------------- |
| `Object` | Contains the following methods: |

| Method         | Description                                |
| -------------- | ------------------------------------------ |
| `add(request)` | To add a request object to the batch call. |
| `execute()`    | Will execute the batch request.            |


# Callbacks Promises Events

## PromiEvent

To help web3 integrate into all kind of projects with different standards, we provide multiple ways to act on asynchronous functions.

Most web3.js objects allow a callback as the last parameter, as well as returning promises to chain functions.

Meter as a blockchain has different levels of finality and therefore needs to return multiple "stages" of an action.

To cope with this requirement, we return a "PromiEvent" for functions like [`web3.eth.sendTransaction`](/developer-documentation/meterify-api-documentation/meterify.eth#sendtransaction) or contract methods. These stages are encapsulated into a "PromiEvent", which combines a promise with an event emitter.

The event emitter fires an event for each of the finality stages.

An example of a function that benefits from a PromiEvent is the [`web3.eth.sendTransaction`](/developer-documentation/meterify-api-documentation/meterify.eth#sendtransaction) method:

```

    web3.eth.sendTransaction({from: '0x123...', data: '0x432...'})
    .once('transactionHash', function(hash){ ... })
    .once('receipt', function(receipt){ ... })
    .on('confirmation', function(confNumber, receipt){ ... })
    .on('error', function(error){ ... })
    .then(function(receipt){
        // will be fired once the receipt is mined
    });
```


# json interface

The json interface is a json object describing the Application Binary Interface (ABI) for a smart contract. Using this json interface, web3.js is able to create JavaScript object representing the smart contract and its methods and events using the web3.eth.Contract object.

## Specification

**Functions:**

1. `type`: `"function"`, `"constructor"` (can be omitted, defaulting to `"function"`; `"fallback"` also possible but not relevant in web3.js).
2. `name`: the name of the function (only present for function types).
3. `constant`: `true` if function is specified to not modify the blockchain state.
4. `payable`: `true` if function accepts ether, defaults to `false`
5. `stateMutability`: a string with one of the following values:&#x20;
   1. `pure` (specified to not read blockchain state)
   2. `view` (same as `constant` above)
   3. `nonpayable` and `payable` (same as `payable` above)
6. `inputs`: an array of objects, each of which contains:
   1. `name`: the name of the parameter
   2. `type`: the canonical type of the parameter
7. `outputs`: an array of objects same as `inputs`, can be omitted if no outputs exist.

**Events:**

1. `type`: always `"event"`
2. `name`: the name of the even&#x74;**.**
3. `inputs`: an array of objects, each of which contains:
   1. `name`: the name of the parameter.
   2. `type`: the canonical type of the parameter.
   3. `indexed`: `true` if the field is part of the log's topics, `false` if it one of the log's data segment.
4. `anonymous`: `true` if the event was declared as `anonymous`.

**Example:**

```javascript
contract Test {
        uint a;
        address d = 0x12345678901234567890123456789012;

        function Test(uint testInt)  { a = testInt;}

        event Event(uint indexed b, bytes32 c);

        event Event2(uint indexed b, bytes32 c);

        function foo(uint b, bytes32 c) returns(address) {
            Event(b, c);
            return d;
        }
    }

    // would result in the JSON:
    [{
        "type":"constructor",
        "payable":false,
        "stateMutability":"nonpayable"
        "inputs":[{"name":"testInt","type":"uint256"}],
      },{
        "type":"function",
        "name":"foo",
        "constant":false,
        "payable":false,
        "stateMutability":"nonpayable",
        "inputs":[{"name":"b","type":"uint256"}, {"name":"c","type":"bytes32"}],
        "outputs":[{"name":"","type":"address"}]
      },{
        "type":"event",
        "name":"Event",
        "inputs":[{"indexed":true,"name":"b","type":"uint256"}, {"indexed":false,"name":"c","type":"bytes32"}],
        "anonymous":false
      },{
        "type":"event",
        "name":"Event2",
        "inputs":[{"indexed":true,"name":"b","type":"uint256"},{"indexed":false,"name":"c","type":"bytes32"}],
        "anonymous":false
    }]
```


# Meterify DApp Tutorials

DApps are decentralized applications that utilize blockchains to store a history of operations (e.g. transactions). They can also consist of functional code, called smart contracts, that are published to the blockchain. DApps interfaces can be graphical, console-based, or APIs.

Popular categories for DApps include finance, exchanges, and gambling, but social applications and games also exist.

One of the primary use cases for a DApp is sending cryptocurrency between two accounts. For example, when Alice wishes to send some MTR and MTRG to Bob's account. Application developers can create methods for this on the Meter blockchain using `meterify`, an extended version of `Web3` (AKA the Ethereum JavaScript API library).

The final project files can be found here:

* [index.js](https://github.com/meter-io-docs/meter-io-docs.github.io/blob/master/examples/includes/meter-dapp/index.js)
* [sample\_token.sol](https://github.com/meter-io-docs/meter-io-docs.github.io/blob/master/examples/includes/meter-dapp/sample_token.sol)
* [docker-compose.yml](https://github.com/meter-io-docs/meter-io-docs.github.io/blob/master/examples/includes/meter-dapp/docker-compose.yml)

## Prerequisites

Meterify requires that Node.js version 10.15.1 or above is [installed](https://nodejs.org/en/download/package-manager/), as well as `npm`.

```
$ node --version

v10.16.3

$ npm --version

6.9.0
```

## Example DApp

### Step 1 - Project Setup

Create a directory (e.g. meter-dapp) and initialize a new project using `npm`. Then install the app prerequisites `meterify` and `web3`, plus the JavaScript bindings for the Solidity compiler (`solc`).

```
$ mkdir meter-dapp

$ cd meter-dapp

$ npm init

$ npm install meterify --save

$ npm install web3@1.0.0-beta.37 --save

$ npm install solc@0.4.24 --save
```

### Step 2 - Test the Connection

Create a file called `index.js`, and include the `meterify` and `web3` requirements, then call the file with `node` to test the connection to the testnet.

**index.js:**

```
const mtr = require("meterify").meterify;
const Web3 = require("web3");
const meterify = mtr(new Web3(), "https://testnet.meter.io");
```

```
$ node index.js
```

If the code runs without any errors the connection was successful.

### Step 3 - Creating an Account-Generating Function

```javascript
meterify.eth.accounts.create()
```

The `meterify.eth.accounts` package contains functions for generating accounts and signing transactions and data. Create an object, using Alice's and Bob's names as keys. Perform a loop on the object, calling the `create` function. This will generate new local accounts that contain both a private key and a public key. Add each account to the object as is created.

```javascript
var accounts = createAccounts({"alice":{},"bob":{}});

function createAccounts(accounts){

  for(key in accounts){
    accounts[key] = meterify.eth.accounts.create();
  }

  return accounts;
}
```

### Step 4 - Add Accounts to a Wallet.

```javascript
meterify.eth.accounts.wallet;
```

`meterify.eth.accounts` also contains an in memory wallet to store multiple accounts. Loop through the object returned by the `createAccounts` function, and add Alice's and Bob's accounts to the wallet, using each account's private key.

```javascript
function addAccountsToWallet(accounts){

  for(var key in accounts){
    meterify.eth.accounts.wallet.add(accounts[key].privateKey);
  }

}
```

### Step 5 - Send MTR to an Account

Use the `eth` package's `sendTransaction` method to create a function for sending some MTR and MTRG from Alice to Bob.

Units in `meterify` are Wei, where 1 MTR = 10e18 Wei. Note that the identifier code for MTR is `0000000000`, while MTRG is `0000000001`. `sendTransaction` returns a [`promiEvent`](/developer-documentation/meterify-api-documentation/callbacks-promises-events#promievent) that is considered resolved once the `receipt` becomes available.

```javascript

/* Note: Alice's account should already contain some MTR and MTRG
 * for this example code to work.
 */

sendCrypto(accounts.alice.address, accounts.bob.address, '0000000000', '1000000000000000000');

sendCrypto(accounts.alice.address, accounts.bob.address, '0000000001', '1000000000000000000');

function sendCrypto(fromAddress, toAddress, code, amount){

  meterify.eth.sendTransaction(
    {
      from: fromAddress,
      to: toAddress,
      value: amount,
      data: code
    }
  ).then(
    receipt => {}
  ).then(
    data => {
      console.log("MTR sent: "+JSON.stringify(data));
      next();
    }
  ).catch(function(error){
    console.log("Error: "+error);
  });
}
```

### Step 6 - Run the application.

```
$ node index.js
```

## Load, Deploy, and Test a Smart Contract

The following modifications to the example demonstrate the use of a sample smart contract on the Meter blockchain. Again, follow the steps to add code snippets to the existing `index.js` file.

### Step 1 - Load a Smart Contract.

The file can be found here: [sample\_token.sol](https://github.com/meter-io-docs/meter-io-docs.github.io/blob/master/examples/includes/meter-dapp/sample_token.sol)

```javascript
function loadContract(file){
  console.log("Loading contract: "+file);
  const contractFile = fs.readFileSync(file).toString();
  const solc = require('solc');
  const compiledCode = solc.compile(contractFile);

  var data = {};

  data.token_abiDefinition = JSON.parse(compiledCode.contracts[':SAMPLEToken'].interface)
  let token_byteCode = compiledCode.contracts[':SAMPLEToken'].bytecode
  data.token_byteCode = "0x" + token_byteCode;

  console.log("Contract Loaded.");
  return data;
}
```

### Step 2 - Deploy a Smart Contract

```javascript
function deployContract(data,address){
  console.log("Deploying contract.");

  contractInstance = new meterify.eth.Contract(data.token_abiDefinition)
  contractInstance.options.data = data.token_byteCode
  contractInstance.deploy(
    {
      arguments: [
        address,
        '1000000000',
        'Sample Token',
        '3',
        'STOKEN'
      ]
    }
  ).send(
    {
      from: address,
      gas: 4700000
    }
  ).then(
    (
      newContractInstance
    ) => {
      console.log("Contract deployed.");
      contractInstance.options.address = newContractInstance.options.address;
      registerEvents(contractInstance);
    }
  );
}
```

### Step 3 - Register Contract Events

Additionally, call some example functions within `contractReady` when the contract is ready.

```javascript
function registerEvents(contractInstance){
  contractInstance.events.allEvents(
    {}, (error, result) => {
      if (error) {
          console.log(error)
      } else {
        console.log("Contract Ready.");
          contractReady(result,contractInstance);
      }
  })
}

function contractReady(result,contractInstance){
  transferFrom(contractInstance, accounts.alice.address, accounts.bob.address);
}

```

### Step 4 - Transfer Between Accounts.

```javascript
function transferFrom(contractInstance, fromAddress, toAddress){
  contractInstance.methods._transferFrom(
    fromAddress,
    toAddress,
    '9999'
  ).send(
    {
      from:fromAddress,
      gas: 4700000
    }
  ).then(
    data => {
      console.log(data)}
    ).catch(
      err => {console.log(err)}
  )
}
```

### Step 5 - Get a Balance.

```javascript
function getAccountBalanceOf(contractInstance,address){
  contractInstance.methods.getAccountBalanceOf(
    address
  ).send(
    {
      from: address,
      gas: 4700000
    }).then(
      data => {
        console.log(data)
      }
    ).catch(err => {
      console.log(err)
    }
  )
}
```

### Step 6 - Mint Some Coins.

```javascript
function mintToken(contractInstance,address){
  contractInstance.methods.mintToken(
    address,
    '99999999999999999999999'
  ).send(
    {
      from: address,
      gas: 4700000
    }
  ).then(
    data => {
      console.log(data)
    }
  ).catch(
    err => {
      console.log(err)
    }
  )
}

```

## Using Docker

### Step 1 - Ensure `docker-compose` is Installed.

```
$ sudo curl -L https://github.com/docker/compose/releases/download/1.24.1/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose

$ sudo chmod +x /usr/local/bin/docker-compose

$ docker-compose --version

docker-compose version 1.24.1, build 4667896b
```

### Step 2 - Create `docker-compose.yml`

A copy of this file can be found here: [docker-compose.yml](https://github.com/meter-io-docs/meter-io-docs.github.io/blob/master/examples/includes/meter-dapp/docker-compose.yml)

```
version: '3.5'
services:
  node:
    image: "node:10"
    user: "node"
    working_dir: /home/node/meter-daap
    volumes:
      - ./:/home/node/meter-daap
    command: >
      sh -c "rm -rf node_modules
            npm init -y &&
            npm install meterify --save &&
            rm -rf node_modules/*/.git/
            npm install web3@1.0.0-beta.37 --save &&
            npm install solc@0.4.24 --save &&
            node index.js"
```

### Step 3 - Run `docker-compose`

Initiate the test application with `docker-compose`.

```
$ docker-compose up
```

If there are no errors the connection was successful.

> Stop Docker using `Ctrl+C`.

```
Ctrl+C
```

### Step 4 - Comment out dependency installation.

After the first run in `docker-compose.yml`, stop repeated initialization and dependency installation by commenting out the following lines.

```
version: '3.5'
services:
  node:
    image: "node:10"
    user: "node"
    working_dir: /home/node/meter-daap
    volumes:
      - ./:/home/node/meter-daap
    command: node index.js
#    command: >
#      sh -c "rm -rf node_modules
#            npm init -y &&
#            npm install meterify --save &&
#            rm -rf node_modules/*/.git/
#            npm install web3@1.0.0-beta.37 --save &&
#            npm install solc@0.4.24 --save &&
#            node index.js"
```


# Meterify Code Examples

## Setup Test Environment  <a href="#create-account-example" id="create-account-example"></a>

We already have the example code in Github, which require node.js as the runtime environment.  The following commands setup node.js, install `meterify` package and check out the example code in Github. &#x20;

Please change the end point in `meterifiedWeb3.js` to your own node or the official mainnet/testnet end points, which are:

mainnet: <https://mainnet.meter.io>

Warringstakes tesnet: <http://testnet.meter.io>

```
$ sudo apt install npm
$ npm install meterify
$ git clone https://github.com/meterio/hackathon-demo
```

## Create Account Example <a href="#create-account-example" id="create-account-example"></a>

```
$ node createAccount.js
```

Please be aware the above script creates the private/public key pair on the RPC end point.  You should always run your own local node and connect to the local RPC end point for creating account due to security reasons.

**Source Files**

* [createAccount.js](https://docs.meter.io/examples/includes/create-account/createAccount.js)
* [meterifiedWeb3.js](https://docs.meter.io/examples/includes/create-account/meterifiedWeb3.js)
* [utils.js](https://docs.meter.io/examples/includes/create-account/utils.js)
* [package.json](https://docs.meter.io/examples/includes/create-account/package.json)

## Send Transaction CLI Example <a href="#send-transaction-cli-example" id="send-transaction-cli-example"></a>

> Run

```

$ node createAccount.js

$ node sendTransaction.js

```

**Source Files**

* [createAccount.js](https://docs.meter.io/examples/includes/send-transaction/createAccount.js)
* [sendTransaction.js](https://docs.meter.io/examples/includes/send-transaction/sendTransaction.js)
* [meterifiedWeb3.js](https://docs.meter.io/examples/includes/send-transaction/meterifiedWeb3.js)
* [utils.js](https://docs.meter.io/examples/includes/send-transaction/utils.js)
* [package.json](https://docs.meter.io/examples/includes/send-transaction/package.json)

## Deploy a Contract Example <a href="#deploy-a-contract-example" id="deploy-a-contract-example"></a>

> Run

```

$ node createAccount.js

$ node sendTransaction.js

$ node deployContract.js
```

**Source Files**

* [createAccount.js](https://docs.meter.io/examples/includes/deploy-contract/createAccount.js)
* [sendTransaction.js](https://docs.meter.io/examples/includes/deploy-contract/sendTransaction.js)
* [deployContract.js](https://docs.meter.io/examples/includes/deploy-contract/deployContract.js)
* [sample\_token.sol](https://docs.meter.io/examples/includes/deploy-contract/sample_token.sol)
* [meterifiedWeb3.js](https://docs.meter.io/examples/includes/deploy-contract/meterifiedWeb3.js)
* [utils.js](https://docs.meter.io/examples/includes/deploy-contract/utils.js)
* [package.json](https://docs.meter.io/examples/includes/deploy-contract/package.json)

## Call a Contract CLI Example <a href="#call-a-contract-cli-example" id="call-a-contract-cli-example"></a>

> Run

```
$ node createAccount.js

$ node sendTransaction.js

$ node deployContract.js

$ node callContract.js
```

**Source Files**

* [createAccount.js](https://docs.meter.io/examples/includes/call-contract/createAccount.js)
* [sendTransaction.js](https://docs.meter.io/examples/includes/call-contract/sendTransaction.js)
* [deployContract.js](https://docs.meter.io/examples/includes/call-contract/deployContract.js)
* [callContract.js](https://docs.meter.io/examples/includes/call-contract/callContract.js)
* [sample\_token.sol](https://docs.meter.io/examples/includes/call-contract/sample_token.sol)
* [meterifiedWeb3.js](https://docs.meter.io/examples/includes/call-contract/meterifiedWeb3.js)
* [utils.js](https://docs.meter.io/examples/includes/call-contract/utils.js)
* [package.json](https://docs.meter.io/examples/includes/call-contract/package.json)

## Meterify + Simple React Wallet <a href="#meterify-react" id="meterify-react"></a>

> Install

```
$ git clone https://github.com/meterio/hackathon-demo-react.git

$ cd hackathon-demo-react.git

$ npm install
```

> Run

```
$ npm start
```


# Contributing to Meter and Our Documentation

Meter welcomes contributions from the community. If you wish to contribute to any of our projects, including documentation, feel free to clone the relevant repositories listed below.

Please create a unique branch in your local copy. When you have made your modifications and are finished with your contribution, submit a merge request and one of the Meter team members will review and provide any feedback.

You may also reach out to our team at any time if you have questions, or wish to get advance feedback on work in progress.

## Meter Project Contributions

Meter has a number of projects you can contribute to. They are available here: <https://github.com/meterio>.

Some notable projects include:

* [meterify](https://github.com/meterio/meterify): An extended version of `web3` to interact with Meter's RESTful API.
* [Meter NOMP](https://github.com/meterio/meter-nomp): A cryptocurrency mining pool for Meter, written entirely in Node.js.<br>

## Documentation Contributions

The documentation for Meter is created with [Gitbook](https://gitbook.com).&#x20;

The [Documentation Guidelines](/developer-documentation/contributing-to-meter-and-our-documentation/documentation-guidelines) discusses how to format documentation according to the Meter standard and highlights approaches to writing Meter documentation.


# Documentation Guidelines

Meter maintains a set of standard guidelines for our technical documentation. The objective is to maintain quality and consistency in delivering important and useful information for persons in need of technical guidance. These include, among other things, the style, tone, formatting procedures for the documentation as a whole, and the unique requirements of specific kinds of content.

## Overview

Gitbook can accept many forms of documentation input, including markdown, Word, HTML, and more.&#x20;

Each documentation file resides in the `source` sub-directory, with the format `filename.html.md`.

### File Naming

The naming convention for each of these files should correspond as closely to the title of the document as possible. It should be all lowercase (except in special circumstances), use hyphens for spaces, and include no special other characters. No greater than 24 characters should be used for the filename, not including the `.html.md` file extension and hyphens.

### Navigation and Structure

The file structure should remain as flat as possible, with no more than one sub-directory representing an important high level topic or documentation section. Examples of this include `api`, `tutorials`, and `contributing`. The top level `source` directory, and all sub-directories underneath it, should include an `index.html.md` file that provides a general overview of that section.

### Publishing

It will often be useful for contributors to build the documentation locally, to see if their modifications have no errors, and conform to the standards. This is a relatively straightforward procedure by running the following command:

```
$ bundle exec middleman build --clean
```

Middleman will take the name conforming Markdown files located in the `source` sub-directory, and then generate static documentation in the `build` sub-directory. Those static HTML files can be opened in a browser without any need for a server.

## Use of Markdown

There is nothing specifically unique about Gitbook's use of Markdown, other than to make note about the ordering of code blocks and sections. The [Outline of a Page](/developer-documentation/contributing-to-meter-and-our-documentation/documentation-guidelines#outline-of-a-page) section that follows should contain sufficient examples for how to use Markdown for Meter docs. If additional guidance is required, check out Gitbook's [markdown documentation.](https://docs.gitbook.com/editing-content/markdown)

## Outline of a Page

Every page will include the following:

1. A [meta-data section](https://docs.meter.io/contributing/documentation-guidelines.html#meta-data-section) at the very top of the source document.
2. A [page title](https://docs.meter.io/contributing/documentation-guidelines.html#page-title).
3. A [summary overview](https://docs.meter.io/contributing/documentation-guidelines.html#summary-overview).
4. A [body section](https://docs.meter.io/contributing/documentation-guidelines.html#body-section).
5. [Code blocks and command line examples](https://docs.meter.io/contributing/documentation-guidelines.html#code-and%20command-line) (where relevant)

### Meta-Data Section

The meta-data section includes details such as title, language tabs (e.g. for code samples), links to other documents, and whether to include search on the page or not.&#x20;

This section is written in Yaml as follows:

```
---
title: Name of the document

language_tabs:
  - javascript

toc_footers:
- <a href='./index.html'>Documentation Home</a>
- A Top Level Topic
- <a href='./another-doc.html'>Another Document</a>
- <a href='./yet-another.html'>Yet Another</a>
- <a href='./and-yet-another.html'>And Yet Another</a>
- <hr>
- A Different Top Level Topic
- <a href='./different-top-level-topic/index.html'>Topic Overview</a>
- <a href='./different-top-level-topic/more-on-topic.html'>More on the Topic</a>
- <hr>  
- <a href='https://www.meter.io/external-link/'>An Important External Link</a>
- <a href='https://www.meter.io'>Meter.io</a>

search: true
---
```

#### Title

See [Page Title](/developer-documentation/contributing-to-meter-and-our-documentation/documentation-guidelines#page-title)

#### **Navigation**

While just about any HTML can be used in the `toc_footers` meta data, for Meter this should only ever include relative links, external links, links to anchors within a page, text for section titles, and section dividers (hr tags). The table of contents can be adjusted for each page individually, but should follow some convention.

The navigation should always include all top level topics within the documentation. Therefore, at the very least a link to that topic's main index page should be included within the `toc_footers`. When the current document belongs to a particular topic (e.g. `API Documentation`), the topic is considered to be the active one. That document and all other documents that belong to that topic should also be included in `toc_footers`. Inactive topics might also include noteworthy links, as well as its index page.

```
toc_footers:
- <a href='./index.html'>Documentation Home</a>
- First Topic
- <a href='./first-topic/index.html'>First Topic</a>
- <a href='./first-topic/the-active-document.html'>The Active Document</a>
- <a href='./first-topic/one-same-topic-doc.html'>One Same Topic Doc</a>
- <a href='./first-topic/another-same-topic-doc.html'>Another Same Topic Doc</a>
- <hr>
- Second Topic
- <a href='./second-topic/index.html'>Second Topic</a>
- <a href='./second-topic/a-noteworthy-doc.html'>A Noteworthy Doc</a>
- <hr>  
- Third Topic
- <a href='./third-topic/index.html'>Third Topic</a>
- <a href='./third-topic/a-noteworthy-doc.html'>A Noteworthy Doc</a>
- <hr>
- <a href='https://www.meter.io/external-link/'>An Important External Link</a>
- <a href='https://www.meter.io'>Meter.io</a>
```

#### **Language Tabs**

In general the language tab meta-data must be in one of the languages listed here: <https://github.com/rouge-ruby/rouge/wiki/List-of-supported-languages-and-lexers>.&#x20;

However, depending on the document, for Meter this will generally always be either `javascript` or `bash` (but never both). Most developer documents will use `javascript`, while documents that are primarily concerned with using the command line will use `bash`. This use of a single tab does not affect the use of Markdown code blocks in any way, but makes it easier for the reader to not need to switch back and forth between tabs unnecessarily.

#### **Search**

The search mechanism is limited to only searching within the current, but it is advisable to always set this to true, for convenience.

```
search: true
```

### Page Title

Readers should have a good sense what the document is about in a reasonable amount of words. Make all document titles as intuitive as possible, and avoid making them too long or too short. Less than 30 characters long, and preferably no more than 24, is ideal. One of the purposes for this is that titles that are too long may get cut off in the side navigation.

### Summary Overview

Write a brief intro on the main topic, in two or three sentences. In one paragraph, give the reader a short and direct summary of what to expect in the document. Convince them to continue reading.

### Body Section

The body section of the document will contain all the topic sub-headings. It does not require a title or any summary overview of its own. However, if there are four or more sub-headings a table of contents before any sub-headings may be useful to help navigate the page. Even child topics within sub-headings may be desirable in some situations.

**Example:**

````
* First Sub-Heading
* Second Sub-Heading
* Third Sub-Heading
  * Child Topic One
  * Child Topic Two
  * Child Topic Three
  * Child Topic Four

* Fourth Sub-Heading
Sub-HeadingsSub-headings will represent a logical section that breaks up the document into something more readable and easier to follow. Such as step by step procedures in a how to guide.  A top level sub-heading will depend on its relevant importance to the document topic, and may be further broken down into child sub-heading sections of their own. Use the first sub-heading to provide any additional details that could not fit in the space of the summary section. All additional top level sub-heading sections must be tightly-related to the main topic and arranged in a logical flow.In Markdown, the hierarchy of sub-heading sections will be marked by between two and four hash marks before the title. Again these should be related to their parent heading and arranged logically.Example:## An Important Topic### A Sub-Topic#### A Child of the Sub-TopicThese sections will contain topical textual information (preferably in paragraphs), code blocks, command line examples, tables or media (e.g. images). There is an important order to which these must be arranged within the sub-heading, due to how Slate determines layout. It might be necessary to move text and code blocks around to get things to look correct. Generally something along the lines of the following will be a standard approach:## Sub-Title```javascript    // Some codeThis comment shows up above the example code below.    // some example codeThis will be the first paragraph. It will show up just under the sub-title, and just beside the first code snippet. It should provide a quick summary of what the sub-section is all about.This comment shows up above the bash section below.    // Possibly some return value or console outputAnother paragraph, this time demonstrating the use of a table. This will show up just below the first paragraph. These should go into more detail about the relevant topic.TypeDescriptiontableThis is a table.<a name="code-and command-line"/>### Code Blocks and Command Line ExamplesAll code and command line examples should be as realistic as possible, relate directly to the topic they accompany, and be simple and concise. Avoid over complicating things as much as possible. An exception to this may be when you want to show the summary end product of a series of previous steps and code snippets that the reader has already gone through._Incorrect_:~~~markdown# Step 1: Include Dependencies```jsconst mtr = require("meterify").meterify;const Web3 = require("web3");const meterify = meterify(new Web3(), "http://test.meter.io:8669");/* * The code below has nothing to do with the immediate topic. * Either change the text to include it in the same step, * or omit the snippet, and include it in the next step. */var accounts = {  "alice":web3.eth.accounts.create(),  "bob":web3.eth.accounts.create()};The application will require the metrify and web3 libraries. Include them as dependencies at the beginning of the index.js file. Then initiate an instance of meterify._Correct_:~~~markdown# Step 1: Include Dependencies```jsconst mtr = require("meterify").meterify;const Web3 = require("web3");const meterify = meterify(new Web3(), "http://test.meter.io:8669");The application will require the metrify and web3 libraries. Include them as dependencies at the beginning of the index.js file. Then initiate an instance of meterify.Step 2: Create Some Accountsvar accounts = {  "alice":web3.eth.accounts.create(),  "bob":web3.eth.accounts.create()};Create some accounts for Bob and Alice. An account contains the public and private keys for blockchain transactions. These accounts need to be added to the local wallet before they can be used.<a name="writing-style"/>## Writing StyleBear in mind that not everyone reading the documentation will always have a strong command of English. Attempt to write for an international audience by using everyday vocabulary. Avoid the use of slang and difficult to understand words, with the exception of technical terminology. Spell words using American English, for consistency.### ParagraphsMake paragraphs three or four sentences long as much as possible. This is not a strict rule, but it is a good guideline and practice to follow. There may be certain regular cases where this is not always going to the the case, particularly when there is not enough information available. If there is too much information to contain in four or less sentences, splitting the paragraph into two may be an option.### Sentences Be clear, concise, and consistent, keeping sentences short and imperative where possible. While there is no hard rule on sentence length, using 25 words or less is recommended. Start sentences with simple form verbs when providing instructions.## Style GuidesFollow the appropriate style guide for the type of document you are preparing or modifying. These guides extend the standard guidelines, to account for the requirements and objectives of different document types. These include:* [API Documentation](api-doc-guidelines.html)* [Tutorials](tutorial-guidelines.html)* [Articles](article-guidelines.html)* [Code Examples](code-example-guidelines.html)<a name="regarding-git"/>## Regarding GitAs with titles, keep branch names intuitive and short. For example, align the branch name with a particular document or group of related documents.Long commit messages may be hard to follow and might sometimes be overkill, while short messages might not provide enough information. Depending on the situation, following the [Git 50/72 rule](https://www.midori-global.com/blog/2018/04/02/git-50-72-rule) may be applicable in the case of significant changes, whereas a commit that corrects a single spelling error would probably only require no more than a few words at the most.
````


# API Documentation Guidelines

The Meter API documentation focuses on the use of the [`meterify`](https://github.com/meterio/meterify) library, which is a modified version of [`web3`](https://github.com/ethereum/web3.js). The content is a combination of the `web3` documentation, and content specific to `meterify` and the Meter blockchain.

All API documentation should be written to reflect `meterify`. So where existing content that has been ported `web3` is mentioned, this should be replaced to the greatest extent possible with `meterify`. Some code snippets provide a good example of these kinds of changes.

**web3**

```
import Web3 from 'web3';

// "Web3.givenProvider" will be set in a Ethereum supported browser.
const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546', net, options);

web3.version
```

**meterify**

```
const meter = require("meterify").meterify;
const Web3 = require("web3");
const meterify = meter(new Web3(), "http://test.meter.io:8669");

meterify.version
```

Another example, where `web3` content might read:

```
For `web3.eth.subscribe` see the [`subscribe`](web3.eth.subscribe.html) reference documentation.
```

Modify it to read:

```
For `meterify.eth.subscribe` see the [`subscribe`](meterify.eth.subscribe.html) reference documentation.
```


# Tutorial Creation Guidelines

The value of tutorials as an instructional tool cannot be underestimated. Tutorials help guide a reader through a sequence of instructional steps, including relevant and informative explanations, in a way that other types of content are not designed for.

Writing attention-grabbing tutorials that provide a solution to a clearly identified problem or challenge is important for Meter technical documentation. The objective is to explain how to accomplish a set of tasks that works towards developing the solution, and also why each step or instruction is important. Explanations should be brief, informative, and focused on the main topic.

This guide is provided to ensure writers are equipped to create clear and interesting Meter specific tutorials, for both [development](/developer-documentation/meter-dapp-tutorials) and non-development purposes such as [mining](/mining/meter-mining-guide). It will outline some important features of tutorials, and include best practices, but is a work in progress. There is a lot that goes into tutorial writing, and as this guide further develops, this will become a more robust tutorial in itself.

* [Audience](https://docs.meter.io/contributing/tutorials-guidelines.html#audience)
* [Structure](https://docs.meter.io/contributing/tutorials-guidelines.html#structure)
* [Use of Examples](https://docs.meter.io/contributing/tutorials-guidelines.html#use-of-examples)

## Audience

Avoid promoting generic third-party tools that don't add much value in the context of Meter.&#x20;

For example, you may safely assume that the reader is already a developer familiar with code editors and syntax highlighting, so there is no need to mention these topics. However, something that is blockchain-centric and can make the reader's job easier when it comes to the specifics of the Meter blockchain may be worthwhile suggesting. It might even be worth writing a full tutorial about how to use it in a Meter context.&#x20;

An example of this could be an IDE that is focused on `web3`, which would likely then be relevant for `meterify` as well.

## Structure

Tutorials have three main sections: an introduction, a body, and a conclusion.&#x20;

The introduction should begin with a problem statement or an objective and describe a proposed solution. It should be 2 or 3 paragraphs long. This does not include any table of contents, which should also be included in the same section, just before the tutorial body.

The body is where to include sub-headings representing the sequential steps of the tutorial. It might also include other sub-headings, such as those that provide links to further reading. These sub-headings should be arranged in sequence, starting off small, and then building up the knowledge necessary to understand the final product.

A concluding statement at the end should be one paragraph long. It should be a review of the tutorial to help consolidate what the reader has learned, and insight into how the solution solves the original problem. The conclusion can also provide one or more links for further reading.

## Use of Examples

Tutorials address the need for better context than is typically possible with the API documentation alone. Building an example, showing each sequential modification, and explaining each step, is a great tutorial strategy. It helps to organize the overall flow of the tutorial, delivers the necessary context, and is an opportunity to provide insight into how each step fits into the overall objective.

Tutorials for developers will almost always focus on the use of `meterify`, and therefore should almost always correspond to a working [code example](/developer-documentation/contributing-to-meter-and-our-documentation/documentation-guidelines/code-example-guidelines). There may however be topics of interest to a developer that are less code related, or perhaps not specific to `meterify`, and therefore will not require any code example.&#x20;

One example might be a tutorial for using a development tool or framework that is compatible with `meterify` development. Relevant code snippets within the tutorial itself may suffice in that type of scenario, rather than including a corresponding example as well.

Keep the code blocks short, representing only the portions of code relevant to that step. Put a link to the full working example code somewhere at the start of the tutorial. This is convenient for the reader to see what the end result is going to look like before they start any further reading. And above all, make sure the example works.


# Code Example Guidelines

Code examples are generally succinct but fully functional applications. All development tutorials involving code should have a matching example that is available for reference or download. Smaller snippets of the example code are then used in the tutorial to guide a developer through the steps to complete the application.

More fully-featured and less succinct examples may be alternatively called a demo. The purpose of a demo may be as more of a showcase for what can be achieved, or accompany an article, and a corresponding tutorial might not be a necessity. However, the code can still provide value as a reference tool for developers, even without any article or tutorial that references it.

As with API documentation, examples should be written with `meterify` in mind, such as naming conventions. This may primarily come up with variables. To maintain consistency, all examples should use the following for including the necessary dependencies:

**Right way:**

```javascript
const meter = require("meterify").meterify;
const Web3 = require("web3");
const meterify = meter(new Web3(), "http://test.meter.io:8669");
```

**Wrong way:**

```javascript
const meterify = require("meterify").meterify;
const Web3 = require("web3");
const web3 = meterify(new Web3(), "http://test.meter.io:8669");
```


# Article Writing Guidelines

The objective of an article is to provide a high-level overview about a specific topic. It should answer questions related to what it is, and tightly-related details that provide more information.

## Word Count

Use no less than 1500 words and no more than 3000 words for an article. Consider splitting a topic into more than one article if more than 3000 words are required. If an article is too short, consolidate related topics into a new article, or include other tightly-related information to reach 1500 words.

## Writing Instructions

An article contains three sections: an intro, a body, and a concluding statement.&#x20;

The objective of the intro is to provide a succinct summary of the topic, outline the document that follows, and convince the reader to continue to read.&#x20;

The body is the main content that informs the reader about the main topic of the document, and should be as tightly related as possible.&#x20;

The concluding statement should be a paragraph that summarizes the article, and perhaps direct the reader to other related content.

### Intro

Keep the intro to between 6 and 10 sentences, broken down into 2 or 3 paragraphs. The first paragraph should be a quick 2 to 3 sentence summary of the topic, or some background to the topic, such as a problem statement. The remaining portion of the intro will begin to lead more into the topic itself, discuss what to expect by reading further, and to convince the reader to continue.

### Body

Follow the general [Documentation Guidelines](/developer-documentation/contributing-to-meter-and-our-documentation/documentation-guidelines) for how to break up an article into sub-headings. Keep the content of each to between 250 and 300 words. Break up a sub-heading into a second one, or child sub-headings if it begins to exceed 300 words.

Keep on topic. Help to answer questions about what the subject is, rather than how to use it. However, include tutorial-style information where applicable, but as sparingly and succinctly as possible. Give a very light summary in the shortest space possible, and refer to related tutorials for more details and instructions. Write a [new tutorial](/developer-documentation/contributing-to-meter-and-our-documentation/documentation-guidelines/tutorial-creation-guidelines) if none is available and the topic is of great enough importance.

### Conclusion

Close the article with one paragraph. Provide a review of what the reader has just read through, and summarize the topic in general again. Optionally, provide links to further reading or another call to action.


