Giter Site home page Giter Site logo

drizzle-react-components-legacy's Introduction

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

drizzle-react-components

A set of useful components for common UI elements.

Components

We provide components that support the React 16.3+ context API and also the legacy context API. The legacy context components will be deprecated in 2.0 with breaking changes to the drizzle-react-components API. We recommend usage of the new context components where possible.

For 1.x.x this is how you import the different components:

React 16.3+ Context Components

import { newContextComponents } from "drizzle-react-components";
const { AccountData, ContractData, ContractForm } = newContextComponents;

LoadingContainer is not provided with the new context components currently. Also note that you must pass in drizzle and drizzleState for each of these components.

Legacy Context Components

import {
  AccountData,
  ContractData,
  ContractForm,
  LoadingContainer
} from "drizzle-react-components";

Refer to the included test apps for usage examples.

LoadingContainer (Legacy only)

This component wraps your entire app (but within the DrizzleProvider) and will show a loading screen until Drizzle, and therefore web3 and your contracts, are initialized.

loadingComp (component) The component displayed while Drizzle initializes.

errorComp (component) The component displayed if Drizzle initialization fails.

AccountData

accountIndex (number, required) Index of account from which to retrieve balance.

units (string) Unit to display either value in. Default is wei. See full list of units here in the web3 documentation.

precision (number) The number of digits after the decimal point to display.

ContractData

contract (string, required) Name of the contract to call.

method (string, required) Method of the contract to call.

methodArgs (array) Arguments for the contract method call. EX: The address for an ERC20 balanceOf() function. The last argument can optionally be an options object with the typical form, gas and gasPrice keys.

hideIndicator (boolean) If true, hides the loading indicator during contract state updates. Useful for things like ERC20 token symbols which do not change.

toUtf8 (boolean) Converts the return value to a UTF-8 string before display.

toAscii (boolean) Converts the return value to an Ascii string before display.

render (function with one argument) Render property, takes the value in the argument and returns render output.

ContractForm

contract (string, required) Name of the contract whose method will be the basis the form.

method (string, required) Method whose inputs will be used to create corresponding form fields.

sendArgs (object) An object specifying options for the transaction to be sent; namely: from, gasPrice, gas and value. Further explanataion of these parameters can be found here in the web3 documentation.

labels (array) Custom labels; will follow ABI input ordering. Useful for friendlier names. For example "_to" becoming "Recipient Address".

render (function) Render prop for rendering custom components. It receives a single object with the fields: inputs, inputTypes, state, handleInputChange, handleSubmit, as arguments and returns render output.

Test Apps

Refer to the test apps to learn more about how to use DRC.

A test app targeting the React 16.3+ context API has been included at ./test-app. And one targeting the legacy context API can be found at test-app-legacy-context.

Installation

  1. cd ./test-app
  2. Install dependencies: npm install
  3. Start your development blockchain: truffle develop
  4. (In Truffle develop console) Compile contracts: compile
  5. (In Truffle develop console) Migrate contracts: migrate
  6. In another terminal window: cd ./app
  7. Install dependencies: npm install
  8. Start dev server: npm start

NOTE: Make sure to migrate --reset your contracts and reset your Metamask account when switching between test apps, otherwise errors may occur.

drizzle-react-components-legacy's People

Contributors

adrianmcli avatar dannycarrera avatar doc-failure avatar honestbonsai avatar igorline avatar maxme avatar mnaamani avatar mwaeckerlin avatar onlyonejmjq avatar prophetdaniel avatar samajammin avatar sdtsui avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

drizzle-react-components-legacy's Issues

Discussion: Usage with new Consumer API

Hiya,
this is not really an issue but I started refactoring the react-components to be used via the context.consumer pattern ( and to work with react-native and web if possible ).

My experience was fun but a bit strange so I wanted to share, cause it does feel a bit weird to me.
I came up with the following to call contract methods for example:

Usage Example:

class Story extends React.Component {
  private walletContract = React.createRef()

  render(){
    return (
      <DrizzleContext.Provider drizzle={storeDrizzle()}>
      
        {/* I feel weird using the component as API using a ref */}
        <ContractSend contractName={'Wallet'} ref={this.walletContract}/> 

        <button onClick={ () => this.walletContract.current.send('deposit', {amount: 10}) }>Deposit</button> 
        <button onClick={ () => this.walletContract.current.send('withdraw', {amount: 10}) }>Withdraw</button> 

      </DrizzleContext.Provider>
    )
  }
}

Implementation:
https://gist.github.com/soundyogi/8eac4a67b820e6ea2f9635301fd2fa66

Problems:
I could not get it to work packages as a library, which is proibably due to how ReactContext works (not the same context), or due to the packaging with webpack.

How are you using drizzle via the new consumer pattern?
Cheers.

ContractData does not update when it's props change

I would expect ContractData component to update it's content when one of it's props value is changed. Instead it remains fixed with data it received on application load.

I submitted a pull request that solved the issue for me.

ContractForm should be able to send value for interaction with payable methods

A common use case to is to send Eth to a contract for example wrapped-eth (https://weth.io/).

Currently this will not work as the deposit method is a payable with no arguments and the methodArgs does not exist for this component.

<ContractForm contract="WrappedEth" method="deposit" methodArgs={[{value: 1000000}]}/>

The preferred implementation would probably be to display an input field when a payable method is detected.

ContractData: does not work for mappings

When wanting to display a contracts mapping, such as
mapping (uint => bool) public isCoolNumber;

with
ContractData contract="SimpleStorage" method="cool" methodArgs={[8]}

i get
utils.js:240 uncaught at l TypeError: e.slice is not a function

I tried this by adjusting the drizzle-box.

ContractForm: bool types are not rendered with labels.

Some contracts have boolean types in their method signatures.

For example:

contract MyContract {
    function doSomething(string name, bool isGood, bool isBad) public {
        // do something here
    }
}

When these methods are rendered in a ContractForm, the bool types render as follows:

<ContractForm contract="MyContract" method="doSomething"
                labels={['Name', 'Is Good', 'Is Bad']} />

becomes

<input name="name" value="" placeholder="Name" type="text">
<input name="isGood" value="" placeholder="Is Good" type="checkbox">
<input name="isGood" value="" placeholder="Is Bad" type="checkbox">

When this renders in a browser, the checkbox inputs do not have labels, meaning the user does not know the meaning of the check boxes.

ContractData: Not updating on change

<ContractData contract="ERC223StandardToken" method="balanceOf" methodArgs={[this.props.accounts[0],{from: this.props.accounts[0]}]} />

<Faucet contract="ERC223StandardToken" method="faucet" />

Faucet function signs transaction, updating user balance with 200 tokens. ContractData component displays out of sync icon but does not update to new balance, refreshing page, ContractData displays correct data

Nightly Development Builds

Please add a nightly npm-release for the latest drizzle develop branch.

Reasons:

  • It would be handy for developers to be able to rely on the latest features, without having to clone and build the project on their own.
  • The current latest release, 1.3.1, is very outdated: no «new» interface, non-working arrays, missing render props

BTW: It would be time for a new release. The current deveopment version runs stable AFAIK. The only reason I see, what would need to be fixed before a release, would be some warnings that need to be eliminated first, see #90.

Variable value?

I'd like for the user to be able to define how much ETH they want to send for the contract, in return for tokens. So they should be able to send ether .001 ETH or 1 ETH depending on how many tokens they want. The component though seems to require me to hardcode the value parameter. Is there a way to make the value parameter end-user defined?

<ContractForm contract="MyCrowdsale"
method="buyTokens"
labels={['To Address']} sendArgs={{
from: '0x....',
value: '20000'
}} />

Add eslint and prettier

I've noticed some PRs include prettification, which makes it tough to see what actually changed. We should use a common set of rules to align this repo around.

npm link not working

So when trying to develop with a test repo and npm link drizzle-react-components it always says

Module not found: Can't resolve 'drizzle-react' in '/Users/hl/development/drizzle-react-components/dist'

If I just use the original nonlinked DRC in node_modules, modify the src and rebuild, it works fine.

ContractData: Address Array is not shown

I just use this code, but I can't show address type data list...

import React, {Component} from 'react'
import { AccountData, ContractData, ContractForm} from 'drizzle-react-components'

class Home extends Component {
    render() {
        return (
            <main className="container">
                        ...
                        <h2>VoteFactory</h2>

                        <strong>현재 생성된 투표 개수</strong>:
                        <ContractData contract="VoteFactory" method="getDeployedVotesLength"/>

                        <br/><br/>

                        <strong>현재 생성된 투표 목록</strong>:
                        <ContractData contract="VoteFactory" method="getDeployedVotes" />
                        ...
            </main>
        )
    }
}

export default Home

And My contract Code is here:

    function getDeployedVotes() external view returns (address[]) {
        return deployedVotes;
    }

    function getDeployedVotesLength() external view returns (uint) {
        return deployedVotes.length;
    }

This is result page:
result page

Contract codes already success Compile and Migration,
I also used properties of toUtf8, toAscii, It is not working.
How can I solve this?

ContractForm: bool types (checkboxes) do not set value

I had a form input that included a boolean argument (isAdmin):

<ContractForm
  contract="SimpleDemocracy"
  method="registerVoter"
  labels={['Address', 'isAdmin']}
/>

Contract code:

function registerVoter(address voter, bool _isAdmin) public isAdmin() {
    require(getRegistration(voter) == false, "Voter already registered.");
    voters[voter] = Voter({ hasRegistered: true, isAdmin: _isAdmin});
}

Regardless of if the isAdmin checkbox was checked or not, the record would save as false. Logging this.state in handleSubmit() of ContractForm.js revealed that my isAdmin value was always being set to an empty string.

PR fix coming...

context.drizzle.contracts async issue

Basically, this line
// Get the contract ABI const abi = this.contracts[this.props.contract].abi; fails because this.contracts is empty at refreshing the page, the info comes later.

Compatibility issue with the new drizzle Context API (DrizzleContext) ?

Could you please tell me if the components < AccountData > , < ContractData > , < ContractForm > works using the new drizzle Context API (DrizzleContext.provider) ? I am visualizing the problem in the following avenue:

inside the AccountData.js, there is a drizzleConnect() function being called to mapStateToProps. This is exactly from where the "Accounts" data is being retrieved as props (this.props.Accounts). But if we go further deeper, inside the drizzleConnect.js, we encounter the following line:

<ConnectedWrappedComponent {...props} store={context.drizzleStore} />

This means there is a context call of context.drizzleStore which is non existent (recall in the new DrizzleContext.provider, the context object is {drizzle, drizzleState, initialized}, no drizzleStore). Hence this should technically throw an error of not finding the store variable in either context or props.

One probable way of fixing this would be to get the "store" value in directly from context.drizzle (context.drizzle.store) , instead of context.drizzleStore.

Could you please clarify if this is not the case? much obliged.

Flexibility in Formatting

I have seen here many questions, requests (e.g. #69, #71) and one idea (#70) on how drizzle-react-component could be made more flexible. Here is my suggestion:

Problems

  • there is no way to configure the rendering of the values (except suggestion in #70)
  • arrays are mapped to unordered lists, there no way to change this (except suggestion in #70)
  • there is no way to render the target contract in an array of addresses to contracts
  • there is no way to render arrays complex structures
  • same for maps
  • there is no way to specify the range in forms
  • there is no way to select the element for an input (e.g. <textarea> vs <input type="text">) or even <TextField> from @material-ui (not even solved in #70)
  • there is now way to specify dependencies between input fields in forms

In short terms: drizzle-react-component is nice for some small tutorial examples, but far away from a production ready library. But I like the basic concepts and simplicity of the approach.

Idea

In #70, @macsj200 suggests to add a property customComponent this solves configurability for simple rendering, but not in complex cases, such as for arrays and maps.

I suggest a different approach: Allow nested components inside ContractData and ContractForm, these are then used to render the content.

This is just a simple pseudo code to show how I see the solution:


  return (
    <>
      <h1>
         <ContractData contract="Mapping" method="something">
           <MyRender>{this.props.displayData}</MyRender>
         </contractData>
      </h1>
      <ul>
        <ContractData contract=Mapping" method="values" foreach="key => val">
          <li>
            <h2><ContractData contract="Value" instance="val" method="name" /></h2>
            <p><ContractData contract="Value" instance="val" method="text" /></p>
            <ul>
              <ContractData contract="Value" instance="val" method="data" foreach="dataItem">
                <li><ContractData contract="Value" instance="val" method="data" methodArgs="[dataItem]" /></li>
              </ContractData>
            </ul>
          </li>
        </ContractData>
      </ul>
    </>
  )
}

ToDo

I forked the project to https://github.com/mwaeckerlin/drizzle-react-components. I will now try to implement step by step a solution for the principle above.

Please add your comments, what do you think about this approach?
@honestbonsai, would you be willing to accept such a change?
@macsj200, would you accept this more flexible solution in favour of your suggestion in #70?

Configurable Form in ContractForm.js

Allow ContractForms to delegate rendering of the form details, similar to #81. A user should have the possibility to render the form according to his needs.

Currently:

  • there is no way to specify the range in forms
  • there is no way to select the element for an input (e.g. <textarea> vs <input type="text">) or even <TextField> from @material-ui
  • there is now way to specify dependencies between input fields in forms

Probably a render prop could solve most if not all of these requirements.

ContractForm does not work correctly with Bool type method argument

I am calling vote method in Contract Form

<ContractForm contract="LCSToken" method="vote" labels={['NFT Token ID','Positive?']} />

and the second argument always receive FALSE as a value, so the voting result is negative
There is my contract method :

 function vote(uint256 _id, bool _positive) public {
        require(_id != uint256(0));
        require(_id == voters[msg.sender]);
        require(extensions[_id].status == uint8(Status.Claim));
        Request storage _request = requests[_id];
        uint votingEnd = _request.timeStamp + _request.duration;
        require(votingEnd >= now);

        if(_positive) {
            _request.positive++;
        } else {
            _request.negative++;
        }
        delete voters[msg.sender]; // deliting prevent the second time voting
        // emit event
        Vote(msg.sender, _id, _positive);
    }

Should ContractForm also have methodArgs()

I'm trying to make a secondary hd account call to ContractForm but only ContractData takes methodArgs().

Is there some reason why ContractForm shouldn't have arguments also or is there another way to send the transaction from a secondary account.

Customization

I'm quite impressed with how easy it is to use this package to read and write values from a smart contract. That being said, the default view that the component provides isn't what I'm looking for.

Is there any way to customize the output of <ContractData>?

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

Release 1.4

  • Point test apps to DRC 1.4
  • Bump version
  • Prep release notes

Release 1.3

  1. Decide when to release
  2. Make release notes
  3. Tag
  4. Link Github to npm page
  5. Move to gitflow by setting develop as main branch, master should reflect what's out in production
  6. Publish to npm

Render Dynamic Contracts

Render contracs that are dynamically instanciated using an address and an ABI, i.e. render the target contract in an array of addresses to contracts. Perhaps this will need a new class, sich as DynamicContract.js.

Warnings in Develoment Branch; Failed prop type

There are some Warnings in the development branch that should be eliminated:

Warning: Failed prop type: Invalid prop accounts of type object supplied to LoadingContainer, expected an array.
in LoadingContainer

Warning: Failed prop type: Invalid prop contracts of type object supplied to ContractData, expected array.
in ContractData

ContractForm: Argument ordering of cacheSend in handleSubmit is arbitrary

When submitting the form, the ordering of arguments to cacheSend method:

method.cacheSend(...Object.values(this.state))

...are not guaranteed to be in the correct order:

Object.values iterates over the state keys in the same order as for...in which iterates over the properties of an object in an arbitrary order

The only case where this implementation is bug free is in the case that less than two arguments are expected by the contract method.

We need a custom method to generate the arguments in correct order.

Add test app

It's getting really tiring to use external test projects. Should just bundle an example with this repo.

Would also be a nice (manual) test suite to make sure all our features are working.

Trouble sendArgs with transfer method

Hello i'm looking to make a transfert with adress and value setup, in order to just click on a button for the user to buy something with token.

I use a ContractForm, working well if adresse and value set by user, but sendArgs is not working.
Here is my form :

              <ContractForm
                contract="Influence"
                method="transfer"
                methodArgs={{to: "0xbd85593F294f953dC67dBDd4C34Ff7cd8681156A", value: 5}}
              />

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.