dart_web3_core - a web3 library for dart that allows you to interact with a local or remote ethereum node using HTTP or WebSocket. Supports custom credentials providers like WalletConnect and Metamask.
Fork of original web3dart 2.3.5 by simolus3, incorporating all changes from other forks.
- 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
- Dart bindings generation based on smart contract ABI for easier interaction
- Encode all supported solidity types, although only (u)fixed, which are not commonly used, are not supported at the moment.
- Test coverage
- Wallet connect example
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_core/dart_web3_core.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 = credentials.address;
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:
```dart
import 'dart:io';
import 'package:dart_web3_core/dart_web3_core.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_core 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, set up 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 this library can connect.
Here's how you can setup a Web3Client:
import 'package:dart_web3_core/dart_web3_core.dart';
final client = Web3Client("https://mainnet.infura.io/v3/your_project_id", Client());
// Always call dispose() when you're done using the client to close open connections.
// The client is based on http.Client, so the way to do this depends on the client
// you're using. With the default http.Client, you can create a new client and call
// client.close() when you're done. This will close all pending http requests which
// is why it's important to only dispose it when you're truly done interacting with it.
Interacting with smart contracts The library has a high-level class for interacting with smart contracts. First, you need a DeployedContract object which represents a contract deployed on the blockchain. You need to know its address and ABI to create one.
import 'package:dart_web3_core/dart_web3_core.dart';
import 'package:web_socket_channel/io.dart';
// You can either create a DeployedContract from the abi and the contract's address...
var abiCode = '[{"constant":true,"inputs":[],"name":"count","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]';
var contractAddress = EthereumAddress.fromHex('0x2c...');
var contract = DeployedContract(ContractAbi.fromJson(abiCode, 'MyContract'), contractAddress);
// ...or if you have the source code and the ABI, use build_runner and web3dart to generate one
// for you. See the example and the readme for details on that.
// Once you have the contract, you can call methods on it! For example, to query the "count"
// method declared above, we would use
var count = contract.function('count');
// We can now read data from the contract. All data returned by the contract is wrapped in a
// `List<dynamic>`, so we need to extract the first element and cast it to BigInt.
// Note that we haven't specified any parameters for this call - if the function requires them,
// simply pass them as the second argument to `call`.
var result = await client.call(contract: contract, function: count, params: []);
BigInt count = result.first as BigInt;
print(count); // prints the current value of count
To send a transaction, use the sendTransaction method on your credentials object. For example, to increase the count in the contract above, we would call
await credentials.sendTransaction(client,
Transaction.callContract(contract: contract, function: count, parameters: []));
To listen for events emitted by the contract, you'd use
var subscription = client.events(FilterOptions.events(
contract: contract, event: contract.event('MyEvent'))).listen((event) {
final decoded = contract.event('MyEvent').decodeResults(event.topics, event.data);
// Do something with the event data
print(decoded);
});
// Don't forget to cancel the subscription when you're done
await subscription.cancel();
Working with streams
The library supports Dart's stream abstraction for real-time updates. For example, you can subscribe to new blocks being mined with
var sub = client.newBlocks().listen((block) {
print(block);
});
// As with any stream, don't forget to cancel the subscription when you're done.
await sub.cancel();
import 'dart:convert';
import 'dart:html';
import 'dart:typed_data';
conditionally import dependencies in order to support web and other platform builds from a single codebase
import 'package:js/js.dart'
if (dart.library.io) 'package:dart_web3_core/lib/src/browser/js-stub.dart'
if (dart.library.js) 'package:js/js.dart';
import 'package:dart_web3_core/browser.dart'
if (dart.library.io) 'package:dart_web3_core/lib/src/browser/dart_wrappers_stub.dart'
if (dart.library.js) 'package:dart_web3_core/browser.dart';
import 'package:dart_web3_core/dart_web3_core.dart';
@JS()
@anonymous
class JSrawRequestParams {
external String get chainId;
Must have an unnamed factory constructor with named arguments.
external factory JSrawRequestParams({String chainId});
}
Future<void> main() async {
final eth = window.ethereum;
if (eth == null) {
print('MetaMask is not available');
return;
}
final client = Web3Client.custom(eth.asRpcService());
final credentials = await eth.requestAccount();
// you can also use eth.requestAllAccounts() to have an array of all authorized Metamask accounts.
print('Using ${credentials.address}');
print('Client is listening: ${await client.isListeningForNetwork()}');
final message = Uint8List.fromList(utf8.encode('Hello from webthree'));
final signature = await credentials.signPersonalMessage(message);
print('Signature: ${base64.encode(signature)}');
await eth.rawRequest('wallet_switchEthereumChain',
params: [JSrawRequestParams(chainId: '0x507')]);
final String chainIDHex = await eth.rawRequest('eth_chainId') as String;
final chainID = int.parse(chainIDHex);
print('chainID: $chainID');
}
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.
By using Dart's build system, webthree can generate Dart code to easily access smart contracts.
To use this feature, put a contract abi json into lib/src/generated/abi
.
The filename has to end with .abi.json
.
dart run build_runner build
You'll now find a .g.dart
file containing code to interact with the contract.
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:
excluding:
- '**/*.g.dart'
See Customizing static analysis for advanced options.
Dart Decimals by Alexandre Ardhuin [Apache-2.0 license]
Please file feature requests and bugs at the issue tracker. If you want to contribute to this library, please submit a Pull Request.