GithubHelp home page GithubHelp logo

snapshot-labs / snapshot.js Goto Github PK

View Code? Open in Web Editor NEW
219.0 10.0 571.0 4 MB

A TypeScript SDK for Snapshot

Home Page: https://docs.snapshot.org/snapshot.js

License: MIT License

JavaScript 34.08% TypeScript 64.28% HTML 1.64%

snapshot.js's People

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  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

snapshot.js's Issues

Error "Property 'SNAPSHOT_SUBGRAPH_URL' does not exist on type"

Expected behavior

Actual behavior

When running tests, there seems to be a broken piece of code related to SNAPSHOT_SUBGRAPH_URL missing

Projects/snapshot-strategies 22:59 > yarn test
yarn run v1.22.17
$ npm run build

@snapshot-labs/[email protected] build
tsc -p .

src/utils.ts:44:3 - error TS2339: Property 'SNAPSHOT_SUBGRAPH_URL' does not exist on type '{ call: (provider: any, abi: any[], call: any[], options?: any) => Promise; multicall: (network: string, provider: any, abi: any[], calls: any[], options?: any) => Promise; ... 18 more ...; verify: (address: any, sig: any, data: any) => Promise<...>; }'.

44 SNAPSHOT_SUBGRAPH_URL
~~~~~~~~~~~~~~~~~~~~~

Found 1 error.

error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Projects/snapshot-strategies 23:05 >

Steps to reproduce the behavior

yarn test

daoModule: TS2783: 'nonce' is specified more than once

I'm getting these typscript errors with the daoModule, and it's also started to throw in the frontend build:

ERROR in node_modules/@snapshot-labs/snapshot.js/src/plugins/daoModule/index.ts:205:9
TS2783: 'nonce' is specified more than once, so this usage will be overwritten.
    203 |     return transactions.map((tx) => {
    204 |       const txHash = _TypedDataEncoder.hash(domain, EIP712_TYPES, {
  > 205 |         nonce: '0',
        |         ^^^^^^^^^^
    206 |         data: '0x',
    207 |         ...tx
    208 |       });

ERROR in node_modules/@snapshot-labs/snapshot.js/src/plugins/daoModule/index.ts:206:9
TS2783: 'data' is specified more than once, so this usage will be overwritten.
    204 |       const txHash = _TypedDataEncoder.hash(domain, EIP712_TYPES, {
    205 |         nonce: '0',
  > 206 |         data: '0x',
        |         ^^^^^^^^^^
    207 |         ...tx
    208 |       });
    209 |       return txHash;

I don't understand why this error is occurring, @rmeissner any ideas how to fix it?

Add 3Box profile integration to the Snapshot app

Prize: 500 DAI

Requirements

1. Add profile in the top nav

Preview

Description

Once the user login, we should request the avatar url and the name of the user from 3Box and display it in the top nav. This data should be loaded on user login and stored on the app store in the web3 module.

Related files

https://github.com/balancer-labs/snapshot/blob/develop/src/store/modules/web3.ts
https://github.com/balancer-labs/snapshot/blob/develop/src/components/Topnav.vue.

2. Add profile and button in account modal

Preview

Description

The name and the avatar of the logged user should appear in the account modal if available along with a button "Edit profile on 3Box". If the profile is not available there should be a button "Create profile on 3Box" instead.

Related file

https://github.com/balancer-labs/snapshot/blob/develop/src/components/Modal/Account.vue.

3. Add names and avatars of the voters

Preview

Description

The names and avatars should be query with a single request. The request must be sent in same time than the action "getProposal".

Related files

https://github.com/balancer-labs/snapshot/blob/develop/src/store/modules/app.ts#L152
https://github.com/balancer-labs/snapshot/blob/develop/src/components/Block/Votes.vue

4. Add name and avatar of the proposal author

Preview

Description

The name and avatar of the proposal author should be loaded within the same request to get the voters profiles.

5. Add profile in user modal

Preview

Description

The name and avatar should appear when open a user modal along with a button "View profile on 3Box". If the user don't have a profile the button to view profile should not appear.

Related file

https://github.com/balancer-labs/snapshot/blob/develop/src/components/Modal/User.vue

GraphQL: Cannot get score when proposal is open

Expected behavior

Retrieve proposal score from graphQL query

Actual behavior

Not retrieving score from graphQL query

Steps to reproduce the behavior

query Proposal {
  proposal(id: "0xb7356adb5ee9f59aeaa97b6af2d69ac0d6d4628f8a40303c433d1474e0064914") {
    id
    votes
    snapshot
    scores
    scores_state
    scores_updated
    scores_by_strategy
  }
}

returns

{
  "data": {
    "proposal": {
      "id": "0xb7356adb5ee9f59aeaa97b6af2d69ac0d6d4628f8a40303c433d1474e0064914",
      "votes": 0,
      "snapshot": "13791875",
      "scores": [],
      "scores_state": "",
      "scores_updated": 0,
      "scores_by_strategy": []
    }
  }
}

But the website is showing
snapshot

I also tried to get voters addresses from graphql query
then call getScore method
which is returning 262.86 and not 720.16

I'm trying to get the 720.16 from code, how do i do that ?

Thanks a lot !

Spaces are limited to five strategies

Expected behavior

Spaces should be allowed to add more than five snapshot strategies.

Actual behavior

Five strategies are the limit, as defined in src/schemas/space.json

Steps to reproduce the behavior

Attempt to add greater than five strategies to a snapshot space

Notes

The Index Coop is planning to add additional strategies to our space to better represent our token holders. At the moment, we use four strategies but intend to add an additional three strategies once we migrate to ENS. I have considered writing a custom strategy that wraps multiple strategies together, but it would be significantly simpler if we could bump the maximum allowed strategies from 5 to 10 to accommodate our needs.

Bug Bounty strategy request

Request description
Add/Modify Snapshot strategy for UBXT governance at the URL: https://snapshot.org/#/ubxt.eth

Details
Currently our snapshot voting strategy allows anyone holding UBXT in their wallet on ETH or BSC to vote. This needs to be advanced so that our snapshot strategy also enables users in our staking pool to vote.

This requires creating a custom strategy that checks two things.

  1. If the wallet has UBXT currently staked in our BSC or ETH staking pool.
  2. If the wallet has UBXT LP currently staked in our BSC or ETH staking pool.

Our staking pool contract has functions for staking UBXT and UBXT LP and we have two contracts one for ETH and one for BSC.
So the strategy just needs to check both the ETH and the BSC staking pools to see if the user has UBXT or UBXT LP staked in the pool. If the user is staking LP the contract should calculate how much UBXT is locked in the UBXT LP tokens they have and count this UBXT in their vote.

Notes
1 UBXT = 1 Vote

Deliverables
Pull request(s) to the Snapshot Github repos that implement the strategy and allow us to add it to our snapshot and test with a vote. The test will be a wallet that has UBXT in both BSC/ETH staking contracts and has normal UBXT staked as well as UBXT LP staked, if the expected total voting power of the user is equal to the amount of UBXT they have in their wallet + the UBXT in the eth/bsc staking pools then the strategy will be working.

Useful Links
Snapshot Strategy docs: docs.snapshot.org

Snapshot space: snapshot.org/#/ubxt.eth

UBXT staking smart contract ETH: 0x6f87364176265CaD6FFC70aD2A795630395a8c24

UBXT staking smart contract BSC: 0x2500C97d1eBD63275DdC3511c825c4d73335Cb77

UNIswapLP: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D

PancakeLP: 0x10ed43c718714eb63d5aa57b78b54704e256024e

UBXT Token ETH contract: 0xbbeb90cfb6fafa1f69aa130b7341089abeef5811

UBXT Token BSC contract: 0x8564653879a18c560e7c0ea0e084c516c62f5653

Document how to follow and unfollow using snapshot.js

Is your feature request related to a problem? Please describe.

  1. I need to search list of spaces by user account address
  2. I need to create and join spaces using snapshot.js but the documentation only has a placeholder .... When will the api be ready?

Describe the solution you'd like
await client.spaces.get("client account address")
await client.spaces.create("awesome.eth", "client account address")
await client.spaces.join("awesome.eth", "client account address")

Additional context
The graphql query for multiple spaces doesn't allow searching by members. Can add there as well.

Strategy symbol error

Expected behavior

Symbol should be 'IOTX'

Actual behavior

Symbol is 'DAI'

Steps to reproduce the behavio

click strategy information button as below

11
13

[bug] vote failed

Expected behavior

vote https://snapshot.org/#/iotex.eth/proposal/QmWhKcFufRfzeWTEpYXzWqvEnh8jrarKE2gL8dV42DnLUK should success.

Actual behavior

an error message: "failed to check voting power"

Steps to reproduce the behavior

vote https://snapshot.org/#/iotex.eth/proposal/QmWhKcFufRfzeWTEpYXzWqvEnh8jrarKE2gL8dV42DnLUK

My analysis

when voting, call to snapshot-hub/server/write/vote.ts

  try {
    const scores = await snapshot.utils.getScores(
      msg.space,
      space.strategies,
      space.network,
      snapshot.utils.getProvider(space.network),
      [body.address]
    );
    const totalScore = scores
      .map((score: any) => Object.values(score).reduce((a, b: any) => a + b, 0))
      .reduce((a, b: any) => a + b, 0);
    if (totalScore === 0) return Promise.reject('no voting power');
  } catch (e) {
    console.log(
      'Failed to check voting power (vote)',
      msg.space,
      body.address,
      e
    );
    return Promise.reject('failed to check voting power');
  }

getScores with 5th parameter snapshot default to "latest"

in snapshot.js/src/utils.ts

export async function getScores(
  space: string,
  strategies: any[],
  network: string,
  provider,
  addresses: string[],
  snapshot: number | string = 'latest'
) {
  try {
    return await Promise.all(
      strategies.map((strategy) =>
        (snapshot !== 'latest' && strategy.params?.start > snapshot) ||
        (strategy.params?.end &&
          (snapshot === 'latest' || snapshot > strategy.params?.end)) ||
        addresses.length === 0
          ? {}
          : _strategies[strategy.name](
              space,
              network,
              provider,
              addresses,
              strategy.params,
              snapshot
            )
      )
    );
  } catch (e) {
    return Promise.reject(e);
  }
}

here will always return true so that getScores return [ { } ];
(strategy.params?.end &&
(snapshot === 'latest' || snapshot > strategy.params?.end))

then vote will always faild with error "failed to check voting power"

Write a readme that explains steps to build & test

npm install and npm run test did not work for me magically. I discovered that because of optional chaining this depends on Node >=14 (#279) and after I upgraded, I managed to build. But still, I'm getting errors when running tests.

In short, it would be very helpful to write a readme that explains what are the steps to build and test this source code.

Vote by API

Hello 👋 - I am trying to see if it's possible to integrate with Snapshot voting thru API. I looked through the docs and seems like its possible since there is a Gnosis app, but couldn't find any more relevant detail. Could someone point me to the right direction?

Can't use the package in a browser

Expected behavior

Install snapshot.js in my frontend app and use it normally

Actual behavior

Uncaught reference error BN is not defined

Steps to reproduce the behavior

create-react-app demo
cd demo
npm i @snapshot-labs/snapshot.js
npm start

Import Snapshot.js give empty object

The package not found issue is definitely fixed, however in another rollup issue it doesn't seem to export anything?

e.g.


import snapshot from "@snapshot-labs/snapshot.js";

function App() {
  console.log(snapshot) // returns {}
  console.log(snapshot.strategies) // expected: { balancer: {}, etc... }; actual: returns undefined
}

I also tried to import snapshot from @snapshot-labs/snapshot.js/dist/index and other variations but says Module not found

Originally posted by @yjkimjunior in #67 (comment)

Support custom score API URL for testing

Analogous to: snapshot-labs/snapshot#918
We could replace:

export const SNAPSHOT_SCORE_API = 'https://score.snapshot.org/api/scores';

...with an optional last parameter here:

snapshot.js/src/utils.ts

Lines 115 to 122 in 81f100e

export async function getScores(
space: string,
strategies: any[],
network: string,
provider: StaticJsonRpcProvider | string,
addresses: string[],
snapshot: number | string = 'latest'
) {

...defaulting to https://score.snapshot.org if not set of course.

Most creative Snapshot strategy

Challenge

Develop the most creative strategy on Snapshot and compete for a prize pool of 1,000 DAI.

Prizes

1st - 500 DAI
2nd - 300 DAI
3rd - 200 DAI

Context

On Snapshot, the strategies are JavaScript functions used to calculate the results of a proposal. The function take as input the list of voters and return a score for each of them. A proposal can use one or multiple strategies, the most common one is "erc20-balance-of", this strategy count the balances of the voters for a specific ERC20 token. Within a strategy you can query data from smart contract, a subgraph or an external API and build your own logic on how results are calculated.

You can find all the available strategies here https://snapshot.page/#/strategies
Learn more https://docs.snapshot.page/strategies

Ideas

  • Use NTFs, POAP to calculate score
  • Use identity protocols like BrightID, Circles
  • Conviction voting (value accruing over time)
  • Quadratic voting
  • Find a use of an external API

Requirements

  • The strategy code should not use more than 2 times the request functions (call, multicall, subgraphRequest or fetch). If the strategy require more requests we suggest to create a smart contract to move some of the logic on-chain.
  • Add a README.md file to explain how your strategy works. See example.
  • Add a examples.json file with samples queries to try with your strategy. The sample queries must return a positive number when tested. See example.
  • Create a space using your strategy and / or find existing space(s) to use it.

Support

You can reach our support on Discord https://discord.snapshot.page in the channel #contribute.

Getting CORS error when trying to create proposal with snapshot.js from browser

Expected behavior

Should create a proposal

Actual behavior

OPTIONS https://snapshot.org//api/msg

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://snapshot.org//api/msg. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 502

Steps to reproduce the behavior

import snapshot from "@snapshot-labs/snapshot.js";

async createProposal() {
    const hub = "https://snapshot.org/"; // or https://testnet.snapshot.org for testnet
    const client = new snapshot.Client712(hub);
    const receipt = await client.proposal(this.app.provider, this.app.account, {
      space: "daouniverse.eth",
      type: "single-choice",
      title: "Test proposal using Snapshot.js",
      body: "",
      choices: ["Alice", "Bob", "Carol"],
      start: 1648189566, // how do we get this?
      end: 1648193166, // how do we calculate this?
      snapshot: 14453547, // how do we get this id?
      network: "1",
      // how to get strategies?
      strategies: JSON.stringify([{ name: "erc20-balance-of", network: "1", params: { symbol: "GCR", address: "0x6307b25a665efc992ec1c1bc403c38f3ddd7c661", decimals: 18 } }]),
      plugins: JSON.stringify({}),
      metadata: JSON.stringify({}),
    });
    console.log("createProposal", receipt);
  }

and in render

<button onClick={this.createProposal}>Create Proposal</button>

Is the snapshot.js not meant to be used from frontend ?

How to do a vote with multiple-choice?

Expected behavior

import { Web3Provider } from '@ethersproject/providers';
const web3 = new Web3Provider(window.ethereum);
const [account] = await web3.listAccounts();
const receipt = await client.vote(web3, account, {
  space: 'yam.eth',
  proposal: '0x21ea31e896ec5b5a49a3653e51e787ee834aaf953263144ab936ed756f36609f',
  type: 'multiple-choice',
  choice: [1,0,0,0,0,0,0,0,0],
  metadata: JSON.stringify({})
});

This should create a signed message with a choice:
{"1":1}. (multiple-choice)

Actual behavior

choice is turned into a single number.

Steps to reproduce the behavior

Run code above.

Balancer strategy not working for smart pools

Expected behavior

Snapshot should recognize users with LP tokens of a smart pool and count them towards the vote

Actual behavior

Smart pool tokens aren't visible to the balance strategy, and users dont have any voting weight.

Steps to reproduce the behavior

This is the JSON config I'm using for MetaFactory's snapshot config (https://snapshot.page/#/metafactory.eth/settings)

Link to the pool: https://pools.balancer.exchange/#/pool/0x3c035c3f8e271e12df1bed648024e60249f507c3/

{
  "symbol": "GEAR",
  "address": "0xfb5453340c03db5ade474b27e68b6a9c6b2823eb",
  "decimals": 18
}

Looking into the strategy, I can see that the Subgraph for Balancer doesn't list poolShares for the smart pools I have liquidity in:
image

Is there an updated subgraph that works with smart pools?

Support Rinkeby ENS resolver

Once this is merged: https://github.com/snapshot-labs/snapshot.js/pull/400/files

The getSpaceUri makes an ENS lookup to find the space settings for a certain ENS name. Would be nice if this could also support a testnet resolver, like: https://rinkeby.etherscan.io/address/0xf6305c19e814d2a75429fd637d01f7ee0e77d615

This way, for testing and local development and everything, if you don't already have a mainnet ENS domain, you can register one e.g. on Rinkeby, and use that to create a new space. The exact implementation of this needs to be discussed, since you probably don't want this to result in real spaces. But some form of dev/local mode would be nice. The frontend would then also need an update to make that somehow configurable.

Circular dependencies

I want to use my local copy of snapshot.js when working on the hub and/or UI. I use yarn link for that but I get this error:

image

Re-building it or running dev mode doesn't work. But what I noticed is this:

image

Circular dependencies... Well, that doesn't sound good. Some more searching later:

image

I checked out some older commits and it is like that for more than a year... at least. Imho already far too long and we just build up more and more technical debt. This should be fixed asap.

utils.getScores() not working

Expected behavior

Return a list, a sum of scores of all addresses of voters specified in parameters, as described in the documentation here: https://docs.snapshot.org/snapshot.js#getscores

Actual behavior

Returns TypeError: Cannot read properties of undefined (reading 'scores')

I investigated a little bit and found out that the problem is in this line. Something is going wrong when reading the object returned by the API.

Steps to reproduce the behavior

I copied the code presented in the documentation in this link. The code was exactly the same.

score.snapshot.org CORS policy blocking API queries.

Expected behavior

We make a call to snapshot.utils.getScores and fetch a user's score.

Actual behavior

Call to snapshot.utils.getScores prints the following in console:

Access to XMLHttpRequest at 'https://score.snapshot.org/api/scores' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Steps to reproduce the behavior

Will be present on any site outside of the snapshot.org domain utilizing the snapshot API to query getScores.

whitelist template doesn't allow add

Expected behavior

copy paste whitelist strategy into add strategy whitelist
add button should show

Actual behavior

add button unselectable

Steps to reproduce the behavior

copy and paste the whitelist template into the white list strategy try to click add.

hi
i am trying to attach an array of addresses to whitelist for a tiered proposal system.
Please advise.

BSC chain failing to connect

Expected behavior

Queries to the BSC should not fail connection.

Actual behavior

The console log for the browser shows this

Screen Shot 2021-05-28 at 5 39 14 PM

This error appeared when trying to getScores() in my local machine, and on production with our space based on this chain.
I believe the API KEY might be outdated. Since I generated a new for myself and everything worked out.

Steps to reproduce the behavior

Try any query to this Chain.

Checklist for adding a new strategy

Here is a simple checklist to look when reviewing a PR for a new strategy:

Overview

  • The strategy must be unique.
  • If the strategy does only a single call with an address as input, it's preferable to use the strategy "contract-call" instead of creating a new one.

Code

  • There should be a maximum of 5 requests, a request can use "fetch" a "subgraphRequest" or "multicall".
  • The strategy should not send a request for each voters, this doesn't scale.
  • The strategy PR should not add any dependency in Snapshot.js.
  • The score returned by the strategy should use the same casing for address than on the input, or should return checksummed addresses.

Example

  • Example must include at least 1 address with a positive score.
  • Example must use a snapshot block number in the past.

Test

Recommended

  • Add a README.md file that describe the strategy and provide an example of parameters.
  • Use string ABI instead of object.

Custom Network Support

A new Snapshot user here, it looks like a great product 👍

The use case have for Snapshot is developing (& testing) a custom strategy against an in-memory network. When the strategy is eventually live, the CI testing will remain as part of the CI/CD pipeline (so it'll be a feature needed beyond the initial strategy development).

Although running Snapshot against a network defined outside of the networks.json is not is not currently a feature, if it is a feature you'd like, I'll happily port the changes from my open PR snapshot-labs/snapshot-strategies#79

Generally speaking, this change switches the sourcing of the networks json from being hard-coded import to a CLI option, with the default being the network.json

The use case(s) supported by such a change are:

  • Running strategy tests on CI boxes
  • Running Snapshot against private networks

Let me. know if this is a change you'd like me to create a PR on, or if there's a better solution in this case with Snapshot 🙂

Desired behavior

Run Snapshot against a network whose definition is in a custom json file.

Actual behavior

The neworks.json from Snapshot.js is used.

Steps to reproduce the behavior

Running a test on the default strategy, with the network being a local Ethereum node.

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.