Agent library for Internet Computer, in Dart

Overview

agent_dart

pub package

GitHub license

An agent library built for Internet Computer, a plugin package for dart and flutter apps. Developers can build ones to interact with Dfinity's blockchain directly.


πŸ“ƒ Table of content

  1. Table of content
  2. Prerequisites
  3. Quick start
  4. Motivation
  5. Milestones
  6. Documentation
  7. Contributing
  8. Reference and related projects
  9. FAQ

🚦 Prerequisites

  • Flutter version in the agent_dart/pubspec.yaml
  • CMake v3.2.0 or later
  • Xcode (10.12) or later (Running on macOS or iOS)
  • Android NDK version 21.4.7075529 (Running on Android)
  • Rust version 1.51
  • Node.js v15.0 or later, TBD

⚑️ Quick start

  1. git clone

  2. install Prerequisites, make sure you run

    flutter doctor -v
    

    Without errors

  3. To run example, follow instructions under example folder

  4. To run tests:

    flutter test
    

πŸ§˜β€β™‚οΈ Motivation

The Internet Computer is powered by blockchain and its major impact is to bring WebApp to be truly decentralized. However, we are in the mobile internet era, even we can use Safari or Chrome on our cell phones. But most average people, not crypto enthusiasts, are likely to use native mobile apps, major users are there.

It's important to attract these people to use Dapps of Internet Computer, by providing stable, fast, and fully integrated to Dfinity's blockchain. We likely to provide further solution to balancing the "Decentralization" and "Efficiency". But first things first, we have to make mobile native apps work.

agent-rs and agent-js are the actual lower level client-SDKs, just like ether.js or web3.js of Ethereum's ecosystem. This library is aiming to port and replicate features from them. And this library is mainly for mobile apps to connect canisters, not deploying contracts (you can do that if you want, but use dart directly).

We have tried our best to migrate most interface styles just like Javascript version, but there are limitations and differences between different programming languages, we will document them as much as possible.


πŸ† Milestones

Milestone 1: Core features/libraries migrating.

  • agent, core library, with crypto and encoding/decoding methods , http call/query encapsulated, for interacting with canister.
  • auth_client, a popup window for flutter, used for getting authentication from Identity provider(eg, Internet Identity).
  • authentication, a library supports auth_client
  • candid, candid library, used for encoding/decoding candid data types, and used them in dart-lang.
  • principal, principal library, used for generate principal for many usage cases.
  • protobuf, protobuf library, used for interacting with rosetta-node in submit/query transaction
  • utils, common utils, including useful helpers like extension methods in dart.
  • wallet, wallet library, signer, rosetta, key-smith all-in-one library.

Milestone 2: Enhanced built tool and more example apps

Milestone 3: Documentation and community driven development


πŸ“˜ Documentation

Reference on pub.dev

Plan for docs site

A stand-alone docs site with guides for Dfinity Dapps made in Flutter/Dart


πŸ‘¨β€πŸ’» Contributing

By contributing to agent_dart, you agree that your contributions will be licensed under its MIT License.

  1. Fork this library and add your own branch. like this:

    {github_id}/{feat|fix|test|dep}-{detail}
    
  2. Install Prerequisites

  3. Build rust dependencies for all supported platform (macOS, iOS, Android, windows, linux)

    $ sh ./scripts/clean && ./scripts/init.sh && ./scripts/build.sh
  4. Start example

    Read instruction first, then run

    $ cd example
    $ flutter run
  5. Test (Unit Test and Integration Test)

    $ flutter test
  6. Commit and make a pull request, process is TBD for now. We will use CI to automate


πŸ”— Reference and related projects


⚠️ FAQ

Build rust libraries for iOS/macOS

  • All rust method have to be written inside SwiftAgentDartPlugin.swift, to avoid tree shaking of latest release build by XCode.
  • The agent_dart_podspec should change accordingly when this repo goes 1.0.0

Network problem in iOS and macOS

  • If you run example or build a flutter app, you may come up with this:
[macOS] SocketException: Connection failed (OS Error: Operation not permitted, errno = 1)
  • Go to macos/Runner/ of macOS and ios/Runner
  • Edit DebugProfile.entitlements and ReleaseProfile.entitlements, Add following:
<key>com.apple.security.network.client</key>
<true/>
Comments
  • [Bounty] Candid builder for dart class

    [Bounty] Candid builder for dart class

    Description

    To build a candid builder for agent dart

    Context

    Candid is used to describe IDL for canister functions. Candid builder is used to transform candid files to usable functions/classes for agent clients in different languages. For dart language, all interfaces are classes. To make a workable builder, like we do json decoding classes, candid builder should also transform all those interfaces into classes.

    Candid files are trans-compiled into typescript and javascript using didc, link is here

    There are repos maintained by community for other languages:

    1. Kotlin
    2. Haskell
    3. AssemblyScript
    4. elm

    Since agent_dart is ported agains agent-js, all IDL interfaces and styles are very similar to javascript/typescript.

    for example , in generarted javascript:

    const Purpose = IDL.Variant({
        'authentication' : IDL.Null,
        'recovery' : IDL.Null,
    });
    const CredentialId = IDL.Vec(IDL.Nat8);
    

    in agent_dart, we can almost simply copy paste

    final Purpose = IDL.Variant({
        'authentication' : IDL.Null,
        'recovery' : IDL.Null,
    });
    final CredentialId = IDL.Vec(IDL.Nat8);
    

    So we might be able to :

    1. modify and use didc to generate those idl,
    2. THEN write classes using dart builder

    To see working classes in dart, please refer to wallet/ledger.dart

    Acceptance Criteria

    • [ ] modify and combine didc to builder to generate idls
    • [ ] use dart builder to generate artifacts in dart classes
    • [ ] tests and working examples, published to other repo.

    Reward

    30 ICPs

    enhancement bounty solved 
    opened by neeboo 11
  • Error while creating an actor

    Error while creating an actor

    This is the error that I am getting while creating an actor

    ArgumentError: Invalid argument(s): Failed to lookup symbol 'bls_verify': dlsym(RTLD_DEFAULT, bls_verify): symbol not found
    

    Full Stack Trace:

    ArgumentError: Invalid argument(s): Failed to lookup symbol 'bls_verify': dlsym(RTLD_DEFAULT, bls_verify): symbol not found
      File "ffi_dynamic_library_patch.dart", line 34, in DynamicLibrary.lookup
      File "ffi_base.dart", line 23, in rustBlsVerify
      File "bls.ffi.dart", in FFIBls.blsVerifySync
      File "certificate.dart", line 155, in Certificate.verify
      File "<asynchronous suspension>"
      File "certificate.dart", line 179, in Certificate._checkDelegation
      File "<asynchronous suspension>"
      File "certificate.dart", line 149, in Certificate.verify
      File "<asynchronous suspension>"
      File "index.dart", line 17, in pollForResponse
      File "<asynchronous suspension>"
      File "actor.dart", line 432, in _createActorMethod.<fn>
    

    If it helps, my app communicates with a dozen dynamic canisters and creates dozen of actors using this common method

      Future<CanisterActor> getVideoCanisterActor(String canisterId) async {
        if (_canisters[canisterId] == null) {
          AgentFactory _videoCanisterAgent = await AgentFactory.createAgent(
            canisterId: canisterId,
            url: backendUrl,
            idl: videoCanisterIDL,
          );
          _canisters[canisterId] = _videoCanisterAgent.actor!;
        }
        return _canisters[canisterId]!;
      }
    
    solved 
    opened by awazgyawali 9
  • Error with Delegation Identity

    Error with Delegation Identity

    Hello,

    When I try to use IC identity (using local page), I got a normal identity, and the result is like in the example project in this lib. After that, I am calling the IC canister, and I got an error. Error: Unhandled Exception: Unhandled error Server returned an error: Code: 403 (Forbidden)

    Body: Failed to authenticate request 0x5f5b53a270e40c4558549975f54c17163b24b337054255bc1c2e56705fab9860 due to: Invalid delegation: Invalid canister signature: IcCanisterSignature signature could not be verified: public key 0a000000000000000701012ad6fa197bcc32c16f588d58ccb0468c9bd039c9b60302ad08e03cda98f6243f, signature d9d9f7a26b63657a9.......678301820458200e729de08c6bfa677847fb8d7bcc79efc892045aed2c4b350f7c7446085257f5830182045820b71837514f52507ff04caee7b05a920f1d5ac8863b9d65d3489951ff33b1187e83025820f487586c5bdaaa19d6f10abc3626e44af4624a386c64832659da432f265a61f5830258208b8ee0cf244a56d1b8fa863141be1b473f9e0576d941282124d41e2b44793519820340, error: the signature tree doesn't contain sig/f487586c5bdaaa19d6f10abc3626e44af4624a386c64832659da432f265a61f5/2baf862838777c8dfc951a5b4b3768b5ce23bc641ea0a1172f3e0726de7ae936

    I don't have any problem with normal identity (created by myself), but this Delegation one made this error.

    Do you have some idea how to solve this problem?

    opened by Nikola1994 8
  • Connection refused when fetching status for root key of local replica

    Connection refused when fetching status for root key of local replica

    I'm encountering this error when calling fetchRootKey() of HttpAgent in _initAgent():

    E/flutter (23155): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: http request failed because SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 46950 E/flutter (23155): #0 HttpAgent._defaultFetch (package:agent_dart/agent/agent/http/index.dart:433:7) E/flutter (23155): E/flutter (23155): #1 HttpAgent.status (package:agent_dart/agent/agent/http/index.dart:362:20) E/flutter (23155): E/flutter (23155): #2 HttpAgent.fetchRootKey (package:agent_dart/agent/agent/http/index.dart:246:20) E/flutter (23155): E/flutter (23155): #3 AgentFactory._initAgent (package:agent_dart_example/init.dart:63:7) E/flutter (23155): E/flutter (23155):

    This means that the port somehow gets changed since I specified port 40161 in the url of the AgentFactory (this is where my local replica runs). I also tried to directly set the port with the host parameter of HttpAgentOptions but still get the same error.

    Am I missing something?

    solved 
    opened by theonlyandreas 4
  • Exception: Subclasses of `FlutterRustBridgeBase` should be singletons - there should not be two instances (runtimeType=AgentDartImpl)

    Exception: Subclasses of `FlutterRustBridgeBase` should be singletons - there should not be two instances (runtimeType=AgentDartImpl)

    agent_dart Branch: 1.0.0-dev
    Commit: 0b39334b70a30f593d0bc6c8f744ac9300659faf

    Stack Trace:

    _Exception: Exception: Subclasses of `FlutterRustBridgeBase` should be singletons - there should not be two instances (runtimeType=AgentDartImpl)
      File "basic.dart", line 28, in FlutterRustBridgeBase._sanityCheckSingleton
      File "basic.dart", line 19, in new FlutterRustBridgeBase
      File "ffi_bridge.dart", line 314, in new AgentDartImpl.raw
      File "ffi_bridge.dart", line 312, in new AgentDartImpl
      File "ffi_helper.dart", line 40, in new AgentDartFFI._
      File "ffi_helper.dart", line 50, in AgentDartFFI._instance
      File "ed25519.dart", in Ed25519KeyIdentity.generate
      File "auth_client.dart", line 212, in AuthClient.login
      File "login.dart", line 61, in _LoginScreenState._loginUsingII
    

    The exact function that caused the issue is Ed25519KeyIdentity.generate from AuthClient package.

    solved 
    opened by awazgyawali 3
  • how to send icp to an account

    how to send icp to an account

    I want to send icp to account: 1586275a55430abba47862989da56f2c9ac31bc9f1c58739d6637a33714f307a Here is my code: var mne ='xxx'; var p = RosettaApi(); var key = fromMnemonicWithoutValidation(mne, []); await p.init(); var pre = await p.transferPreCombine( key.getPublicKey().toRaw(), hex.HEX.decode( '1586275a55430abba47862989da56f2c9ac31bc9f1c58739d6637a33714f307a'), BigInt.from(90000), BigInt.from(10000), {}); var s = await transferCombine(key, pre); var res = await p.transfer_post_combine(s); print(res);

    But when I run code above, I get some error. Could you please give me a code example, thanks.

    enhancement good first issue 
    opened by xiao11lang 2
  • ⚑️ Improvements

    ⚑️ Improvements

    • Improve all import/export sorts.
    • Add @immutable as much as possible.
    • Better construct for RosettaTransaction and RecClass.
    • Make PrimitiveType's constructor private.
    • Constraint Android API support range to 23~32.
    opened by AlexV525 1
  • [Web] Http response error: http request failed because Error on line 1, column 17: Invalid media type: expected no more input.

    [Web] Http response error: http request failed because Error on line 1, column 17: Invalid media type: expected no more input.

    Error

    1 β”‚ application/cbor, application/cbor

    Description:

    While execute with update and query call using flutter web, the IC behaves differently between Native and Web, which is on the Web, IC (mainnet) may return dual headers to the client, somehow it's However, agent_dart using flutter/dart's official http package to make the requests internally. Although the Response class from Http returns normally, however, while using Response.body to get a string( in order to display non-bytes error or message), the MediaType.parse function will throw error since it only supports single type Media type.

    Fix: To set Response.headers manually ,only accept the first content-type and discard the rest, before getting the body string.

    https://github.com/AstroxNetwork/agent_dart/blob/f6f41e842999a710da9f4f20dfcdaea1bc2e0904/lib/agent/agent/http/fetch.dart#L73

    solved 
    opened by neeboo 1
  • Flutter Web support

    Flutter Web support

    Update: Try this branch https://github.com/AstroxNetwork/agent_dart/tree/feat/web

    Worth trying for further experiment: https://github.com/EPNW/web_ffi

    TODO:

    • ~~Migrate bls_init & bls_verify to WASM built for Flutter Web~~
    • ~~Other possible compatible problem~~
    enhancement 
    opened by neeboo 1
  • Looking for a replacement method to encode/decode the ( phrase || privateKey ) <> keystore

    Looking for a replacement method to encode/decode the ( phrase || privateKey ) <> keystore

    Thinking about the keystore file format compatible to ethereum's system, however is not so efficiency. But it still worth finding a replacement to the format.

    In dart, to implement the keystore encode/decode, one has to combine the scrypt and pbkdf2 to it. The easiest way to complete the job is to borrow the code from web3dart or laksadart I previously built for Zilliqa. However the encoding speed is too slow because of scrypt algorithm is slow.

    Another option is to use FFI from other native library like ethsign , it is fast and run smoothly when I tried to bind it to the dynamic library. However, in rust we generally use serde_json to encode the Crypto object, the serde_json will be binded too, which will largely increase the bundle's size.

    I don't have enough time to do enough search to finish the task. So if you have idea or solution, please comment or reply.

    1. A replacement standard or format for keystore.
    2. A fast and efficient way to encode/decode using FFI or pure dart code.
    3. Any other good ideas
    enhancement 
    opened by neeboo 1
  • Feat/signer+candid

    Feat/signer+candid

    added CurveType to Signer.importPhrase and related area

    • https://github.com/AstroxNetwork/agent_dart/blob/e8737627911b0ac24460ecfc71378bd0322e64e8/lib/wallet/signer.dart#L252-L255
    • https://github.com/AstroxNetwork/agent_dart/blob/e8737627911b0ac24460ecfc71378bd0322e64e8/lib/wallet/signer.dart#L196-L197
    • https://github.com/AstroxNetwork/agent_dart/blob/e8737627911b0ac24460ecfc71378bd0322e64e8/lib/wallet/signer.dart#L182-L186
    • https://github.com/AstroxNetwork/agent_dart/blob/e8737627911b0ac24460ecfc71378bd0322e64e8/lib/wallet/signer.dart#L179
    • https://github.com/AstroxNetwork/agent_dart/blob/e8737627911b0ac24460ecfc71378bd0322e64e8/lib/wallet/signer.dart#L82-L83
    • https://github.com/AstroxNetwork/agent_dart/blob/e8737627911b0ac24460ecfc71378bd0322e64e8/lib/wallet/signer.dart#L51-L55
    opened by neeboo 0
  • Add support for pure dart projects.

    Add support for pure dart projects.

    Right now the project has a dependency on flutter thus it's not possible to use the package on a pure dart environment like a server-side dart.

    Package behaves more like agent_flutter rather than agent_dart.

    enhancement 
    opened by awazgyawali 3
  • Projects using agent_dart

    Projects using agent_dart

    Feel free to submit your projects here, and we will move them to README, and later to doc site

    Template below:


    • Project Name

    My very cool project

    • Project Type

    Defi DApp/Wallet/Metaverse/Social DApps/Open Service/Tooling....

    • Description

    Your project description

    • Official Website

    If available

    • Download Link/Market URI

    If available, Google Play/ Apple AppStore/ other URL


    good first issue 
    opened by neeboo 0
  • [Bounty]Documentation for agent_dart apis

    [Bounty]Documentation for agent_dart apis

    Description

    Documentation for agent_dart apis

    Context

    To have better understanding of internet computer, for client developers, it is the best way to understand how the sdk works.

    Though we have ported most agent-js features to agent_dart, we don't have enough resources to complete the api docs. Which is really important work for community developers.

    Thus, we need to cover as many apis as possible, we need someone to comment on code like we do for dart code.

    Acceptance Criteria

    • [ ] [comment on code to cover all apis]
    • [ ] [generate dart docs]
    • [ ] [optional generate gitbook or github pages]
    • [ ] [optional tutorial/docs site for developers]

    Reward

    [20 ICPs, with 10 ICPs bonus for docs site]

    bounty 
    opened by neeboo 0
Releases(v1.0.0-dev.7)
  • v1.0.0-dev.7(Nov 30, 2022)

    What's Changed

    • Fix RecordClass covariant. (#48)

    Full Changelog: https://github.com/AstroxNetwork/agent_dart/compare/v1.0.0-dev.6...v1.0.0-dev.7

    Source code(tar.gz)
    Source code(zip)
  • v1.0.0-dev.6(Oct 18, 2022)

    What's Changed

    • bnToHex not produce 0x by default.
    • hexFixLength and isHex now use named arguments.
    • Remove isHexString and isHexadecimal.
    • Allow to configure include0x with toHex.
    • Add secp256K1SignRecoverable with FFI upgrade.

    Full Changelog: https://github.com/AstroxNetwork/agent_dart/compare/v1.0.0-dev.5...v1.0.0-dev.6

    Source code(tar.gz)
    Source code(zip)
  • v1.0.0-dev.5(Sep 30, 2022)

    What's Changed

    • Fix isHex and isTestChain.
    • Remove IdentityDescriptor.

    Full Changelog: https://github.com/AstroxNetwork/agent_dart/compare/v1.0.0-dev.4...v1.0.0-dev.5

    Source code(tar.gz)
    Source code(zip)
  • v1.0.0-dev.4(Sep 29, 2022)

    What's Changed

    • Improve all import/export sorts.
    • Add @immutable as much as possible.
    • Better construct for RosettaTransaction and RecClass.
    • Make PrimitiveType's constructor private.
    • Constraint Android API support range to 23~32.

    Full Changelog: https://github.com/AstroxNetwork/agent_dart/compare/v1.0.0-dev.3...v1.0.0-dev.4

    Source code(tar.gz)
    Source code(zip)
  • v1.0.0-dev.3(Sep 23, 2022)

    What's Changed

    • πŸ› Use the correct super class for HttpAgentCallRequest by @AlexV525 in https://github.com/AstroxNetwork/agent_dart/pull/39

    Full Changelog: https://github.com/AstroxNetwork/agent_dart/compare/v1.0.0-dev.2...v1.0.0-dev.3

    Source code(tar.gz)
    Source code(zip)
  • v1.0.0-dev.2(Sep 22, 2022)

    What's changed

    Tweak ignored files for pub.dev.

    Full Changelog: https://github.com/AstroxNetwork/agent_dart/compare/v1.0.0-dev.1...v1.0.0-dev.2

    Source code(tar.gz)
    Source code(zip)
  • v1.0.0-dev.1(Sep 16, 2022)

    • Support FFI asynchronized methods with Rust bindings.
    • Consist of all namings, fields, and constructors, including:
      • fromMap -> fromJson
      • toJSON -> toJson
    • Better throws when exceptions occurred.
    • Remove unused codes.
    Source code(tar.gz)
    Source code(zip)
Owner
null
A cryptocurrency, crypto-currency, or crypto is a digital currency designed to work as a medium of exchange through a computer network that is not reliant on any central authority

A cryptocurrency, crypto-currency, or crypto is a digital currency designed to work as a medium of exchange through a computer network that is not reliant on any central authority, such as a government or bank, to uphold or maintain it.

Prashant Kumar Singh 10 Dec 3, 2022
Connectionstatusbar - Flutter connection status bar, widget that animates when internet connection changes

connection_status_bar A widget that animates when internet connection changes Getting Started add it to your dependencies then use it anywhere on your

Amir Ghezelbash 112 Nov 23, 2022
A Dart library for creating a Dart object to represent directory trees.

Directory Tree A Dart library for creating a Dart object to represent directory trees. Getting Started Import and initialize package import 'package:d

Chiziaruhoma Ogbonda 5 Dec 1, 2021
A type-safe command-line parsing library for Dart

plade Plade is a type-safe CLI parsing library for Dart. Highlights Fully type-safe and null-safe. Support for a variety of different parsing styles (

Ryan Gonzalez 6 Jan 1, 2022
ThingsBoard PE API client library for Dart developers.

ThingsBoard PE API client library for Dart developers. It's compatible with TB PE 3.3.0. Usage A simple usage example: import 'package:thingsboard_pe_

ThingsBoard - Open-source IoT Platform 45 Sep 28, 2022
An equation solving library written purely in Dart.

An equation solving library written purely in Dart Thanks to the equations package you will be able to solve numerical analysis problems with ease. It

Alberto 43 Dec 27, 2022
A Dart library with a solution to use smart enums

Smart Enums Author: Jop Middelkamp A package that can help you create 'smarter' enums that could be extended with some domain logic. Usage final bestF

Jop Middelkamp 2 Oct 1, 2022
A mock library for Dart inspired by mockito

?? mocktail This repository contains mocking libraries for Dart inspired by mockito. package:mocktail A Dart mocking library which simplifies mocking

Felix Angelov 430 Dec 25, 2022
Bosun is a library for building organized command line applications in Dart.

Bosun A library for parsing CLI input and structuring CLI commands Features Structure CLI commands in a nice, uniform fashion. Parse args and flag inf

null 3 Oct 13, 2022
A fast and space efficient library to deal with data in Dart, Flutter and the web.

Dart Data Dart Data is a fast and space efficient library to deal with data in Dart, Flutter and the web. As of today this mostly includes data struct

Lukas Renggli 14 Nov 4, 2022
A simple DLNA DMC library implemented by Dart.

DLNA-Dart A simple DLNA DMC library implemented by Dart. It is tiny and only the basic network video casting function is supported. Structure Flutter

Ning 68 Jan 4, 2023
Dart library with stack blur algorithm for RGBA images

stack_blur The Dart library for blurring images with the Stack blur algorithm. T

ArtΡ‘m IG 3 Nov 19, 2022
Postgres-conector - A library for connecting to and querying PostgreSQL databases in Dart.

TODO: Put a short description of the package here that helps potential users know whether this package might be useful for them. Features TODO: List w

null 2 Nov 14, 2021
Ethers: A dart library that connects to interact with the Ethereum blockchain and inspired by ethers.js

Ethers For Flutter Ethers is a dart library that connects to interact with the Ethereum blockchain and inspired by ethers.js. Thanks to web3dart which

Hanggi 12 Oct 30, 2022
Flutter library to create beautiful surveys (aligned with ResearchKit on iOS)

SurveyKit: Create beautiful surveys with Flutter (inspired by iOS ResearchKit Surveys)

QuickBird Studios 90 Dec 28, 2022
Complete Flutter OpenIdConnect Library

OpenIdConnect for Flutter Standards compliant OpenIdConnect library for flutter that supports: Code flow with PKCE (the evolution of implicit flow). T

null 50 Dec 24, 2022
🎞 Flutter media playback, broadcast & recording library for Windows, Linux & macOS. Written in C++ using libVLC & libVLC++. (Both audio & video)

dart_vlc Flutter media playback, broadcast, recording & chromecast library for Windows, Linux & macOS. Written in C++ using libVLC & libVLC++. Install

Hitesh Kumar Saini 417 Dec 29, 2022
Flutter example project to run Solidity smart contracts using web3Dart library

Fluthereum Description Flutter example project to run Solidity smart contracts using web3Dart library Dependencies web3dart: A dart library that conne

Marcos Carlomagno 72 Dec 27, 2022
more code then the original with cupertino library

this version only update flutter cupertino library for crud purpose with backend api this is not stable version yet both side. Youtube for flutter cup

nobody but me 1 Aug 21, 2022