Dart web3 - A dart library that connects and interacts with the Ethereum blockchain

Overview

dart_web3

A dart library that connects and interact with the Ethereum blockchain. It connects to an Ethereum node to send transactions, interact with smart contracts and much more!

Features

  • Connect to an Ethereum node with the rpc-api, call common methods
  • Send signed Ethereum transactions
  • Generate private keys, setup new Ethereum addresses
  • Call functions on smart contracts and listen for contract events
  • Code generation based on smart contract ABI for easier interaction

TODO

  • Encode all supported solidity types, although only (u)fixed, which are not commonly used, are not supported at the moment.

Usage

Credentials and Wallets

In order to send transactions on the Ethereum network, some credentials are required. The library supports raw private keys and v3 wallet files.

import 'dart:math'; //used for the random number generator

import 'package:dart_web3/dart_web3.dart';
// You can create Credentials from private keys
Credentials fromHex = EthPrivateKey.fromHex("c87509a[...]dc0d3");

// Or generate a new key randomly
var rng = Random.secure();
Credentials random = EthPrivateKey.createRandom(rng);

// In either way, the library can derive the public key and the address
// from a private key:
var address = await credentials.extractAddress();
print(address.hex);

Another way to obtain Credentials which the library uses to sign transactions is the usage of a wallet file. Wallets store a private key securely and require a password to unlock. The library has experimental support for version 3 wallets commonly generated by other Ethereum clients:

import 'dart:io';
import 'package:dart_web3/dart_web3.dart';

String content = File("wallet.json").readAsStringSync();
Wallet wallet = Wallet.fromJson(content, "testpassword");

Credentials unlocked = wallet.privateKey;
// You can now use these credentials to sign transactions or messages

You can also create Wallet files with this library. To do so, you first need the private key you want to encrypt and a desired password. Then, create your wallet with

Wallet wallet = Wallet.createNew(credentials, "password", random);
print(wallet.toJson());

You can also write wallet.toJson() into a file which you can later open with MyEtherWallet (select Keystore / JSON File) or other Ethereum clients like geth.

Custom credentials

If you want to integrate dart_web3 with other wallet providers, you can implement Credentials and override the appropriate methods.

Connecting to an RPC server

The library won't send signed transactions to miners itself. Instead,it relies on an RPC client to do that. You can use a public RPC API like infura, setup your own using geth or, if you just want to test things out, use a private testnet with truffle and ganache. All these options will give you an RPC endpoint to which the library can connect.

import 'package:http/http.dart'; //You can also import the browser version
import 'package:dart_web3/dart_web3.dart';

var apiUrl = "http://localhost:7545"; //Replace with your API

var httpClient = Client();
var ethClient = Web3Client(apiUrl, httpClient);

var credentials = ethClient.credentialsFromPrivateKey("0x...");

// You can now call rpc methods. This one will query the amount of Ether you own
EtherAmount balance = ethClient.getBalance(credentials.address);
print(balance.getValueInUnit(EtherUnit.ether));

Sending transactions

Of course, this library supports creating, signing and sending Ethereum transactions:

import 'package:dart_web3/dart_web3.dart';

/// [...], you need to specify the url and your client, see example above
var ethClient = Web3Client(apiUrl, httpClient);

var credentials = ethClient.credentialsFromPrivateKey("0x...");

await client.sendTransaction(
  credentials,
  Transaction(
    to: EthereumAddress.fromHex('0xC91...3706'),
    gasPrice: EtherAmount.inWei(BigInt.one),
    maxGas: 100000,
    value: EtherAmount.fromUnitAndValue(EtherUnit.ether, 1),
  ),
);

Missing data, like the gas price, the sender and a transaction nonce will be obtained from the connected node when not explicitly specified. If you only need the signed transaction but don't intend to send it, you can use client.signTransaction.

Smart contracts

The library can parse the abi of a smart contract and send data to it. It can also listen for events emitted by smart contracts. See this file for an example.

Dart Code Generator

By using Dart's build system, dart_web3 can generate Dart code to easily access smart contracts.

To use this feature, put a contract abi json somewhere into lib/. The filename has to end with .abi.json. Then, add a dev_dependency on the build_runner package and run

pub run build_runner build

You'll now find a .g.dart file containing code to interact with the contract.

Optional: Ignore naming suggestions for generated files

If importing contract ABIs with function names that don't follow dart's naming conventions, the dart analyzer will (by default) be unhappy about it, and show warnings. This can be mitigated by excluding all the generated files from being analyzed.
Note that this has the side effect of suppressing serious errors as well, should there exist any. (There shouldn't as these files are automatically generated).

Create a file named analysis_options.yaml in the root directory of your project:

analyzer:
  exclude: 
    - '**/*.g.dart'

See Customizing static analysis for advanced options.

NOTE.

This package was clone of web3dart version 2.3.3 originally created by @simolus3. This is one of the popular packages for dapp development in flutter eco-system, but yesterday(04-02-2022) web3dart is discontinued by its owner and marked as read-only. So I decided to release it as dart_web3 for the community.

From the original creator of web3dart:

I no longer want to support, contribute to, or be associated with cryptocurrencies and web3. So, the package is marked as discontinued and the repository is archived.
If anyone wants to continue maintaining this package, please get in touch.

Feature requests and bugs

Please file feature requests and bugs at the issue tracker. If you want to contribute to this library, please submit a Pull Request.

You might also like...

A mobile-responsive blockchain website built with flutter. NB: For educational purposes.

A mobile-responsive blockchain website built with flutter.      NB: For educational purposes.

Excursy A mobile-responsive blockchain website built with flutter. Build flutter build web --web-renderer html --release or flutter build web --web-re

Oct 25, 2022

Food Delivery on Blockchain

Food Delivery on Blockchain

Food Delivery on Blockchain This research is an application development to increase the reliability of food delivery businesses. By applying proven an

May 19, 2022

DeFi Scan - Mobile BlockChain Explorer app for cryptocurrency accounts.

DeFi Scan - Mobile BlockChain Explorer app for cryptocurrency accounts.

DeFi Scan This is the official repository for DeFi Scan - a mobile blockchain explorer built with Dart/Flutter for searching, curating and storing det

Dec 20, 2022

This library provides the easiest and powerful Dart/Flutter library for Mastodon API 🎯

This library provides the easiest and powerful Dart/Flutter library for Mastodon API 🎯

The Easiest and Powerful Dart/Flutter Library for Mastodon API 🎯 1. Guide 🌎 1.1. Features 💎 1.2. Getting Started ⚡ 1.2.1. Install Library 1.2.2. Im

Jul 27, 2023

A middleware library for Dart's http library.

http_middleware A middleware library for Dart http library. Getting Started http_middleware is a module that lets you build middleware for Dart's http

Oct 23, 2021

Flutter Control is complex library to maintain App and State management. Library merges multiple functionality under one hood. This approach helps to tidily bound separated logic into complex solution.

Flutter Control is complex library to maintain App and State management. Library merges multiple functionality under one hood. This approach helps to tidily bound separated logic into complex solution.

Flutter Control is complex library to maintain App and State management. Library merges multiple functionality under one hood. This approach helps to

Feb 23, 2022

Flutter book library - Book Library Application with Flutter and Google Book API

Book Library Application Flutter iOS, Android and Web with Google Book API Demo

Jan 25, 2022

[Flutter Library] Flamingo is a firebase firestore model framework library. 🐤

[Flutter Library] Flamingo is a firebase firestore model framework library. 🐤

Flamingo Flamingo is a firebase firestore model framework library. https://pub.dev/packages/flamingo 日本語ドキュメント Example code See the example directory

Sep 22, 2022

Flutter-Animated-Library-of-Books - Flutter App - Animated Book Library

bookshelf A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if thi

Dec 4, 2022
Comments
  • Metamask connection for Mobile App

    Metamask connection for Mobile App

    It would be amazing to find a way to connect Metamask mobile app to our native mobile app built with Flutter. For now the only possible thing is putting a private key in the code, but we can't directly ask private keys to users of course.

    opened by 0xCaso 1
  • going through examples -- getting errors ('address' doesn't refer to an import prefix)

    going through examples -- getting errors ('address' doesn't refer to an import prefix)

    This is from the example documentation:

    import 'dart:math'; //used for the random number generator
    
    import 'package:dart_web3/dart_web3.dart';
    // You can create Credentials from private keys
    Credentials fromHex = EthPrivateKey.fromHex("c87509a[...]dc0d3");
    
    // Or generate a new key randomly
    var rng = Random.secure();
    Credentials random = EthPrivateKey.createRandom(rng);
    
    // In either way, the library can derive the public key and the address
    // from a private key:
    var address = await credentials.extractAddress();
    print(address.hex);
    

    However, in my dart application, this creates errors.

    I modified some of the content, but it still gets an error:

    import 'package:dart_web3/dart_web3.dart';
    import 'package:http/http.dart';
    import 'dart:math'; //used for the random number generator
    
    // Or generate a new key randomly
    var rng = Random.secure();
    final EthPrivateKey credentials = EthPrivateKey.createRandom(rng);
    
    var address = await credentials.extractAddress();
    //print(address.hex);
    

    My changes solves for the type errors for credentials. But I still get an await error saying its missing async.

    Error: 'address.hex' can't be used as a type because 'address' doesn't refer to an import prefix

    opened by timfong888 0
  • Balance of erc20 token on polygon

    Balance of erc20 token on polygon

    Hi, I am reading the docs to see if we can generate on mobile flutter app a public address.

    That public address would receive an airdrop erc20 polygon token.

    The mobile app displays the erc20 balance.

    But it's polygon. It seems that as long as we add the correct RPC we can do this but wanted to confirm because wasn't fully clear when reading docs.

    Thanks.

    opened by timfong888 3
  • Secure wallet creation?

    Secure wallet creation?

    Hi is it possible to create a wallet that is compatible with MetaMask?

    It looks like from the code a wallet file can be created. But is the random number generator the right way to create the private keys?

    My use case: I want to be able to generate a legitimate public and private key pair on the mobile wallet to receive an airdrop token to the public address.

    But then that address can also be used in MetaMask.

    Thanks.

    opened by timfong888 0
Web3-demo-flutter - A demo for the flutter web3 library.

web3_demo_flutter A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you starte

Tommaso Azzalin 0 Oct 7, 2022
Ensdart - A dart library that wraps the Ethereum Name Service

⚡️ ENS Dart A dart library that wraps the Ethereum Name Service. The Ethereum Na

Chiziaruhoma Ogbonda 22 Nov 29, 2022
(Top 10 GDG Devfest 2021) Mobile Application to prove intellectual property rights using blockchain technology and NFT

brainshield A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if t

Nguyen Minh Dung 4 Jan 12, 2022
Naan is an easy to use and secure wallet for NFTs & DeFi on the Tezos blockchain.

Naan - A Tasty Tezos Wallet Naan is a fun, simple, and secure way to create a Tezos wallet, collect NFTs, and explore the new world of Web3 on Tezos.

Tezsure 3 Aug 26, 2022
Basic todo mobile application built on top of the ETH blockchain with Flutter, Truffle and Ganache.

Todo-DAPP This project is a basic mobile Todo App build with Flutter. The backend consist in a Solidity contract running on the Ethereum Blockchain. C

Lorenzo Gangemi 2 Sep 28, 2022
MedRec: Using Blockchain for Medical Data Access and Permission Management

MedRec Medical records need innovation. Patients leave data scattered across various jurisdictions as life events take them away from one provider’s d

Abhishek Kumar 4 Sep 14, 2022
constructing... Flutter, Ganache, Truffle, Remix, Getx Pattern, Infura, GetX, Blockchain

constructing... Flutter, Ganache, Truffle, Remix, Getx Pattern, Infura, GetX, Blockchain

Kauê Murakami 20 Dec 20, 2022
Tezart helps to interact with ​Tezos blockchain.

Tezart What it is Tezart is a Dart library for building decentralized applications on Tezos blockchain. Tezart interacts with a Tezos node to send tra

MoneyTrack 21 Dec 14, 2022
Official Sonr Blockchain Node implementation with Frontend Clients to access Wallet.

Sonr Blockchain Sonr-Chain is a blockchain built using Cosmos SDK and Tendermint and created with Starport. Get started starport chain serve serve com

Sonr 625 Dec 29, 2022
A blockchain based voting application built as a project for KJSCE Hack 6.0

Secure Vote A decentralized and transparent Blockchain-based voting application, built with Flutter, a Solidity Smart contract, Firebase and Infura as

Manas Gandhi 4 Nov 15, 2022