• This repository has been archived on 27/Sep/2019
  • Stars
    star
    503
  • Rank 87,705 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 7 years ago
  • Updated about 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Reactive Ethereum datastore for dapp UIs.

DEPRECATION NOTICE This repository has been deprecated in favor of: https://github.com/trufflesuite/drizzle

Drizzle Logo

drizzle

npm install --save drizzle

Drizzle is a collection of front-end libraries that make writing dapp frontends easier and more predictable. The core of Drizzle is based on a Redux store, so you have access to the spectacular development tools around Redux. We take care of synchronizing your contract data, transaction data and more. Things stay fast because you declare what to keep in sync.

  • Fully reactive contract data, including state, events and transactions.
  • Declarative, so you're not wasting valuable cycles on uneeded data.
  • Maintains access to underlying functionality. Web3 and your contract's methods are still there, untouched.

Using React?: The easiest way to get started with Drizzle is to use our official drizzle-react package and (optionally) its companion drizzle-react-components.

Getting Started

Note: Since Drizzle uses web3 1.0 and web sockets, be sure your development environment can support these.

  1. Import the provider.

    import { Drizzle } from 'drizzle'
  2. Create an options object and pass in the desired contract artifacts for Drizzle to instantiate. Other options are available, see the Options section below.

    // Import contracts
    import SimpleStorage from './../build/contracts/SimpleStorage.json'
    import TutorialToken from './../build/contracts/TutorialToken.json'
    
    const options = {
      contracts: [
        SimpleStorage
      ]
    }
    
    const drizzle = new Drizzle(options)

    Note: The above assumes you have no existing redux store and will generate a new one. If you need something more sophisticated, consult our documentation Using Drizzle's Redux Store

  3. Get contract data. Calling the cacheCall() function on a contract will execute the desired call and return a corresponding key so the data can be retrieved from the store. When a new block is received, Drizzle will refresh the store automatically if any transactions in the block touched our contract. For more information on how this works, see How Data Stays Fresh.

    Note: We have to check that Drizzle is initialized before fetching data. A simple if statement such as below is fine for displaying a few pieces of data, but a better approach for larger dapps is to use a loading component. We've already built one for you in our drizzle-react-components library as well.

    // Assuming we're observing the store for changes.
    var state = drizzle.store.getState()
    
    // If Drizzle is initialized (and therefore web3, accounts and contracts), continue.
    if (state.drizzleStatus.initialized) {
     // Declare this call to be cached and synchronized. We'll receive the store key for recall.
     const dataKey = drizzle.contracts.SimpleStorage.methods.storedData.cacheCall()
    
     // Use the dataKey to display data from the store.
     return state.contracts.SimpleStorage.storedData[dataKey].value
    }
    
    // If Drizzle isn't initialized, display some loading indication.
    return 'Loading...'

    The contract instance has all of its standard web3 properties and methods. For example, you could still call as normal if you don't want something in the store:

    drizzle.contracts.SimpleStorage.methods.storedData().call()
  4. Send a contract transaction. Calling the cacheSend() function on a contract will send the desired transaction and return a corresponding transaction hash so the status can be retrieved from the store. The last argument can optionally be an options object with the typical from, gas and gasPrice keys. Drizzle will update the transaction's state in the store (pending, success, error) and store the transaction receipt. For more information on how this works, see How Data Stays Fresh.

    Note: We have to check that Drizzle is initialized before fetching data. A simple if statement such as below is fine for displaying a few pieces of data, but a better approach for larger dapps is to use a loading component. We've already built one for you in our drizzle-react-components library as well.

    // Assuming we're observing the store for changes.
    var state = drizzle.store.getState()
    
    // If Drizzle is initialized (and therefore web3, accounts and contracts), continue.
    if (state.drizzleStatus.initialized) {
     // Declare this transaction to be observed. We'll receive the stackId for reference.
     const stackId = drizzle.contracts.SimpleStorage.methods.set.cacheSend(2, {from: '0x3f...'})
    
     // Use the dataKey to display the transaction status.
     if (state.transactionStack[stackId]) {
       const txHash = state.transactionStack[stackId]
    
       return state.transactions[txHash].status
     }
    }
    
    // If Drizzle isn't initialized, display some loading indication.
    return 'Loading...'

    For more information on what's contained in transaction state, see Drizzle State.

    The contract instance has all of its standard web3 properties and methods. For example, you could still send as normal if you don't want a tx in the store:

    drizzle.contracts.SimpleStorage.methods.set(2).send({from: '0x3f...'})

Adding contracts dynamically

You can programmatically add contracts to Drizzle using either drizzle.addContract() or the ADD_CONTRACT action.

var contractConfig = {
  contractName: "0x066408929e8d5Ed161e9cAA1876b60e1fBB5DB75",
  web3Contract: new web3.eth.Contract(/* ... */)
}
events = ['Mint']

// Using an action
dispatch({type: 'ADD_CONTRACT', drizzle, contractConfig, events, web3})

// Or using the Drizzle context object
this.context.drizzle.addContract(contractConfig, events)

Deleting contracts

You can also delete contracts using either drizzle.deleteContract() or the DELETE_CONTRACT action.

const contractName = "MyContract"

// Using an action
dispatch({type: 'DELETE_CONTRACT', drizzle, contractName})

// Or using the Drizzle context object
this.context.drizzle.deleteContract(contractName)

Options

Drizzle has a number of configuration options so it only keeps track of exactly the data you need. Here's the full list of options along with their default values.

{
  contracts,
  events: {
    contractName: [
      eventName,
      {
        eventName,
        eventOptions
      }
    ]
  },
  polls: {
    accounts: interval,
    blocks: interval
  },
  syncAlways,
  web3: {
    customProvider,
    fallback: {
      type
      url
    }
  },
  networkWhitelist
}

contracts (array)

An array of either contract artifact files or Web3 contract objects. The objects have a contractName and web3Contract key.

i.e.

contracts: [
  truffleArtifact, // A regular Truffle contract artifact
  {
    contractName: 'RegisteredContract',
    web3Contract: new web3.eth.Contract(abi, address, {data: 'deployedBytecode' }) // An instance of a Web3 contract
  }
]

events (object)

An object consisting of contract names each containing an array of strings of the event names we'd like to listen for and sync with the store. Furthermore, event names may be replaced with an object containing both eventName and eventOptions, where eventOptions field corresponds to the web3 Contract.events options.

polls (object)

An object containing key/value pairs denoting what is being polled and the interval (in ms). Possible polls are accounts and blocks. Accounts will poll for addresses and balances, blocks for new blocks. Default: { blocks: 3000 }

syncAlways (boolean)

If true, will replay all contract calls at every block. This is useful if your dapp uses a proxy contract which obfuscates your primary contract's address. By default Drizzle checks blocks to see if a transaction interacting with your contracts has occured. If so, it syncs that contract. Default: false

web3 (object)

Options regarding web3 instantiation.

customProvider (object)

A valid web3 provider object. For example, you may wish to programatically create a Ganache provider for testing:

// Create a Ganache provider.
const testingProvider = Ganache.provider({
  gasLimit: 7000000
})

const options = {
  web3: {
    customProvider: testingProvider
  }
}

const drizzle = new Drizzle(options)

fallback (object)

An object consisting of the type and url of a fallback web3 provider. This is used if no injected provider, such as MetaMask or Mist, is detected.

type (string): The type of the fallback web3 provider. Currently the only possibility is 'ws' (web socket). Default: 'ws'

url (string): The full fallback web3 provider url. Default: 'ws://127.0.0.1:8545'

networkWhitelist (array)

An array of valid network ids for your project. Your smart contracts might only be deployed on particular networks, or you might want to restrict access on networks that are under development.

Allows all networks by default. Ganache bypasses this check and is never restricted.

// Allows the listed networks, plus Ganache
const options = {
  networkWhitelist: [
    1, // Mainnet
    3, // Ropsten
    4, // Rinkeby
    5, // Goerli
    42 // Kovan
  ]
}

Drizzle State

{
  accounts,
  accountBalances: {
    address
  }
  contracts: {
    contractName: {
      initialized,
      synced,
      events,
      callerFunctionName: {
        argsHash: {
          args,
          value
        }
      }
    }
  },
  currentBlock,
  drizzleStatus: {
    initialized
  },
  transactions: {
    txHash: {
      confirmations,
      error,
      receipt,
      status
    }
  },
  transactionStack,
  web3: {
    status
  }
}

accounts (array)

An array of account addresses from web3.

accountBalances (object)

An object whose keys are account addresses and values are account balances (in Wei).

contracts (object)

A series of contract state objects, indexed by the contract name as declared in its ABI.

contractName (object)

initialized (boolean): true once contract is fully instantiated. synced (boolean): false if contract state changes have occurred in a block and Drizzle is re-running its calls.

events (array): An array of event objects. Drizzle will only listen for the events we declared in options.

The contract's state also includes the state of each constant function called on the contract (callerFunctionName). The functions are indexed by name, and contain the outputs indexed by a hash of the arguments passed during the call (argsHash). If no arguments were passed, the hash is 0x0. Drizzle reads from the store for you, so it should be unnecessary to touch this data cache manually.

args (array): Arguments passed to function call. value (mixed): Value returned from function call.

currentBlock (object)

An object the latest block as an object resulting from web3.getBlock(). This is updated once the block is received from a subscription or fetched via polling, but before any processing takes place.

drizzleStatus (object)

An object containing information about the status of Drizzle.

initialized (boolean): true once:

  • web3 is found or instantiated
  • Account addresses are stored in state
  • All contracts are instantiated

initialized (boolean)

false by default, becomes true once a web3 instance is found and the accounts and contracts are fetched.

transactions (object)

A series of transaction objects, indexed by transaction hash.

txHash (object)

confirmations (array): After the initial receipt, further confirmation receipts (up to the 24th). error (object): contains the returned error if any. receipt (object): contains the first transaction receipt received from a transaction's success event.

status (string): true or false depending on transaction status

  • pending when the transaction has broadcasted successfully, but is not yet mined
  • success when a transaction receipt has been received (you may also wish to check for further confirmations)
  • error if any errors occurred after broadcasting

For more in-depth information on the Ethereum transaction lifecycle, check out this great blog post.

transactionStack (array)

In cases where a user cancels a transaction or the transaction is malformed and unable to be broadcasted, it won't receive a hash. To keep track of these cases, a temporary ID will be added to this array and replaced with the transaction hash once broadcasted. The cacheSend() method will return a stackId, which will allow you get the temporary ID to observe this process for your own transaction status indicator UI.

web3 (object)

status (string): initializing, initialized and failed are possible options. Useful for triggering warnings if web3 fails to instantiate.

How Data Stays Fresh

  1. Once initialized, Drizzle instantiates web3 and our desired contracts, then observes the chain by subscribing to new block headers.

    Drizzle Sync Step 1

  2. Drizzle keeps track of contract calls so it knows what to synchronize.

    Drizzle Sync Step 2

  3. When a new block header comes in, Drizzle checks that the block isn't pending, then goes through the transactions looking to see if any of them touched our contracts.

    Drizzle Sync Step 3

  4. If they did, we replay the calls already in the store to refresh any potentially altered data. If they didn't we continue with the store data.

    Drizzle Sync Step 4

License

MIT

More Repositories

1

truffle

⚠️ The Truffle Suite is being sunset. For information on ongoing support, migration options and FAQs, visit the Consensys blog. Thank you for all the support over the years.
TypeScript
14,021
star
2

ganache-ui

Personal blockchain for Ethereum development
JavaScript
4,647
star
3

ganache-cli-archive

Fast Ethereum RPC client for testing and development. See https://github.com/trufflesuite/ganache for current development.
JavaScript
3,360
star
4

ganache

⚠️ The Truffle Suite is being sunset. For information on ongoing support, migration options and FAQs, visit the Consensys blog. Thank you for all the support over the years.
TypeScript
2,618
star
5

drizzle

Reactive Ethereum dapp UI suite
JavaScript
906
star
6

truffle-hdwallet-provider

HD Wallet-enabled Web3 provider
JavaScript
401
star
7

truffle-artifactor

A contract packager for Ethereum and Javascript (formerly ether-pudding)
JavaScript
254
star
8

trufflesuite.com

Trufflesuite website source ✨
HTML
182
star
9

drizzle-react-legacy

JavaScript
176
star
10

drizzle-react-components-legacy

A set of useful components for common dapp UI elements.
JavaScript
96
star
11

truffle-core

Core code for Truffle command line tool
JavaScript
93
star
12

truffle-debugger

Core functionality for debugging Solidity files built with Truffle
JavaScript
67
star
13

drizzle-utils

A library for interacting with Ethereum smart contracts based on RxJS streams.
JavaScript
43
star
14

vscode-ext

Truffle for VSCode simplifies how you create, build, debug and deploy smart contracts on Ethereum and EVM-compatible blockchains
TypeScript
38
star
15

trufflesuite.github.io

Staging Repo of Build Artifacts for Truffle Suite. Find the source at https://github.com/trufflesuite/trufflesuite.com
HTML
34
star
16

ethpm-js

Javascript library for publishing and consuming Ethereum packages.
JavaScript
34
star
17

truffle-plugin-debugger

Debug all the things!
TypeScript
30
star
18

truffle-logger-example

Console.log example for Solidity inside Truffle projects
JavaScript
29
star
19

truffle-contract-schema

JSON schema for contract artifacts
JavaScript
25
star
20

truffle-compile

Compiler helper and artifact manager
JavaScript
22
star
21

truffle-init-default

Default project for Truffle: example contracts, migrations and tests
JavaScript
21
star
22

drizzle-vue-plugin

Connect Vue to Drizzle
JavaScript
19
star
23

pet-shop-tutorial

Solution for the Pet Shop tutorial
JavaScript
18
star
24

truffle-default-builder

Default build process for truffle dapps
JavaScript
18
star
25

truffle-migrate

On-chain migrations management
JavaScript
17
star
26

swirl

Make curl easier with ethereum bash completions.
Shell
15
star
27

webinar-episode-01

Code to go along with our webinars
JavaScript
15
star
28

truffle-deployer

Light deployment module for deploying Ethereum contracts
JavaScript
14
star
29

truffle-teams

Continuous Integration for your Truffle Project
13
star
30

ts-lxd

A client for LXD, written in TypeScript
TypeScript
12
star
31

solidity-magic-square

Demo project for testing debugging features
Solidity
11
star
32

unleashed

JavaScript
10
star
33

unleashed_nft_rental_marketplace

JavaScript
10
star
34

truffle-solidity-utils

Utilities for solidity contracts
JavaScript
9
star
35

truffle-blockchain-utils

Utilities for identifying and managing blockchains
JavaScript
9
star
36

unleashed_royalty_standard

JavaScript
8
star
37

dotfiles

Shell
8
star
38

drizzle-event-demo

Using drizzle events
JavaScript
8
star
39

dashboard

JavaScript
8
star
40

artifact-updates

Working Repository for requirements / design of for general-purpose artifacts format
Shell
8
star
41

truffle-provider

Beefed up Provider utility for Truffle
JavaScript
7
star
42

truffle-box

Truffle project boilerplate management
JavaScript
7
star
43

ethpm-registry

Create a new epm-registry on-chain.
JavaScript
7
star
44

truffle-require

Executed a Javascript module within a Truffle context
JavaScript
7
star
45

devcon5-pentesting-ethereum-contracts-with-ganache

https://trfl.co/devcon5
JavaScript
7
star
46

webinar-truffle-badge

Truffle-themed ERC721 (using OpenZeppelin) for exploring the development lifecycle
JavaScript
6
star
47

ci

Truffle Suite continuous integration config
Shell
6
star
48

reselect-tree

Abstraction around reactjs's `reselect`to define trees of selectors
JavaScript
5
star
49

truffle-config

Utility for interacting with truffle.js files
JavaScript
5
star
50

unleashed_rentable_nft

ERC-4907 implementation for Web3 Unleashed Episode 2
JavaScript
5
star
51

solidity-rock-paper-scissors

JavaScript
5
star
52

txlog-to-plantuml

JavaScript
5
star
53

react-eth-tx-params

A component for displaying ethereum tx params
JavaScript
5
star
54

gas-exactimation-tutorial

Solution for the Gas Exactimation tutorial
JavaScript
4
star
55

truffle-checkout

Used to checkout specific versions of Truffle and associated modules for the purposes of development
JavaScript
4
star
56

ganache-filecoin-alpha-cli

Alpha CLI for Ganache's Filecoin integration. Will be replaced by ganache-cli once integration is stable.
JavaScript
4
star
57

trufflecon-block-contender

Demo app for TruffleCon 2019 Gas Estimation and Optimization Workshop
JavaScript
4
star
58

trufflevsix

Visual Studio Extension for Truffle
C#
4
star
59

truffle-init

Initializer for example Truffle projects
JavaScript
3
star
60

wild-truffle

Truffle cores running on large public Truffle projects.
Shell
3
star
61

truffle-contract-sources

Utility for finding all contracts within a directory
JavaScript
3
star
62

truffle-init-bare

Barebones Truffle project
JavaScript
3
star
63

truffle-code-utils

Utilities for parsing EVM bytecode
JavaScript
3
star
64

unleashed_upgrade_contract

JavaScript
3
star
65

vscode-ext-scaffold

JavaScript
3
star
66

the-bet

Truffle project to look to an external service to determine who wins a contract. Used with an upcoming Truffle video.
JavaScript
3
star
67

truffle-resolver

Resolve contract dependencies given multiple configurable dependency sources
JavaScript
3
star
68

useful-internal-notes

Useful notes on Ethereum, Solidity, Vyper, etc
Solidity
2
star
69

solidity-test-cases

Various helpful solidity test cases
Solidity
2
star
70

truffle-provisioner

Provision contract objects for use from multiple sources
JavaScript
2
star
71

vscode-truffle-debugger

TypeScript
2
star
72

SmartPyBasic-Docker

Dockerized command-line version of SmartPy, a Python library for Tezos smart contract development.
Dockerfile
2
star
73

fetch-and-compile-server

TypeScript
2
star
74

declarative-deployments

Collaborative space to work on getting declarative deployments working!
TypeScript
2
star
75

metacoin-playground

A metacoin repo used internally by Truffle Suite
JavaScript
2
star
76

truffle-expect

Simple module for ensuring expected parameters exist
JavaScript
2
star
77

teams-stress

Stress out the Truffle Teams debugger
Solidity
2
star
78

truffle-workflow-compile

Core workflow logic for the `truffle compile` command behavior
JavaScript
2
star
79

ttt-contracts

Smart contracts for the Unity + Consensys Web3 Tic Tac Toe game.
JavaScript
1
star
80

truffle-error

Simple module that allows native Error objects to be extended
JavaScript
1
star
81

ganache-flavors

1
star
82

truffle-debug-utils

Code for integration between Truffle and Truffle Debugger
JavaScript
1
star
83

quorum-tutorial

Solution for the Quorum tutorial
JavaScript
1
star
84

unleashed_optimism_bridge

The tutorial for this repo lives [here](www.trufflesuite.com/guides/optimism-bridge-widget)
JavaScript
1
star
85

txlog-seedlings

Truffle contracts suitable for planting
JavaScript
1
star
86

CaptureTheFlag

JavaScript
1
star
87

unity-plugin

C#
1
star
88

jstezos

1
star
89

preserves

Truffle preserve framework monorepo
TypeScript
1
star
90

clairvoyance

HTML
1
star