simolus3 / web3dart Goto Github PK
View Code? Open in Web Editor NEWEthereum library, written in Dart.
License: MIT License
Ethereum library, written in Dart.
License: MIT License
Here is my code, a button calls this function on tap
checkBalanceTester() async {
var apiUrl = "my_infura_api"; //Replace with your API
var httpClient = new Client();
var ethClient = new Web3Client(apiUrl, httpClient);
var credentials = Credentials.fromPrivateKeyHex("my_private_key");
// 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));
}
When deploying the smart contract to Ropsten network, I tried to listen to the events from the contract, however, I got an error.
There's no error when deploying the same smart contract to Ganache.
E/flutter (27128): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: RPCError: got code -32601 with msg "The method eth_newFilter does not exist/is not available".
E/flutter (27128): #0 JsonRPC.call
package:web3dart/json_rpc.dart:49
E/flutter (27128): <asynchronous suspension>
E/flutter (27128): #1 _FilterEngine._registerToAPI
package:web3dart/…/core/filters.dart:232
E/flutter (27128): <asynchronous suspension>
E/flutter (27128): #2 _FilterEngine.addFilter
package:web3dart/…/core/filters.dart:222
E/flutter (27128): #3 Web3Client.events
package:web3dart/…/core/client.dart:328
E/flutter (27128): #4 _DeviceDetailPageState._listenevent
package:iotdevices/pages/detail.dart:62
E/flutter (27128): <asynchronous suspension>
E/flutter (27128): #5 _DeviceDetailPageState.initState
package:iotdevices/pages/detail.dart:125
My listening event dart code is as below:
var privatekey =
"XXXXX";//Ropsten
final EthereumAddress contractAddr =
EthereumAddress.fromHex('XXXX);//Ropsten
var apiUrl =
"https://ropsten.infura.io/v3/XXX"; //Ropsten
var credentials = EthPrivateKey.fromHex(privatekey);
_listenevent() async {
String serveraddress = await SharedData.getServerAddress();
if (serveraddress.length > 5) {
apiUrl = serveraddress;
}
setState(() {
client = Web3Client(apiUrl, Client());
});
var contract = await Web3.deployedcontract();
final colorChangeEvent = contract.event('ColorChange');
subscription = client
.events(
FilterOptions.events(contract: contract, event: colorChangeEvent))
.take(4)
.listen((event) {
final decoded = colorChangeEvent.decodeResults(event.topics, event.data);
final deviceid = decoded[0] as String;
final red = decoded[1] as BigInt;
final green = decoded[2] as BigInt;
final blue = decoded[3] as BigInt;
print("event:ID:$deviceid");
print("event:red:${red.toInt()}");
print("event:green:${green.toInt()}");
print("event:blue:${blue.toInt()}");
var curid = widget.curdevice.bid.toInt().toString();
if (deviceid.contains(curid)) {
print("this device changed!");
var devcolor =
TransColor.trancolor(red.toInt(), green.toInt(), blue.toInt());
// print(widget.curdevice.green);
if (mounted) {
setState(() {
currentColor = Color(devcolor);
});
}
Event.eventBus.fire(new DeviceAdd(curdevices.name));
}
});
await subscription.asFuture();
}
How can I do with that error, is that the problem with https request? Thank you.
this is error
[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: RPCError: got code -32000 with msg "invalid sender".
await client.sendTransaction( credentials, Transaction( from: ethaddress, nonce: nonce, to: EthereumAddress.fromHex('0xC914Bb2ba888e3367bcecEb5C2d99DF7C7423706'), gasPrice: EtherAmount.inWei(BigInt.one), maxGas: 100000, value: EtherAmount.fromUnitAndValue(EtherUnit.ether, 1), ), fetchChainIdFromNetworkId: false, );
Have you considered using decimal instead of BigInt for the implementation of EtherAmount?
Error Log
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: Exception: Tried to call a transaction that modifys state
#0 FinalizedTransaction.call (package:web3dart/src/transaction.dart:124:4)
#1 _MyHomePageState._getSmartCoursesContract (package:flutter_token/main.dart:94:32)
<asynchronous suspension>
#2 _MyHomePageState.initState (package:flutter_token/main.dart:170:5)
#3 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3846:58)
#4 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3711:5)
#5 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2956:14)
#6 Element.updateChild (package:flutter/src/widgets/framework.dart:2759:12)
#7 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:4876:14)
#8 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2956:14)
#9 Element.updateChild (package:flutter/src/widgets/framework.dart:2759:12)
#10 ComponentElement.performR<…>
Contract ABI
const List coursesABI = [
{
"constant": true,
"inputs": [
{"name": "_address", "type": "address"}
],
"name": "getInstructor",
"outputs": [
{"name": "", "type": "string"},
{"name": "", "type": "string"},
{"name": "", "type": "uint256"}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "getInstructors",
"outputs": [
{"name": "", "type": "address[]"}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": false,
"inputs": [
{"name": "_address", "type": "address"},
{"name": "_fname", "type": "string"},
{"name": "_lname", "type": "string"},
{"name": "_age", "type": "uint256"}
],
"name": "setInstructor",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "countInstructors",
"outputs": [
{"name": "", "type": "uint256"}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{"name": "", "type": "uint256"}
],
"name": "instructorAccounts",
"outputs": [
{"name": "", "type": "address"}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
];
My function
void _getSmartCoursesContract() async {
String courseContractABI = json.encode(coursesABI);
print(courseContractABI);
String tokenAddress = "0x8b373636Ff3147FCc01B40b57114eC282e77E2df";
String privateKeyHex =
"79FD6A46633A4AF7B1C3C1CA1D5EDFEC35245D42A5A3661B29AFFD8263E32853";
var httpClient = new Client();
var ethClient = new Web3Client(apiUrl, httpClient);
var credentials = Credentials.fromPrivateKeyHex(privateKeyHex);
var contractHelloABI =
ContractABI.parseFromJSON(courseContractABI, "Courses");
var coursesContract = new DeployedContract(contractHelloABI,
new EthereumAddress(tokenAddress), ethClient, credentials);
var getCoursesFn =
coursesContract.findFunctionsByName("countInstructors").first;
var listTokenFn = coursesContract.functions;
print(listTokenFn[2].name);
// for (FunctionParameter fp in getCoursesFn.parameters) {
// print("Function ${getCoursesFn.name} ---- Parameters ${fp.name}");
// }
//
// for (int a = 0; a < listTokenFn.length; a++) {
// print(listTokenFn[a].name);
// }
// for (ContractFunction fn in listTokenFn) {
// for (FunctionParameter fp in fn.parameters) {
// print("Function ${fn.name} ---- Parameters ${fp.name}");
// }
// }
var age = new BigInt.from(24);
var coursesResponse = new Transaction(keys: credentials, maximumGas: 0);
FinalizedTransaction finalizedTransaction = coursesResponse.prepareForCall(
coursesContract,
listTokenFn[2],
[credentials.address.number, "Maugost", "Okore", age],
);
await finalizedTransaction.call(ethClient).then((result) {
//print(result);
});
}
I was expecting to get a list of transactions by using this library, but it seems that the method doesn't exist. How can I solve this issue without any limitation?
I have a method where I call my contract balance and decimals functions (see below):
case 'FNT':
try {
var abiCode = await DefaultAssetBundle.of(context).loadString('assets/json/fnt-abi.json');
if ( abiCode != null ) {
final EthereumAddress contractAddr = EthereumAddress.fromHex( '0x1f88badf3b56998673896572c8c1de846ab0e6c2' );
var contract = DeployedContract ( ContractAbi.fromJson( abiCode, 'FinentToken' ), contractAddr );
Credentials creds = EthPrivateKey.fromHex( crypto.privateKey );
EthereumAddress address = await creds.extractAddress();
// this is line 104 <- CryptoHelper.loadBalance (package:finent_wallet/src/helpers/crypto-helper.dart:104)
final balanceFunction = contract.function('balanceOf');
final decimalsFunction = contract.function('decimals');
final balance = await _client.call(
contract: contract, function: balanceFunction, params: [address]);
final decimals = await _client.call(
contract: contract, function: decimalsFunction, params: []);
BigInt bigBalance = BigInt.parse( balance.first.toString(), radix: 10 );
BigInt bigDecimals = BigInt.parse( decimals.first.toString(), radix: 10 );
cryptoBalances[crypto.symbol]['balance'] = bigBalance / BigInt.from(10).pow(bigDecimals.toInt());
break;
}
cryptoBalances[crypto.symbol]['balance'] = 0;
} catch( e ) {
debugPrint( e.toString() );
_showDialog( context, e.toString() );
}
break;
}
And somehow it works when in development mode, but when creating a released version of the app, I get to see this error:
E/flutter (23672): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: RangeError: Value not in range: 32
E/flutter (23672): #0 _rangeCheck (dart:typed_data-patch/typed_data_patch.dart:4445)
E/flutter (23672): #1 _ByteBuffer.asUint8List (dart:typed_data-patch/typed_data_patch.dart:1923)
E/flutter (23672): #2 _IntTypeBase.decode (package:web3dart/src/contracts/abi/integers.dart:23)
E/flutter (23672): #3 TupleType.decode (package:web3dart/src/contracts/abi/tuple.dart:102)
E/flutter (23672): #4 ContractFunction.decodeReturnValues (package:web3dart/src/contracts/abi/abi.dart:255)
E/flutter (23672): #5 Web3Client.call (package:web3dart/src/core/client.dart:303)
E/flutter (23672): <asynchronous suspension>
E/flutter (23672): #6 CryptoHelper.loadBalance (package:finent_wallet/src/helpers/crypto-helper.dart:104)
E/flutter (23672): <asynchronous suspension>
E/flutter (23672): #7 CryptoHelper.loadBalances (package:finent_wallet/src/helpers/crypto-helper.dart:59)
E/flutter (23672): <asynchronous suspension>
E/flutter (23672): #8 SplashState._navigateWhenUserExists (package:finent_wallet/src/screens/splash.dart:62)
E/flutter (23672): #9 _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:77)
E/flutter (23672): #10 _rootRunUnary (dart:async/zone.dart:1132)
E/flutter (23672): #11 _CustomZone.runUnary (dart:async/zone.dart:1029)
E/flutter (23672): #12 _FutureListener.handleValue (dart:async/future_impl.dart:126)
E/flutter (23672): #13 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639)
E/flutter (23672): #14 Future._propagateToListeners (dart:async/future_impl.dart:668)
E/flutter (23672): #15 Future._complete (dart:async/future_impl.dart:473)
E/flutter (23672): #16 _SyncCompleter.complete (dart:async/future_impl.dart:51)
E/flutter (23672): #17 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:28)
E/flutter (23672): #18 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:294)
E/flutter (23672): #19 DatabaseHelper.getList (package:finent_wallet/src/core/database_helper.dart:0)
E/flutter (23672): #20 _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:77)
E/flutter (23672): #21 _rootRunUnary (dart:async/zone.dart:1132)
E/flutter (23672): #22 _CustomZone.runUnary (dart:async/zone.dart:1029)
E/flutter (23672): #23 _FutureListener.handleValue (dart:async/future_impl.dart:126)
E/flutter (23672): #24 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639)
E/flutter (23672): #25 Future._propagateToListeners (dart:async/future_impl.dart:668)
E/flutter (23672): #26 Future._complete (dart:async/future_impl.dart:473)
E/flutter (23672): #27 _SyncCompleter.complete (dart:async/future_impl.dart:51)
E/flutter (23672): #28 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:28)
E/flutter (23672): #29 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:294)
E/flutter (23672): #30 _SqfliteDatabaseBase&Object&SqfliteDatabaseMixin.txnSynchronized (package:sqflite/src/database_mixin.dart:0)
E/flutter (23672): #31 _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:77)
E/flutter (23672): #32 _rootRunUnary (dart:async/zone.dart:1132)
E/flutter (23672): #33 _CustomZone.runUnary (dart:async/zone.dart:1029)
E/flutter (23672): #34 _FutureListener.handleValue (dart:async/future_impl.dart:126)
E/flutter (23672): #35 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639)
E/flutter (23672): #36 Future._propagateToListeners (dart:async/future_impl.dart:668)
E/flutter (23672): #37 Future._complete (dart:async/future_impl.dart:473)
E/flutter (23672): #38 _SyncCompleter.complete (dart:async/future_impl.dart:51)
E/flutter (23672): #39 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:28)
E/flutter (23672): #40 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:294)
E/flutter (23672): #41 BasicLock.synchronized (package:synchronized/src/basic_lock.dart:0)
E/flutter (23672): #42 _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:77)
E/flutter (23672): #43 _rootRunUnary (dart:async/zone.dart:1132)
E/flutter (23672): #44 _CustomZone.runUnary (dart:async/zone.dart:1029)
E/flutter (23672): #45 _FutureListener.handleValue (dart:async/future_impl.dart:126)
E/flutter (23672): #46 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639)
E/flutter (23672): #47 Future._propagateToListeners (dart:async/future_impl.dart:668)
E/flutter (23672): #48 Future._complete (dart:async/future_impl.dart:473)
E/flutter (23672): #49 _SyncCompleter.complete (dart:async/future_impl.dart:51)
E/flutter (23672): #50 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:28)
E/flutter (23672): #51 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:294)
To create a released version, I use the following terminal commands:
flutter clean
flutter build apk --release
Any idea what is going wrong here?
Hi Simon
I'm looking to connect my Flutter app to smart contracts on the EVM running on the Hedera Hashgraph test net.
Have you looked at Hedera at all? Was wondering how much of a change it would be to your web3dart library to support it?
Best
G
It's really awesome to use this plugin, it's very useful, I have learned how to set data to the blockchain and get data from the blockchain. The only problem now is I can listen to the events in the smart contract, I'm just wondering when will this function be supported. Cheers!
Thanks for what you have already done!
final balance = await client.call(
contract: contract, function: balanceFunction, params: [ownAddress]);
print('We have ${balance.first} MetaCoins')
example: balanceFunction decimal 18 how to convert to ether uint like 18000000000000000000 to 18
As the default n parameter for the scrypt algorithm in wallet.dart, Wallet createNew(...), is 8192, I think you should add a method to customize this value. In fact, 1024 is a more suitable value, balanced between security and time to produce the keystore.
I tried to get the output of a function, but the result I have is like that. How can I get the result, thank you.
function fetchDeviceStatus() public view returns ( string memory, uint, string memory )
var resp = await new Transaction(keys: credentials, maximumGas: 6521975) .prepareForCall(contract, fnfetchdevicestatus, []).send(ethClient);
Result:
[237, 129, 145, 92, 172, 45, 190, 132, 88, 86, 224, 55, 215, 225, 61, 244, 29, 98, 82, 90, 128, 255, 12, 212, 129, 75, 83, 147, 208, 197, 72, 147]
When i call the function below i receive this error.
static Future getClient(String key) async {
final getClientFn = SystemContract.findFunctionsByName('getClient').first;
final SystemResponse = await Transaction(keys: global_config.credentials, maximumGas: 0)
.prepareForCall(
SystemContract, getClientFn, [new EthereumAddress(key).number]).call(ethClient,chainId: 3);
return SystemResponse;
}
[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: RangeError: Value not in range: 64
If I clear the cached data, uninstall the app, disable the developer mode, then install the application again the error stop happening. for a while.
It would be great if you could add more documentation on how to create a fresh new wallet.
All the interesting stuffs like HD Wallets, Mnemonic recovery, ...
I'd really like to see if I can use this lib in my flutter application.
Could you please update
http: "^0.11.3+16"
to
http: "^0.12.0"
in the pubspec.
This is actually not an issue but just a place of following up the progress in implementation of latest wallets standards in the library.
I have already started with the mnemonic seed generation on my fork and hopefully will get that ready in a week with unit test and co.
web3dart/lib/src/web3client.dart
Line 184 in a0968df
function sendRawTransaction call _makeRPCCall without await, and then cannot catch the exception thrown by _makeRPCCall. The exception can't be transfered to the caller.
eg.
Using Ropsten and infura as an api provider. For some reason I keep getting this error. Anybody know why?
I/flutter (10196): SocketException: Failed host lookup: 'ropsten.infura.io' (OS Error: No address associated with hostname, errno = 7)
E/flutter (10196): [ERROR:flutter/shell/common/shell.cc(186)] Dart Error: Unhandled exception:
E/flutter (10196): SocketException: Failed host lookup: 'ropsten.infura.io' (OS Error: No address associated with hostname, errno = 7)
E/flutter (10196): #0 IOClient.send (package:http/src/io_client.dart:33:23)
E/flutter (10196): <asynchronous suspension>
E/flutter (10196): #1 BaseClient._sendUnstreamed (package:http/src/base_client.dart:169:38)
E/flutter (10196): <asynchronous suspension>
E/flutter (10196): #2 BaseClient.post (package:http/src/base_client.dart:54:7)
E/flutter (10196): #3 JsonRPC.call (package:web3dart/src/io/jsonrpc.dart:32:31)
E/flutter (10196): <asynchronous suspension>
E/flutter (10196): #4 Web3Client._makeRPCCall (package:web3dart/src/web3client.dart:29:30)
E/flutter (10196): <asynchronous suspension>
E/flutter (10196): #5 Web3Client.getTransactionCount (package:web3dart/src/web3client.dart:155:10)
E/flutter (10196): #6 FinalizedTransaction._asRaw (package:web3dart/src/transaction.dart:98:48)
E/flutter (10196): <asynchronous suspension>
E/flutter (10196): #7 FinalizedTransaction.send (package:web3dart/src/transaction.dart:114:10)
E/flutter (10196): #8 _MyHomePageState.test (package:flutter_web3/main.dart:59:10)
E/flutter (10196): <asynchronous suspension>
E/flutter (10196): #9 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:507:14)
E/flutter (10196): #10 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:562:30)
E/flutter (10196): #11 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
E/flutter (10196): #12 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9)
E/flutter (10196): #13 TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:204:7)
E/flutter (10196): #14 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
E/flutter (10196): #15 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:184:20)
E/flutter (10196): #16 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:158:22)
E/flutter (10196): #17 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:138:7)
E/flutter (10196): #18 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:101:7)
E/flutter (10196): #19 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:85:7)
E/flutter (10196): #20 _invoke1 (dart:ui/hooks.dart:173:13)
E/flutter (10196): #21 _dispatchPointerDataPacket (dart:ui/hooks.dart:127:5)
When I call a function on a contract(compiled solc0.5.0) that is returning a String value an error arises complaining about value not in range but the problem is in decode functions on dynamiclengthbytes and staticlengthbytes, I presume is due to the breaking changes in the new solidity version regarding left-aligned hex representation of String and padding issues, or maybe this
"Conversions between bytesX and uintY of different size are now disallowed due to bytesX padding on the right and uintY padding on the left which may cause unexpected conversion results. The size must now be adjusted within the type before the conversion"
I don't understand too much about it because I'm starting learning solidity and ethereum.
E/flutter (22015): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)]
Unhandled Exception: SocketException: Failed host lookup:
'localhost:8545' (OS Error: No address associated with hostname, errno
= 7)
I'm using a solidity contract version 0.5.0 and infura for sending transactions. The function is not payable
for this reason I'm using EtherAmount.zero() parameter
E/flutter (16270): RPCError: got code -32000 with msg "invalid sender".
E/flutter (16270): #0 JsonRPC.call (package:web3dart/src/io/jsonrpc.dart:47:4)
E/flutter (16270):
E/flutter (16270): #1 Web3Client._makeRPCCall (package:web3dart/src/web3client.dart:29:30)
E/flutter (16270):
E/flutter (16270): #2 Web3Client.sendRawTransaction (package:web3dart/src/web3client.dart:177:10)
E/flutter (16270): #3 FinalizedTransaction.send. (package:web3dart/src/transaction.dart:112:18)
It seems that the code is changed because I can't use some of the functionalities with the latest update. Please update the file.
I've upgraded Flutter and Dart and am getting an error:
Because every version of flutter_test from sdk depends on meta 1.1.6 and every version of web3dart from git depends on meta ^1.1.7, flutter_test from sdk is incompatible with web3dart from git.
Is there a way of downgrading the meta dependency in web3dart?
Thanks
G
const String rpcUrl = 'https://api.infura.io/v1/jsonrpc/rinkeby';
const String privateKey = *************;
final client = Web3Client(rpcUrl, Client(), enableBackgroundIsolate: true);
final credentials = await client.credentialsFromPrivateKey(privateKey);
final address = await credentials.extractAddress();
final etherAmount = await client.getBalance(address);
print(etherAmount.getValueInUnit(EtherUnit.ether));
when I run this code, this error occurs:
E/flutter (17927): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: RPCError: got code -32601 with msg "The method eth_getBalance does not exist/is not available".
E/flutter (17927): #0 JsonRPC.call (package:web3dart/json_rpc.dart:49:7)
E/flutter (17927):
E/flutter (17927): #1 Web3Client._makeRPCCall (package:web3dart/src/core/client.dart:58:35)
E/flutter (17927):
E/flutter (17927): #2 Web3Client.getBalance (package:web3dart/src/core/client.dart:192:12)
Trying to incorporate the web3dart package into my project. When I run pub get I receive the error:
web3dart ^0.3.0 requires build_runner ^0.8.0.
When I change build_runner to ^0.8.0 my project will not build and I get the error:
The build_runner version – 0.8.3 – is not within the allowed constraint – >=0.8.10 <0.10.0.
Appears I'm in a bind, in need of advice on how to proceed.
pubspec.yaml for reference:
environment:
sdk: '>=2.0.0-dev.67.0 <3.0.0'
dependencies:
angular: ^5.0.0-beta
angular_components: ^0.9.0-beta
angular_forms: ^2.0.0-beta
angular_router: ^2.0.0-alpha+15
firebase: ^5.0.0
json_serializable: ^0.5.2
web3dart: ^0.3.0
dev_dependencies:
angular_test: ^2.0.0-beta
build_runner: ^0.9.0
build_test: ^0.10.2
build_web_compilers: ^0.4.0
sass_builder: ^2.0.0
test: ^1.0.0
i am getting error while connecting with ethereum node
E/flutter (22015): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)]
Unhandled Exception: SocketException: Failed host lookup:
'mainnet.infura.io' (OS Error: No address associated with hostname, errno
= 7)
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:web3dart/web3dart.dart';
import 'dart:async';
const String url =
'https://mainnet.infura.io/v3/YOUR-PROJECT-ID'; //i have remove YOUR-PROJECT-ID temporarily to post this issue
class HomeScreen extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _HomeScreenState();
}
}
class _HomeScreenState extends State<HomeScreen> {
@override
void initState() {
main();
super.initState();
}
main() {
final httpClient =new Client();
final client =new Web3Client(url, httpClient);
print(client.getBlockNumber());
}
}
Here is the situation; I get the data below:
mnemonic -> seed -> extendedBase58 -> m/44'/60'/0'/0/0 child private key .
and I check these values on iancoleman , values are correct.
Then I use web3dart create Credentials and Wallet while I get the incorrect public key ,address ,and Keystore. May Someone tell me where the possible wrongs lie ?
It's not very sure that the code should be modified as follows, but for the original code when I test an empty String type data response, it would be failed. And the modified code works well.
int calculatePadLen(int actualLength) {
//must be padded with x so that actualLength + x = k * SIZE_UNIT_HEX
var mod = actualLength % SIZE_UNIT_HEX;
- return (mod == 0 && actualLength > 0) ? 0 : SIZE_UNIT_HEX - mod;
+ return mod == 0 ? 0 : SIZE_UNIT_HEX - mod;
}
When I run the app from Android Studio (both debug and flutter run --release) Wallet.fromJson is working but when I generate the signed apk and then I install it on the device, the right password does not work.
try { Wallet wallet = Wallet.fromJson(walletFile.readAsStringSync(), password); return wallet.privateKey; } catch (e) { print('Error'); return null; }
I build the apk using:
flutter clean
flutter build apk --release
(the same happens when generating signed apks)
I already tried to switch to beta channel of flutter, but it didn't solve the problem.
The exception is:
Invalid argument(s): Could not unlock wallet file. You either supplied the wrong password or the file is corrupted
From some tests I made it seems that the derivedMac generated by fromJson method is different if I run the app using a signed APK.
Hi Simon,
I'm trying to implement the event listening function to my app, when I deploy it I get the error:
Exception has occurred. FormatException (FormatException: Positive input exceeds the limit of integer 0x35732b9fba7d3dd3006cd7be339a88e4)
The code of my event Listening part as below:
_listenevent() async {
var contract = await Web3.deployedcontract();
final colorChangeEvent = contract.event('ColorChange');
final subscription = client
.events(
FilterOptions.events(contract: contract, event: colorChangeEvent))
.take(1)
.listen((event) {
final decoded = colorChangeEvent.decodeResults(event.topics, event.data);
final deviceid = decoded[0] as String;
final red = decoded[1] as BigInt;
final green = decoded[2] as BigInt;
final blue = decoded[3] as BigInt;
print(red.toInt());
});
await subscription.asFuture();
await subscription.cancel();
await client.dispose();
}
SendTransaction and call function are working well, is there something wrong with my code?
Thanks for your time.
I had previously been developing a simple app to record data into the Ethereum blockchain, and had used the web3.js package because I was in a javascript/Angular/browser world. I've now switched over to flutter/dart native device application and will be trying to use this package. Scanning the code and examples, it seems like a transaction's credentials are usually made starting from a privateKey. From documentation for web3.js, it was thought to be dangerous to be explicitly handling privateKeys. So I had used the 'geth' ethereum client to make an account ('geth account new'), providing a passphrase when creating it, with accounts ending up in an Ethereum keystore file. To use an account's address as a transaction's 'from' address, I had to unlock the account first ('web3.personal.unlockAccount' and provide the passphrase). For web3dart, do things work similarly? I see references to 'wallet' files, (String content = new File("wallet.json").readAsStringSync();
Wallet wallet = Wallet.fromJson(content, "testpassword");),
but I don't know if my keystore file is the same, or even usable. Looks like 'testpassword' is what selects the account(?), so if I have 2 accounts with the same password/passphrase, would this work? Or would I have to make new accounts using web3dart functions? Thanks for any help or guidance.
hey there,
is there a way to create a smart contract from the dart code? I can read the contract and also call the functions with the abi. But is there also a way, to create new contracts?
Thanks for help
When I send a transaction, I get an error:
error: {code: -32000, message: invalid sender}
I have been experimenting with the library outside of a Flutter app in a pure Dart command line application, everything seemed to work and then when I tried to move the code into a Flutter app it's bringing this weird type error when trying to generate a KeyPair by invoking Credentials.generateNew()
.
type 'AsymmetricKeyPair<PublicKey, PrivateKey>' is not a subtype of type 'AsymmetricKeyPair<ECPublicKey, ECPrivateKey>
package:web3dart/src/utils/keys.dart 45:63 generateNewPrivateKey
package:web3dart/src/utils/credentials.dart 44:27 Credentials.generateNew
My assumption is it might be crashing with some internals types with the same naming.
How to get the nonce ?
web3dart/lib/src/web3client.dart
Line 198 in a0968df
Is it should be setted by forcePadLen = 40 ?
String intToHex(dynamic d) => numbers.toHex(d, pad: true, include0x: true, forcePadLen: 40);
e.g. Send a tx to address "0x0000000000000000000000000000000000000100" cause error.
Using Infura, can get the events but when exit current page, it will drop error. It works fine using ganache.
I/flutter (13960): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (13960): The following NoSuchMethodError was thrown while finalizing the widget tree:
I/flutter (13960): The method 'dispose' was called on null.
I/flutter (13960): Receiver: null
I/flutter (13960): Tried calling: dispose()
My code is like that:
_listenevent() async {
network = await SharedData.getNetwork();
DeployedContract contract;
var apiUrl = Web3P.apiUrl;
if (network == "Private") {
contract = await Web3P.deployedcontract();
String serveraddress = await SharedData.getServerAddress();
if (serveraddress.length > 5) {
apiUrl = serveraddress;
}
client = Web3Client(apiUrl, Client());
final colorChangeEvent = contract.event('ColorChange');
subscription = client
.events(
FilterOptions.events(contract: contract, event: colorChangeEvent))
.take(1)
.listen((event) {
final decoded =
colorChangeEvent.decodeResults(event.topics, event.data);
final deviceid = decoded[0] as String;
final red = decoded[1] as BigInt;
final green = decoded[2] as BigInt;
final blue = decoded[3] as BigInt;
print("event:ID:$deviceid");
print("event:red:${red.toInt()}");
print("event:green:${green.toInt()}");
print("event:blue:${blue.toInt()}");
var curid = widget.curdevice.bid.toInt().toString();
if (deviceid.contains(curid)) {
print("this device changed!");
var devcolor =
TransColor.trancolor(red.toInt(), green.toInt(), blue.toInt());
// print(widget.curdevice.green);
if (mounted) {
setState(() {
currentColor = Color(devcolor);
});
}
Event.eventBus.fire(new DeviceAdd(curdevices.name));
}
});
await subscription.asFuture();
} else if (network == "Public") {
print("Listening to public");
var httpUrl =
"https://ropsten.infura.io/v3/xxx"; //Ropsten
var wsUrl =
"wss://ropsten.infura.io/ws/v3/xxx"; //Ropsten
contract = await Web3.deployedcontract();
final client = Web3Client(httpUrl, Client(), socketConnector: () {
return IOWebSocketChannel.connect(wsUrl).cast<String>();
});
final colorChangeEvent = contract.event('ColorChange');
subscription = client
.events(
FilterOptions.events(contract: contract, event: colorChangeEvent))
.take(5)
.listen((event) {
final decoded =
colorChangeEvent.decodeResults(event.topics, event.data);
final deviceid = decoded[0] as String;
final red = decoded[1] as BigInt;
final green = decoded[2] as BigInt;
final blue = decoded[3] as BigInt;
print("event:ID:$deviceid");
print("event:red:${red.toInt()}");
print("event:green:${green.toInt()}");
print("event:blue:${blue.toInt()}");
var curid = widget.curdevice.bid.toInt().toString();
if (deviceid.contains(curid)) {
print("this device changed!");
var devcolor =
TransColor.trancolor(red.toInt(), green.toInt(), blue.toInt());
// print(widget.curdevice.green);
if (mounted) {
setState(() {
currentColor = Color(devcolor);
});
}
// Event.eventBus.fire(new DeviceAdd(curdevices.name));
}
});
await subscription.asFuture();
}
}
@override
void dispose() {
subscription.cancel();
client.dispose();
super.dispose();
}
Another problem is, it will take a long time to receive an event from Infura, sometimes quickly, sometimes slowly, is it supposed to be like that?
Thanks for your time.
compiler message: file:///Users/tian/.pub-cache/hosted/pub.dartlang.org/web3dart-0.2.1/lib/src/web3client.dart:145:32: Error: A value of type '(dart.core::String) ??? dart.core::List<dart.core::int>' can't be assigned to a variable of type '(dynamic) ??? dart.async::FutureOr<dart.core::List<dart.core::int>>'.
compiler message: Try changing the type of the left hand side, or casting the right hand side to '(dynamic) ??? dart.async::FutureOr<dart.core::List<dart.core::int>>'.
compiler message: blockParam]).then(numbers.hexToBytes);
In the web3js transaction recipt there is a status tag that tells me if the transaction was excecuted successfully. After getting the Transaction information with web3.dart this status tag does not exist. I tested a failing and a not failing transactions (failing transaction reasons: not enough gas, require condition equals false). The problem is I don't see any difference whether a trancsaction fails in the transaction information of web3.dart. Is there a way for me to find out if a transaction succeeded or failed (without events or returns) because the EVM rolled it back?
Edit: Or is there a way to get the transaction recipt with status information (1/0 or true/false) whether the transaction succeeded?
I'm getting this error when I call the function balanceOf and set it to double
E/flutter (13715): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type '_BigIntImpl' is not a subtype of type 'double'
I run my smart contract on my MacBook, the IP address of my MacBook is 10.0.0.47, my flutter app runs on my phone in the same network 10.0.0.133, I can use the browser to access the web server on my MacBook, but when I tried to connect with my smart contract, it shows Connection refused, whatever I use private key or Json file, the result is the same.
Maybe this not the issue with web3dart, but can anybody help me with that, thanks a lot.
ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: SocketException: OS Error: Connection refused, errno = 111, address = 10.0.0.47, port = 45794
There are nodes, like infura, which don't support some operations like events when not connecting via a websocket. Thus, web3dart should also support the websocket rpc api.
This is what causes #37.
How to listen to ERC20 transfer events from/to a specific account?
And is there a way to wait for a transaction to be mined and then get the status?
I 've made a simple demo to test the cost on 2 platforms.The result follows:
2m15s on iOS device, 45s on Android device . not feel good :(
I'm using solidity version 0.5.0
when json abi string contains an event parameter the parse function still looks for statemutability key that in my case event types dont have that key in the interface, and the switch clause in the function in that case throws an error.
That error is easy to solve but I'm doing tests so finally I ripped that part from abi. you can watch events to know when an state changes.
the next line at abi.dart:327 in function decodeReturnValues should be changed as follows:
var decodedRaw = param.type.decodeRest(data);
===> var decodedRaw = param.type.decodeRest(modifiedData);
otherwise, the response cannot be parsed correctly.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.