diff --git a/.github/workflows/cd.js-sdk-lts-v0_6.create-release-drafts.yml b/.github/workflows/cd.js-sdk-lts-v0_6.create-release-drafts.yml deleted file mode 100644 index 276aef4caf..0000000000 --- a/.github/workflows/cd.js-sdk-lts-v0_6.create-release-drafts.yml +++ /dev/null @@ -1,60 +0,0 @@ -name: CD | Create JS-SDK v0.6 LTS Release Draft -env: - GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} - -on: - workflow_dispatch: - push: - branches: - - "release-js-sdk-lts-v0.6" - paths: - - "packages/js-sdk/**" - - ".github/workflows/cd.js-sdk-v0_6.create-release-drafts.yml" - -jobs: - - create-release-draft: - name: Create Release Draft for js-sdk v0.6 - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v3 - - - name: Use Node.js 16.x - uses: actions/setup-node@v3 - with: - node-version: 16.x - registry-url: https://registry.npmjs.org/ - - - name: Check package versions - id: check_versions - run: | - # js-sdk@v0.6 - PUBLISHED_JS_SDK_VERSION=`npm show @superfluid-finance/js-sdk@v0.6 version` - NEW_JS_SDK_VERSION=`jq -r .version packages/js-sdk/package.json` - if [ "$PUBLISHED_JS_SDK_VERSION" != "$NEW_JS_SDK_VERSION" ];then - echo "PUBLISH_JS_SDK=1" >> $GITHUB_ENV - echo "js-sdk changed: $PUBLISHED_JS_SDK_VERSION -> $NEW_JS_SDK_VERSION" - else - echo js-sdk unchanged: $PUBLISHED_JS_SDK_VERSION - fi - - echo "::set-output name=NEW_JS_SDK_VERSION::$NEW_JS_SDK_VERSION" - - - name: Create js-sdk v0.6 LTS release draft - if: env.PUBLISH_JS_SDK == 1 - id: create_release_js_sdk - uses: actions/create-release@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token - with: - tag_name: js-sdk@v${{ steps.check_versions.outputs.NEW_JS_SDK_VERSION }} - release_name: js-sdk@v${{ steps.check_versions.outputs.NEW_JS_SDK_VERSION }} - body: | - Changes in this js-sdk v0.6 release - ## Changed - ## Added - ## Fixes - ## Breaking - draft: true diff --git a/.github/workflows/cd.js-sdk-stable.create-release-drafts.yml b/.github/workflows/cd.js-sdk-stable.create-release-drafts.yml deleted file mode 100644 index f934c512b4..0000000000 --- a/.github/workflows/cd.js-sdk-stable.create-release-drafts.yml +++ /dev/null @@ -1,60 +0,0 @@ -name: CD | Create JS-SDK v0.6 Stable Release Draft -env: - GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} - -on: - workflow_dispatch: - push: - branches: - - "release-js-sdk-stable" - paths: - - "packages/js-sdk/**" - - ".github/workflows/cd.js-sdk-stable.create-release-drafts.yml" - -jobs: - - create-release-draft: - name: Create Release Draft - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v3 - - - name: Use Node.js 16.x - uses: actions/setup-node@v3 - with: - node-version: 16.x - registry-url: https://registry.npmjs.org/ - - - name: Check package versions - id: check_versions - run: | - # js-sdk@latest - PUBLISHED_JS_SDK_VERSION=`npm show @superfluid-finance/js-sdk@latest version` - NEW_JS_SDK_VERSION=`jq -r .version packages/js-sdk/package.json` - if [ "$PUBLISHED_JS_SDK_VERSION" != "$NEW_JS_SDK_VERSION" ];then - echo "PUBLISH_JS_SDK=1" >> $GITHUB_ENV - echo "js-sdk changed: $PUBLISHED_JS_SDK_VERSION -> $NEW_JS_SDK_VERSION" - else - echo js-sdk unchanged: $PUBLISHED_JS_SDK_VERSION - fi - - echo "::set-output name=NEW_JS_SDK_VERSION::$NEW_JS_SDK_VERSION" - - - name: Create js-sdk release draft - if: env.PUBLISH_JS_SDK == 1 - id: create_release_js_sdk - uses: actions/create-release@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token - with: - tag_name: js-sdk@v${{ steps.check_versions.outputs.NEW_JS_SDK_VERSION }} - release_name: js-sdk@v${{ steps.check_versions.outputs.NEW_JS_SDK_VERSION }} - body: | - Changes in this js-sdk stable release - ## Changed - ## Added - ## Fixes - ## Breaking - draft: true diff --git a/README.md b/README.md index 995d7f2f78..53fe257a50 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,9 @@ Official subgraph for the Superfluid Protocol.

-:warning: This repo is deprecated, use sdk-core instead :warning: +:warning: This repo is fully deprecated, use sdk-core instead :warning: + +You can get the last release of js-sdk at the branch [here](https://github.com/superfluid-finance/protocol-monorepo/tree/release-js-sdk-stable). Javascript SDK for building with Superfluid Protocol. diff --git a/packages/js-sdk/.eslintignore b/packages/js-sdk/.eslintignore deleted file mode 100644 index 51c489b079..0000000000 --- a/packages/js-sdk/.eslintignore +++ /dev/null @@ -1,3 +0,0 @@ -src/abi.js -dist -build diff --git a/packages/js-sdk/.eslintrc.json b/packages/js-sdk/.eslintrc.json deleted file mode 100644 index 9905f3b996..0000000000 --- a/packages/js-sdk/.eslintrc.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "env": { - "browser": true, - "es6": true - }, - "globals": { - "Atomics": "readonly", - "SharedArrayBuffer": "readonly" - }, - "parserOptions": { - "ecmaVersion": 2018, - "sourceType": "module" - } -} diff --git a/packages/js-sdk/.gitignore b/packages/js-sdk/.gitignore deleted file mode 100644 index fbd7fa7cf7..0000000000 --- a/packages/js-sdk/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -/src/abi.js -/reports -/coverage -/.nyc_output -.idea -stats.json diff --git a/packages/js-sdk/.nycrc.json b/packages/js-sdk/.nycrc.json deleted file mode 100644 index 727d85c23b..0000000000 --- a/packages/js-sdk/.nycrc.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "exclude": [ - "src/abi.js" - ] -} diff --git a/packages/js-sdk/.prettierignore b/packages/js-sdk/.prettierignore deleted file mode 100644 index 13d85ef105..0000000000 --- a/packages/js-sdk/.prettierignore +++ /dev/null @@ -1,3 +0,0 @@ -/dist -/src/abi.js -/build diff --git a/packages/js-sdk/.prettierrc.js b/packages/js-sdk/.prettierrc.js deleted file mode 100644 index 42697c69af..0000000000 --- a/packages/js-sdk/.prettierrc.js +++ /dev/null @@ -1,5 +0,0 @@ -module.exports = { - trailingComma: "es5", - singleQuote: false, - bracketSpacing: false, -}; diff --git a/packages/js-sdk/LICENSE b/packages/js-sdk/LICENSE deleted file mode 100644 index bff8e5a2af..0000000000 --- a/packages/js-sdk/LICENSE +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright © 2020-2022 Superfluid Finance Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/js-sdk/README.md b/packages/js-sdk/README.md deleted file mode 100644 index bc19ee1163..0000000000 --- a/packages/js-sdk/README.md +++ /dev/null @@ -1,255 +0,0 @@ -

Welcome to @superfluid-finance/js-sdk 👋 -

-
-Superfluid logo -

- - Version - - - - - - License: MIT - - - Twitter: Superfluid_HQ - -

-
- -Javascript SDK for building with Superfluid Protocol. - -### :warning: This repo is deprecated :warning: -**Superfluid SDK project has been modularized, for similar functionality use [`@superfluid-finance/sdk-core`](https://github.com/superfluid-finance/protocol-monorepo/tree/dev/packages/sdk-core) instead.** - - -### 🏠 [Homepage](https://superfluid.finance) - -### ✨ [Superfluid App](https://app.superfluid.finance/) - -### 📖 [Docs](https://docs.superfluid.finance) - -# Important Notice - -We will be deprecating the JS-SDK and stop providing support/fixes in the near future, so please use either: -- [sdk-core](https://www.npmjs.com/package/@superfluid-finance/sdk-core) which can be used for both front-end and back-end dApp development, this can be thought of more as a thin wrapper of the protocol contracts and is unconcerned with state. - -or - -- [sdk-redux](https://www.npmjs.com/package/@superfluid-finance/sdk-redux) for building production-grade front-ends for dApps with state management, caching logic, transaction tracking, react hooks and much more. - -# Usage - -Here is a quick look at using the SDK. - -```js -const SuperfluidSDK = require("@superfluid-finance/js-sdk"); -const Web3 = require("web3"); - -const sf = new SuperfluidSDK.Framework({ - web3: new Web3(window.ethereum), - tokens: ["fDAI"], -}); -await sf.initialize(); - -const bob = sf.user({ address: "0xabc...", token: sf.tokens.fDAIx.address }); - -// Constant Flow Agreement -await bob.flow({ - recipient: "0x123...", - flowRate: "38580246913580", // 100 tokens / mo -}); - -// Instant Distribution Agreement -// - More utilities coming soon. See the docs for now -``` - -## What's In the Bag - -- `sf.user`: A helpful abstraction that should handle most of your needs. See below for more details. -- `sf.host` : The [truffle contract instance](https://www.trufflesuite.com/docs/truffle/getting-started/interacting-with-your-contracts) - to interact with the host contract (Superfluid.sol). -- `sf.contracts` : The [truffle contract](https://www.trufflesuite.com/docs/truffle/reference/contract-abstractions) objects loaded by the SDK: - - `IERC20` : The ERC20 Interface. - - `TokenInfo` : A customary ERC20 token info interface (name/symbol/decimals). - - `ERC20WithTokenInfo` : A combination of IERC20 and TokenInfo. - - `TestToken` : A ERC20 Test token. - - `IResolver` : A simple resolver interface to locate different versions of the contracts. - - `ISuperfluid` : The Superfluid host contract interface. - - `ISuperToken` : The Super token contract interface. - - `IConstantFlowAgreementV1` : The constant flow agreement (v1) contract interface. - - `IInstantDistributionAgreementV1` : The instant distribution agreement (v1) contract interface. -- Token factory helper functions: - - `sf.createERC20Wrapper` -- `sf.resolver`: The resolver used by the SDK. - - In test nets, there are some test tokens can be located with the resolver: - - `fDAI` : The fake DAI. `sf.resolver.get("tokens.fDAI")`. - - `fUSDC` : The fake USDC. `sf.resolver.get("tokens.fUSDC")`. - - `fTUSD` : The fake TUSD. `sf.resolver.get("tokens.fTUSD")`. -- `sf.agreements`: - - `sf.agreements.cfa` : Constant flow agreement truffle contract instance. - - `sf.agreements.ida` : Instant distribution agreement truffle contract instance. -- `sf.cfa`: The constant flow agreement helper class instance. -- `sf.ida`: The instant distribution agreement helper class instance. - -## Initialization - -During initialization, the resolver will be used to fetch the correct set of contracts based on the `version` you provide - -| Argument | Type | description | default | -| :------------------- | :------- | ------------------------------------------------------ | --------- | -| version | String | Release version of the deployed protocol | v1 | -| isTruffle | Boolean | Use the Framework under the native truffle environment | false | -| web3 | Object | Use the Framework with web3.js (1.3.x) | undefined | -| additionalContracts | String[] | additional contracts to be loaded | [] | -| tokens | String[] | List of token keys to load from the resolver | [] | -| loadSuperNativeToken | Boolean | Load super native token (e.g. ETHx) if possible | false | -| resolverAddress | Address | Force resolver address | undefined | - -You also need to choose what web3 framework you plan to use, currently we support three modes: - -- Truffle native environment (developing using `truffle test|exec|egc.`). -- [Web3.js](https://web3js.readthedocs.io/en/v1.2.1/), currently the SDK has been tested with web3.js `1.3.x` versions. - - -**Example with Web3.js** - -```js -const SuperfluidSDK = require("@superfluid-finance/js-sdk"); -const web3 = require("web3"); - -const sf = new SuperfluidSDK.Framework({ - web3: new Web3(window.ethereum), - tokens: ["fDAI"], -}); -await sf.initialize(); - -const bob = sf.user({ address: "0xabc...", token: sf.tokens.fDAIx.address }); -``` - -The exposed contract objects are of [`truffle-contract`](https://github.com/trufflesuite/truffle/tree/develop/packages/contract/) type. - -**Example with truffle native** - -```js -const SuperfluidSDK = require("@superfluid-finance/js-sdk"); - -const sf = new SuperfluidSDK.Framework({ - isTruffle: true, - tokens: ["fDAI"], -}); -await sf.initialize(); - -const bob = sf.user({ address: "0xabc...", token: sf.tokens.fDAIx.address }); -``` - -The exposed contract objects are of [`truffle-contract`](https://github.com/trufflesuite/truffle/tree/develop/packages/contract/) type loaded using truffle `artifacts` object. - -## :bust_in_silhouette: User - -Create a new User object to quickly create and modify agreements. - -Example: - -```js -const bob = sf.user({ address: "0xabc...", token: sf.tokens.fDAI }); -const carol = sf.user({ address: "0x123...", token: sf.tokens.fDAI }); -``` - -### `user.details()` - -Returns details about an account. - -| Argument | Type | default | -| :------- | :--- | ------- | -| n/a | | | - -Example: - -```js -console.log(await bob.details()); - -> { - cfa: { - flows: { - inFlows: [ - { - sender: "0xf17f52151EbEF6C7334FAD080c5704D77216b732", - receiver: "0xC5fdf4076b8F3A5357c5E395ab970B5B54098Fef", - flowRate: "38580246913580" - } - ], - outFlows: [ - { - sender: "0xC5fdf4076b8F3A5357c5E395ab970B5B54098Fef", - receiver: "0x821aEa9a577a9b44299B9c15c88cf3087F3b5544", - flowRate: "19290123456790" - } - ] - }, - netFlow: "19290123456790" - }, - ida: {} // Available soon -} -``` - -### `user.flow({recipient, flowRate, [, onTransaction, ...]})` - -Create / update / delete a flow to the recipient. Enter "0" to delete a flow. - -| Argument | Type | default | -| :------------ | :----------------------------- | -------- | -| recipient | Address or another User Object | required | -| flowRate | String | required | -| onTransaction | Function | null | - -Example: - -```js -const tx = await alice.flow({ - recipient: bob, - flowRate: "38580246913580", // 100 / mo - // OPTIONS: See ConstantFlowAgreementV1Helper for more - onTransaction: (hash) => { - txHash = hash; - }, -}); -``` - -## Closer to the metal - -You may also use the helper classes and functions instead of the `User` abstraction. - -The helpers are usually considered thinner wrappers of the underlying contract calls. It is suitable if you want more control and customization of how to interact with the protocol. - -The available helpers currently are: - -- `sf.cfa` - Constant flow agreement helper. -- `sf.ida` - Instant distribution agreement helper. -- `sf.createERC20Wrapper` - Create a new ERC20 wrapper. -- `sf.batchCall` - (TBD) batchCall helper. -- `sf.callAppAction` - (TBD) callAppAction helper. - -For their documentations, please look into their code comments directly. - -# Contributing - -Contributions and suggestions welcome! - -## Module packaging - -Check the module size and dependencies: - -```bash -yarn stats -``` - -## Testing - -Since testing can take a long time to execute, you may want to use the [execlusive tests](https://mochajs.org/#exclusive-tests) feature from MochaJS to isolate only the test you want. For example: - -```bash -# Only run User.test.js -nodemon -x npx truffle test ./test/User.test.js -``` diff --git a/packages/js-sdk/hardhat.config.js b/packages/js-sdk/hardhat.config.js deleted file mode 100644 index 997c664a2c..0000000000 --- a/packages/js-sdk/hardhat.config.js +++ /dev/null @@ -1,46 +0,0 @@ -require("@typechain/hardhat"); -require("@nomiclabs/hardhat-ethers"); -require("@nomicfoundation/hardhat-chai-matchers"); -require("@nomiclabs/hardhat-web3"); -require("dotenv").config(); - -/** - * This Hardhat config is only used for testing the SDK-Core. - * Note: For tests to work, 0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266 - * must be the deployer of the contracts. - */ -module.exports = { - solidity: { - version: "0.8.15", - settings: { - optimizer: { - enabled: true, - runs: 200, - }, - }, - }, - paths: { - artifacts: "../ethereum-contracts/artifacts", - }, - networks: { - localhost: { - // url may not be necessary for localhost/hardhat node chainId - url: "http://0.0.0.0:8545/", - chainId: 31337, - }, - matic: { - url: process.env.MATIC_PROVIDER_URL || "", - chainId: 137, - }, - bsc: { - url: process.env.BSC_PROVIDER_URL || "", - accounts: process.env.TEST_PRIVATE_KEY - ? [process.env.TEST_PRIVATE_KEY || ""] - : [], - chainId: 56, - }, - }, - mocha: { - timeout: 250000, - }, -}; diff --git a/packages/js-sdk/package.json b/packages/js-sdk/package.json deleted file mode 100644 index 83eaf0dd6a..0000000000 --- a/packages/js-sdk/package.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "name": "@superfluid-finance/js-sdk", - "version": "0.6.3", - "description": "Javascript SDK for building with Superfluid Protocol", - "homepage": "https://github.com/superfluid-finance/protocol-monorepo/tree/dev/packages/js-sdk#readme", - "repository": { - "type": "git", - "url": "https://github.com/superfluid-finance/protocol-monorepo.git", - "directory": "packages/js-sdk" - }, - "license": "MIT", - "main": "src/index.js", - "types": "src/index.d.ts", - "files": [ - "src/**/*.md", - "src/**/*.d.ts", - "src/**/*.json", - "src/**/*.js", - "dist/index.js" - ], - "browser": { - "fs": false, - "path": false - }, - "scripts": { - "dev": "nodemon -e js,ts -i build -x 'truffle test 2>&1'", - "build": "tasks/build-abi-js.sh && webpack", - "testenv:start": "../ethereum-contracts/test/testenv-ctl.sh start", - "testenv:stop": "../ethereum-contracts/test/testenv-ctl.sh stop", - "pretest": "{ run-s testenv:start > /dev/null& } && sleep 5", - "test": "truffle test", - "test-coverage": "nyc --reporter=html --reporter=lcov --reporter=json yarn test", - "posttest": "yarn testenv:stop", - "watch": "webpack --watch", - "stats": "webpack --profile --json > stats.json && webpack-bundle-analyzer ./stats.json", - "lint": "run-s lint:*", - "lint:js-eslint": "eslint . --max-warnings=0 --report-unused-disable-directives && echo '✔ Your .js files look good.'", - "check-no-focused-tests": "grep -FR .only test || { echo '✔ No test is focused.';exit 0; } && { echo '✘ You have focused tests.'; exit 1; }", - "pre-commit": "if [ ! -z \"$(git status -s .)\" ];then run-s pre-commit:*;else true;fi", - "pre-commit:lint": "yarn lint", - "pre-commit:check-no-focused-tests": "yarn check-no-focused-tests", - "check-updates": "ncu --target minor --dep prod,dev", - "cloc": "sh tasks/cloc.sh" - }, - "dependencies": { - "@superfluid-finance/metadata": "git+https://github.com/superfluid-finance/metadata.git", - "@truffle/contract": "4.5.23", - "auto-bind": "^4.0.0", - "node-fetch": "^2.6.7" - }, - "peerDependencies": { - "@truffle/contract": "^4.0.0" - }, - "devDependencies": { - "@superfluid-finance/ethereum-contracts": "1.4.0", - "chai-as-promised": "^7.1.1", - "webpack": "^5.74.0", - "webpack-bundle-analyzer": "^4.6.1", - "webpack-cli": "^4.10.0" - } -} diff --git a/packages/js-sdk/src/ConstantFlowAgreementV1Helper.d.ts b/packages/js-sdk/src/ConstantFlowAgreementV1Helper.d.ts deleted file mode 100644 index 8cf34543a2..0000000000 --- a/packages/js-sdk/src/ConstantFlowAgreementV1Helper.d.ts +++ /dev/null @@ -1,212 +0,0 @@ -import type { Transaction } from "web3-core"; -import type { Framework } from "./Framework"; -import type { LoadedContract } from "./loadContracts"; -import type BN from 'bn.js'; -import { GasOptions } from "./types/gasOptions"; - -// returned from listFlows -export interface FlowList { - inFlows: { - sender: string; - receiver: string; - flowRate: string; - }[]; - outFlows: { - sender: string; - receiver: string; - flowRate: string; - }[]; -} - -// from CFAv1 contract -// returned from _sanitizeflowInfo -// returned from getFlow and getAccountFlowInfo -export interface FlowInfo { - timestamp: Date; - flowRate: string; - deposit: string; - owedDeposit: string; -} - -// Same interface used for create and update flow -export interface CreateFlowOptions { - superToken: string; - sender: string; - receiver: string; - flowRate: string; - userData?: string; - onTransaction?: ()=>any; - gasOptions?: GasOptions; -} -export type UpdateFlowOptions = CreateFlowOptions - -// MUST include 'by' type, it's only diff between create and update -export interface DeleteFlowOptions { - superToken: string; - sender: string; - receiver: string; - flowRate: string; - by?: string; - userData?: string; - onTransaction?: ()=>any; - gasOptions?: GasOptions; -} - -export interface GetFlowOptions { - superToken: string; - sender: string; - receiver: string; -} - -export interface GetNetFlowOptions { - superToken: string; - account: string; -} - -export type GetAccountFlowInfoOptions = GetNetFlowOptions - -export declare class ConstantFlowAgreementV1Helper { - static _sanitizeflowInfo({ - timestamp, - flowRate, - deposit, - owedDeposit, - }: { - timestamp: number | BN, - flowRate: number | BN, - deposit: number | BN, - owedDeposit: number | BN - }): FlowInfo; - /** - * @dev Create new helper class - * @param {Framework} sf Superfluid Framework object - * - * NOTE: You should first call async function Framework.initialize to initialize the object. - */ - constructor(sf: Framework); - _sf: Framework; - _cfa: LoadedContract; - /** - * @dev Create a new flow - * @param {tokenParam} superToken superToken for the flow - * @param {addressParam} sender sender of the flow - * @param {addressParam} receiver receiver of the flow - * @param {flowRateParam} flowRate the flowrate of the flow - * @param {Buffer} userData the user data passed to the callbacks - * @param {GasOptions} gasOptions pass network gas parameters - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @return {Promise} web3 transaction object - */ - createFlow({ - superToken, - sender, - receiver, - flowRate, - userData, - onTransaction, - gasOptions, - }: CreateFlowOptions): Promise; - /** - * @dev Update a new flow with a new flow rate - * @param {tokenParam} superToken superToken for the flow - * @param {addressParam} sender sender of the flow - * @param {addressParam} receiver receiver of the flow - * @param {flowRateParam} flowRate the flowrate of the flow - * @param {Buffer} userData the user data passed to the callbacks - * @param {GasOptions} gasOptions override network gas parameters - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @return {Promise} web3 transaction object - */ - updateFlow({ - superToken, - sender, - receiver, - flowRate, - userData, - onTransaction, - gasOptions, - }: UpdateFlowOptions): Promise; - /** - * @dev Delete a existing flow - * @param {tokenParam} superToken superToken for the flow - * @param {addressParam} sender sender of the flow - * @param {addressParam} receiver receiver of the flow - * @param {addressParam} by delete flow by a third party (liquidations) - * @param {Buffer} userData the user data passed to the callbacks - * @param {GasOptions} gasOptions override network gas parameters - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @return {Promise} web3 transaction object - */ - deleteFlow({ - superToken, - sender, - receiver, - by, - userData, - onTransaction, - gasOptions, - }: DeleteFlowOptions): Promise; - /** - * @dev Get information of a existing flow - * @param {tokenParam} superToken superToken for the flow - * @param {addressParam} sender sender of the flow - * @param {addressParam} receiver receiver of the flow - * @return {Promise} Informationo about the flow: - * - timestamp, time when the flow was last updated - * - flowRate, flow rate of the flow - * - deposit, deposit of the flow - * - owedDeposit, owed deposit of the flow - */ - getFlow({ - superToken, - sender, - receiver, - }: GetFlowOptions): Promise; - /** - * @dev Get information of the net flow of an account - * @param {tokenParam} superToken superToken for the flow - * @param {addressParam} account the account for the query - * @return {Promise} Net flow rate of the account - */ - getNetFlow({ - superToken, - account, - }: GetNetFlowOptions): Promise; - /** - * @dev Get information of the net flow of an account - * @param {tokenParam} superToken superToken for the flow - * @param {addressParam} account the account for the query - * @return {Promise} Net flow rate of the account - */ - getAccountFlowInfo({ - superToken, - account, - }: GetAccountFlowInfoOptions): Promise; - - getFlowEvents({ - token, - receiver, - sender, - }: { - token: string; - receiver?: string; - sender?: string; - }): Promise; - /** - * @dev List flows of the account - * @param {tokenParam} superToken superToken for the flow - * @param {addressParam} account the account for the query - * @return {Promise<[]>} - */ - listFlows({ - superToken, - account, - onlyInFlows, - onlyOutFlows, - }: { - superToken: string; - account: string; - onlyInFlows?: boolean; - onlyOutFlows?: boolean; - }): Promise; -} diff --git a/packages/js-sdk/src/ConstantFlowAgreementV1Helper.js b/packages/js-sdk/src/ConstantFlowAgreementV1Helper.js deleted file mode 100644 index c6c858bc6d..0000000000 --- a/packages/js-sdk/src/ConstantFlowAgreementV1Helper.js +++ /dev/null @@ -1,338 +0,0 @@ -const autoBind = require("auto-bind"); -const {completeTransaction} = require("./utils/general"); - -/** - * @dev Constant flow agreement v1 helper class - */ -module.exports = class ConstantFlowAgreementV1Helper { - /** - * @dev Create new helper class - * @param {Framework} sf Superfluid Framework object - * - * NOTE: You should first call async function Framework.initialize to initialize the object. - */ - constructor(sf) { - this._sf = sf; - this._cfa = sf.agreements.cfa; - autoBind(this); - } - - /** - * @dev Create a new flow - * @param {tokenParam} superToken superToken for the flow - * @param {addressParam} sender sender of the flow - * @param {addressParam} receiver receiver of the flow - * @param {flowRateParam} flowRate the flowrate of the flow - * @param {Buffer} userData the user data passed to the callbacks - * @param {Object} gasOptions pass network gas parameters - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @return {Promise} web3 transaction object - */ - async createFlow({ - superToken, - sender, - receiver, - flowRate, - userData, - gasOptions = {}, - onTransaction = () => null, - }) { - const superTokenNorm = await this._sf.utils.normalizeTokenParam( - superToken - ); - const senderNorm = await this._sf.utils.normalizeAddressParam(sender); - const receiverNorm = await this._sf.utils.normalizeAddressParam( - receiver - ); - const flowRateNorm = this._sf.utils.normalizeFlowRateParam(flowRate); - userData = userData || "0x"; - console.debug( - `Create flow from ${sender} to ${receiver} at ${flowRate} for ${superToken} ...` - ); - const tx = await completeTransaction({ - sf: this._sf, - args: [ - this._cfa.address, - this._cfa.contract.methods - .createFlow( - superTokenNorm, - receiverNorm, - flowRateNorm, - "0x" - ) - .encodeABI(), - userData, - ], - sender: senderNorm, - method: this._sf.host.callAgreement, - gasOptions: { - maxPriorityFeePerGas: gasOptions.maxPriorityFeePerGas, - maxFeePerGas: gasOptions.maxFeePerGas, - }, - onTransaction, - }); - this._sf._pushTxForGasReport(tx, "createFlow"); - console.debug("Flow created."); - return tx; - } - - /** - * @dev Update a new flow with a new flow rate - * @param {tokenParam} superToken superToken for the flow - * @param {addressParam} sender sender of the flow - * @param {addressParam} receiver receiver of the flow - * @param {flowRateParam} flowRate the flowrate of the flow - * @param {Buffer} userData the user data passed to the callbacks - * @param {Object} gasOptions pass network gas parameters - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @return {Promise} web3 transaction object - */ - async updateFlow({ - superToken, - sender, - receiver, - flowRate, - userData, - gasOptions = {}, - onTransaction = () => null, - }) { - const superTokenNorm = await this._sf.utils.normalizeTokenParam( - superToken - ); - const senderNorm = await this._sf.utils.normalizeAddressParam(sender); - const receiverNorm = await this._sf.utils.normalizeAddressParam( - receiver - ); - const flowRateNorm = this._sf.utils.normalizeFlowRateParam(flowRate); - userData = userData || "0x"; - console.debug( - `Update flow from ${sender} to ${receiver} to ${flowRate} for ${superToken} ...` - ); - - const tx = await completeTransaction({ - sf: this._sf, - args: [ - this._cfa.address, - this._cfa.contract.methods - .updateFlow( - superTokenNorm, - receiverNorm, - flowRateNorm, - "0x" - ) - .encodeABI(), - userData, - ], - sender: senderNorm, - method: this._sf.host.callAgreement, - gasOptions: { - maxPriorityFeePerGas: gasOptions.maxPriorityFeePerGas, - maxFeePerGas: gasOptions.maxFeePerGas, - }, - onTransaction, - }); - - this._sf._pushTxForGasReport(tx, "updateFlow"); - console.debug("Flow updated."); - return tx; - } - - /** - * @dev Delete a existing flow - * @param {tokenParam} superToken superToken for the flow - * @param {addressParam} sender sender of the flow - * @param {addressParam} receiver receiver of the flow - * @param {addressParam} by delete flow by a third party (liquidations) - * @param {Buffer} userData the user data passed to the callbacks - * @param {Object} gasOptions pass network gas parameters - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @return {Promise} web3 transaction object - */ - async deleteFlow({ - superToken, - sender, - receiver, - by, - userData, - gasOptions = {}, - onTransaction = () => null, - }) { - const superTokenNorm = await this._sf.utils.normalizeTokenParam( - superToken - ); - const senderNorm = await this._sf.utils.normalizeAddressParam(sender); - const receiverNorm = await this._sf.utils.normalizeAddressParam( - receiver - ); - const byNorm = - (by && (await this._sf.utils.normalizeAddressParam(by))) || - senderNorm; - userData = userData || "0x"; - console.debug( - `Delete flow from ${sender} to ${receiver} by ${ - by || byNorm - } for ${superToken} ...` - ); - const tx = await completeTransaction({ - sf: this._sf, - args: [ - this._cfa.address, - this._cfa.contract.methods - .deleteFlow(superTokenNorm, senderNorm, receiverNorm, "0x") - .encodeABI(), - userData, - ], - sender: byNorm, - method: this._sf.host.callAgreement, - gasOptions: { - maxPriorityFeePerGas: gasOptions.maxPriorityFeePerGas, - maxFeePerGas: gasOptions.maxFeePerGas, - }, - onTransaction, - }); - this._sf._pushTxForGasReport(tx, "deleteFlow"); - console.debug("Flow deleted."); - return tx; - } - - /** - * @dev Get information of a existing flow - * @param {tokenParam} superToken superToken for the flow - * @param {addressParam} sender sender of the flow - * @param {addressParam} receiver receiver of the flow - * @return {Promise} Informationo about the flow: - * - timestamp, time when the flow was last updated - * - flowRate, flow rate of the flow - * - deposit, deposit of the flow - * - owedDeposit, owed deposit of the flow - */ - async getFlow({ - superToken, - sender, - receiver, - //unit - }) { - const superTokenNorm = await this._sf.utils.normalizeTokenParam( - superToken - ); - const senderNorm = await this._sf.utils.normalizeAddressParam(sender); - const receiverNorm = await this._sf.utils.normalizeAddressParam( - receiver - ); - const result = await this._cfa.getFlow( - superTokenNorm, - senderNorm, - receiverNorm - ); - return this.constructor._sanitizeflowInfo(result); - } - - /** - * @dev Get information of the net flow of an account - * @param {tokenParam} superToken superToken for the flow - * @param {addressParam} account the account for the query - * @return {Promise} Net flow rate of the account - */ - async getNetFlow({ - superToken, - account, - //unit - }) { - const superTokenNorm = await this._sf.utils.normalizeTokenParam( - superToken - ); - const accountNorm = await this._sf.utils.normalizeAddressParam(account); - const netFlow = await this._cfa.getNetFlow(superTokenNorm, accountNorm); - return netFlow.toString(); - } - - /** - * @dev Get information of the net flow of an account - * @param {tokenParam} superToken superToken for the flow - * @param {addressParam} account the account for the query - * @return {Promise} Net flow rate of the account - */ - async getAccountFlowInfo({ - superToken, - account, - //unit - }) { - const superTokenNorm = await this._sf.utils.normalizeTokenParam( - superToken - ); - const accountNorm = await this._sf.utils.normalizeAddressParam(account); - const result = await this._cfa.getAccountFlowInfo( - superTokenNorm, - accountNorm - ); - return this.constructor._sanitizeflowInfo(result); - } - - static _sanitizeflowInfo({timestamp, flowRate, deposit, owedDeposit}) { - return { - timestamp: new Date(Number(timestamp.toString()) * 1000), - flowRate: flowRate.toString(), - deposit: deposit.toString(), - owedDeposit: owedDeposit.toString(), - }; - } - - async getFlowEvents({token, receiver = null, sender = null}) { - let flows = await this._sf.getPastEvents(this._cfa, "FlowUpdated", { - token, - receiver, - sender, - }); - return Object.values( - flows.reduce((acc, i) => { - acc[i.sender + ":" + i.receiver] = i; - return acc; - }, {}) - ).filter((i) => i.flowRate.toString() != "0"); - } - - /** - * @dev List flows of the account - * @param {tokenParam} superToken superToken for the flow - * @param {addressParam} account the account for the query - * @return {Promise<[]>} - */ - async listFlows({ - superToken, - account, - onlyInFlows, - onlyOutFlows, - //unit - }) { - const superTokenNorm = await this._sf.utils.normalizeTokenParam( - superToken - ); - const accountNorm = await this._sf.utils.normalizeAddressParam(account); - const result = {}; - if (!onlyOutFlows) { - result.inFlows = ( - await this.getFlowEvents({ - receiver: accountNorm, - token: superTokenNorm, - }) - ).map((f) => ({ - sender: f.sender, - receiver: f.receiver, - flowRate: f.flowRate.toString(), - })); - } - if (!onlyInFlows) { - result.outFlows = ( - await this.getFlowEvents({ - token: superTokenNorm, - sender: accountNorm, - }) - ).map((f) => ({ - sender: f.sender, - receiver: f.receiver, - flowRate: f.flowRate.toString(), - })); - } - return result; - } -}; diff --git a/packages/js-sdk/src/Framework.d.ts b/packages/js-sdk/src/Framework.d.ts deleted file mode 100644 index 94d915cd22..0000000000 --- a/packages/js-sdk/src/Framework.d.ts +++ /dev/null @@ -1,69 +0,0 @@ -import type Web3 from "web3"; -import type { ConstantFlowAgreementV1Helper } from "./ConstantFlowAgreementV1Helper"; -import type { InstantDistributionAgreementV1Helper } from "./InstantDistributionAgreementV1Helper"; -import type { GasMeter, Record } from "./utils/gasMetering/gasMetering"; -import LoadContracts from "./loadContracts"; -import Config from "./getConfig"; -import type { User } from "./User"; -import type { Utils } from "./Utils"; - -declare type GasReportTypeOptions = 'JSON' | 'HTML' | 'TENDERLY'; - -export interface Agreements { - cfa?: ConstantFlowAgreementV1Helper, - ida?: InstantDistributionAgreementV1Helper -} - -export interface FrameworkOptions { - version?: string, - isTruffle?: boolean, - web3?: Web3, - gasReportType?: GasReportTypeOptions, - additionalContracts?: string[], - tokens?: string[], - loadSuperNativeToken?: boolean, - contractLoader?: LoadContracts.ContractLoader, - resolverAddress?: string, -} -export declare class Framework { - - constructor(options: FrameworkOptions); - - _options: FrameworkOptions; - version: string; - web3: Web3; - _gasReportType: GasReportTypeOptions; - config: Config.NetworkConfig; - contracts: Promise | undefined; - resolver: LoadContracts.LoadedContract; - host: LoadContracts.LoadedContract; - agreements: Agreements; - tokens: { [key: string]: any }; - superTokens: { [key: string]: any }; - cfa: ConstantFlowAgreementV1Helper | undefined; - ida: InstantDistributionAgreementV1Helper | undefined; - utils: Utils | undefined; - _gasMetering: GasMeter | undefined; - - initialize(): Promise; - isSuperTokenListed(superTokenKey: string): Promise; - loadToken(tokenKey: string): Promise; - createERC20Wrapper(tokenInfo: any, - { superTokenSymbol, superTokenName, from, upgradability }: { - superTokenSymbol?: string, - superTokenName?: string, - from?: string, - upgradability?: string - } - ): Promise; - user({ address, token, options }: { - address: string; - token: string; - options?: any; - }): User; - batchCall(calls: any): any; - subgraphQuery(query: string): Promise; - getPastEvents(contract: any, eventName: any, filter: any, options: any): Promise; - _pushTxForGasReport(tx: Record, actionName: string): void; - generateGasReport(name: string): void; -} diff --git a/packages/js-sdk/src/Framework.js b/packages/js-sdk/src/Framework.js deleted file mode 100644 index 9022db5f44..0000000000 --- a/packages/js-sdk/src/Framework.js +++ /dev/null @@ -1,501 +0,0 @@ -const loadContracts = require("./loadContracts"); -const getConfig = require("./getConfig"); -const GasMeter = require("./utils/gasMetering/gasMetering"); -const {getErrorResponse} = require("./utils/error"); -const {isAddress, validateAddress} = require("./utils/general"); -const {batchCall} = require("./batchCall"); -const ConstantFlowAgreementV1Helper = require("./ConstantFlowAgreementV1Helper"); -const InstantDistributionAgreementV1Helper = require("./InstantDistributionAgreementV1Helper"); -const fetch = require("node-fetch"); - -const User = require("./User"); - -const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000"; - -/** - * @dev Superfluid Framework class - */ -module.exports = class Framework { - /** - * @dev Create new Superfluid framework object - * @param {string} options.version (Default: v1) protocol release version. - * @param {boolean} options.isTruffle (Default: false) if the framework is used within truffle environment. - * @param {Web3} options.web3 Injected web3 instance (version has to be 1.x) - * - * @param {Array} options.additionalContracts (Optional) additional contracts to be loaded - * @param {string[]} options.tokens (Optional) Tokens to be loaded with a list of (in order of preference): - * - super chain-native token symbol (see getConfig.js), - * - underlying token resolver key (tokens.{KEY}), - * - super token key (supertokens.{protocol_release_version}.{KEY}) - * @param {bool} options.loadSuperNativeToken Load super native token (e.g. ETHx) if possible - * @param {Function} options.contractLoader (Optional) alternative contract loader function - * - * @param {string} options.resolverAddress force resolver address - * @param {string} options.gasReportType output type for gas reporting. Currently HTML only - * @return {Framework} The Framework object - * - * NOTE: You should call async function Framework.initialize to initialize the object. - */ - constructor(options) { - this._options = options; - this.version = options.version || "v1"; - - if (options.isTruffle && options.web3) - throw Error( - "@superfluid-finance/js-sdk: Flag 'isTruffle' cannot be 'true' when using a web3 instance." - ); - if (!options.isTruffle && !options.web3) - throw Error( - "@superfluid-finance/js-sdk: You must provide a web3 instance." - ); - - this.web3 = options.isTruffle ? global.web3 : options.web3; - - if (options.gasReportType) { - if ( - options.gasReportType !== "HTML" && - options.gasReportType !== "JSON" - ) { - throw new Error( - "Unsuported gas report type: " + options.gasReportType - ); - } - console.debug("Enabling gas report type:", options.gasReportType); - this._gasReportType = options.gasReportType; - } - } - - /** - * @dev Initialize the framework object - * @return {Promise} - */ - async initialize() { - console.log("Initializing Superfluid Framework..."); - // NOTE: querying network type first, - // Somehow web3.eth.net.getId may send bogus number if this was not done first - // It could be a red-herring issue, but it makes it more stable. - this.networkType = await this.web3.eth.net.getNetworkType(); - this.networkId = await this.web3.eth.net.getId(); - this.chainId = await this.web3.eth.getChainId(); - - console.log("version", this.version); - console.log("networkType", this.networkType); - console.log("networkId", this.networkId); - console.log("chainId", this.chainId); - - this.config = getConfig(this.chainId, this.version); - - this.contracts = await loadContracts({ - isTruffle: this._options.isTruffle, - web3: this._options.web3, - from: this._options.from, - additionalContracts: this._options.additionalContracts, - contractLoader: this._options.contractLoader, - networkId: this.networkId, - }); - - const resolverAddress = - this._options.resolverAddress || this.config.resolverAddress; - console.debug("Resolver at", resolverAddress); - this.resolver = await this.contracts.IResolver.at(resolverAddress); - - // get framework loader and load - this.loader = await this.contracts.SuperfluidLoader.at( - await this.resolver.get("SuperfluidLoader-v1") - ); - console.debug("Superfluid Loader v1", this.loader.address); - console.debug("Loading framework with release version", this.version); - const loaderResult = await this.loader.loadFramework(this.version); - - console.debug( - "Superfluid host contract: TruffleContract .host", - loaderResult.superfluid - ); - console.debug( - "SuperTokenFactory address:", - loaderResult.superTokenFactory - ); - console.debug( - "ConstantFlowAgreementV1: TruffleContract .agreements.cfa | Helper .cfa", - loaderResult.agreementCFAv1 - ); - console.debug( - "InstantDistributionAgreementV1: TruffleContract .agreements.ida | Helper .ida", - loaderResult.agreementIDAv1 - ); - - this.agreements = {}; - this.tokens = {}; - this.superTokens = {}; - - // load agreement classes - [this.host, this.agreements.cfa, this.agreements.ida] = - await Promise.all([ - // load host - this.contracts.ISuperfluid.at(loaderResult.superfluid), - // load agreements - this.contracts.IConstantFlowAgreementV1.at( - loaderResult.agreementCFAv1 - ), - this.contracts.IInstantDistributionAgreementV1.at( - loaderResult.agreementIDAv1 - ), - // load tokens - ...[ - ...(this._options.tokens ? this._options.tokens : []), - ...(this._options.loadSuperNativeToken && - this.config.nativeTokenSymbol - ? [this.config.nativeTokenSymbol] - : []), - ].map(this.loadToken.bind(this)), - ]); - - // load agreement helpers - this.cfa = new ConstantFlowAgreementV1Helper(this); - this.ida = new InstantDistributionAgreementV1Helper(this); - - this.utils = new (require("./Utils"))(this); - if (this._gasReportType) { - const defaultGasPrice = await this.web3.eth.getGasPrice(); - this._gasMetering = new GasMeter( - this.web3, - this._gasReportType, - defaultGasPrice - ); - } - console.log("Superfluid Framework initialized."); - } - - /** - * @dev Load additional token using resolver - * @param {String} superTokenKey super token key used to query resolver - */ - async isSuperTokenListed(superTokenKey) { - if (!isAddress(superTokenKey)) { - const superTokenAddress = await this.resolver.get( - `supertokens.${this.version}.${superTokenKey}` - ); - return superTokenAddress !== ZERO_ADDRESS; - } else { - try { - const superToken = await this.contracts.ISuperToken.at( - superTokenKey - ); - const symbol = await superToken.symbol(); - const superTokenAddress = await this.resolver.get( - `supertokens.${this.version}.${symbol}` - ); - return ( - superToken.address.toLowerCase() == - superTokenAddress.toLowerCase() - ); - } catch (error) { - console.warn("Invalid super token address", superTokenKey); - return false; - } - } - } - - /** - * @dev Load additional token using resolver - * @param {String} tokenKey token key used to query resolver (in order of preference): - * - super chain-native token symbol (see getConfig.js), - * - underlying token resolver key (tokens.{KEY}), - * - super token key (supertokens.{protocol_release_version}.{KEY}) - * - super token address - * @param options.skipTokens skips .tokens object, to save some network calls - * - * As a result: - * - sf.tokens[tokenKey] and sf.superTokens[tokenKey] is the loaded SuperToken Object. - * - Additionally, superTokenObject.underlyingToken is the underlying token object. - * - If tokenKey is a super token address, it is normalized to lower case. - */ - async loadToken(tokenKey, {skipTokens} = {}) { - let underlyingToken; - let superTokenKey; - let superTokenContractType; - let superTokenAddress; - let superToken; - let superTokenCustomType = ""; - // validate if the underlying token matches its corresponding - // listed super token underlying token - let doValidateUnderlyingToken = false; - let isLoadingByAddress = false; - - if (!isAddress(tokenKey)) { - if ( - tokenKey === this.config.nativeTokenSymbol || - tokenKey === this.config.nativeTokenSymbol + "x" - ) { - // it is the same as native token symbol (or plus "x"), we assume it is a SETH - superTokenKey = this.config.nativeTokenSymbol + "x"; - superTokenContractType = this.contracts.ISETH; - superTokenCustomType = "SETH"; - } else { - // first check if tokenKey is symbol of a listed non-super token - const tokenAddress = await this.resolver.get( - `tokens.${tokenKey}` - ); - if (tokenAddress !== ZERO_ADDRESS) { - // if it is, we assume its ERC20 super token wrapper is postfixed with "x" - underlyingToken = - await this.contracts.ERC20WithTokenInfo.at( - tokenAddress - ); - if (!skipTokens) this.tokens[tokenKey] = underlyingToken; - console.debug( - `${tokenKey}: ERC20WithTokenInfo .tokens["${tokenKey}"]`, - tokenAddress - ); - superTokenKey = tokenKey + "x"; - doValidateUnderlyingToken = true; - } else { - // if it is not, then we assume it is a listed super token - superTokenKey = tokenKey; - } - superTokenContractType = this.contracts.ISuperToken; - } - - // load super token - superTokenAddress = await this.resolver.get( - `supertokens.${this.version}.${superTokenKey}` - ); - if (superTokenAddress === ZERO_ADDRESS) { - throw new Error(`Super Token for ${tokenKey} cannot be found`); - } - } else { - superTokenAddress = superTokenKey = tokenKey.toLowerCase(); - superTokenContractType = this.contracts.ISuperToken; - isLoadingByAddress = true; - } - - superToken = await superTokenContractType.at(superTokenAddress); - superToken.superTokenCustomType = superTokenCustomType; - if (!skipTokens) this.tokens[superTokenKey] = superToken; - this.superTokens[superTokenKey] = superToken; - let underlyingTokenAddress = await superToken.getUnderlyingToken.call(); - if (doValidateUnderlyingToken) { - if (underlyingTokenAddress !== ZERO_ADDRESS) { - // if underlying token is not undefined and not equal to getUnderlyingToken() returned address - if ( - underlyingTokenAddress.toLowerCase() !== - underlyingToken.address.toLowerCase() - ) { - throw new Error( - `Underlying token addresses are different for ${tokenKey}` - ); - } - } else { - throw new Error(`Unexpected underlying token for ${tokenKey}`); - } - } - - // if underlying token is still null or undefined, load it - if (!underlyingToken) { - if (underlyingTokenAddress !== ZERO_ADDRESS) { - underlyingToken = await this.contracts.ERC20WithTokenInfo.at( - underlyingTokenAddress - ); - if (!isLoadingByAddress && !skipTokens) { - // do not pollute the tokens namespace if loading a potentially - // unlisted token - const symbol = await underlyingToken.symbol(); - this.tokens[symbol] = underlyingToken; - } - } - } - superToken.underlyingToken = underlyingToken; - - console.debug( - `${superTokenKey}: ISuperToken .tokens["${superTokenKey}"] ${superTokenCustomType}`, - superToken.address - ); - } - - /** - * @dev Create the ERC20 wrapper from underlying token - * @param {Any} tokenInfo the TokenInfo contract object to the underlying token - * @param {string} superTokenName (optional) overriding superTokenName - * @param {string} superTokenSymbol (optional) overriding superTokenSymbol - * @param {address} from (optional) send transaction from - * @param {address} upgradability (optional) send transaction from - * @return {Promise} web3 transaction object - */ - async createERC20Wrapper( - tokenInfo, - {superTokenSymbol, superTokenName, from, upgradability} = {} - ) { - const tokenName = await tokenInfo.name.call(); - const tokenSymbol = await tokenInfo.symbol.call(); - superTokenName = superTokenName || `Super ${tokenName}`; - superTokenSymbol = superTokenSymbol || `${tokenSymbol}x`; - const factory = await this.contracts.ISuperTokenFactory.at( - await this.host.getSuperTokenFactory() - ); - upgradability = - typeof upgradability === "undefined" ? 1 : upgradability; - const tx = await factory.createERC20Wrapper( - tokenInfo.address, - upgradability, - superTokenName, - superTokenSymbol, - ...((from && [{from}]) || []) // don't mind this silly js stuff, thanks to web3.js - ); - this._pushTxForGasReport(tx, "createERC20Wrapper"); - const wrapperAddress = tx.logs[0].args.token; - const u = ["Non upgradable", "Semi upgrdable", "Full upgradable"][ - upgradability - ]; - console.log( - `${u} super token ${superTokenSymbol} created at ${wrapperAddress}` - ); - const superToken = await this.contracts.ISuperToken.at(wrapperAddress); - superToken.tx = tx; - return superToken; - } - - /** - * @dev Create an user object - * @param {address} address Account address Address of the user - * @param {token} token Default token for the user - * @param {options} options Additional options for the user. - * - * NOTE: - * - See User class for more details about the options - */ - user({address, token, options}) { - try { - if (!address) throw "Please provide an address"; - if (!token) throw "Please provide a token"; - validateAddress(address); - // TODO: validate token - return new User({sf: this, address, token, options}); - } catch (e) { - throw getErrorResponse(e, "Framework", "user"); - } - } - - /** - * @dev Create a batch call - * @param {object[]} calls Array of batch call descriptions. - * - * NOTE: - * The batch call description is defined in batchCall.js, for lack of better - * documentation, please read the source code of it. - */ - batchCall(calls) { - return this.host.batchCall(batchCall(calls)); - } - - /** - * @dev Make a subgraph query - * @param {string} query The subgraph query body - * @return {Promise} - */ - async subgraphQuery(query) { - const response = await fetch(this.config.subgraphQueryEndpoint, { - method: "POST", - body: JSON.stringify({query}), - headers: {"Content-Type": "application/json"}, - }); - if (response.ok) { - const result = JSON.parse(await response.text()); - if (!result.errors) { - return result.data; - } else { - throw new Error( - "subgraphQuery errors: " + JSON.stringify(result.errors) - ); - } - } else throw new Error("subgraphQuery failed: " + response.text()); - } - - /** - * @dev Get past events thourhg either web3 or subgraph - * @param {Contract} contract The contract object where the event is emitted - * @param {string} eventName The event name - * @param {object} filter Event filtering - * @return {Promise} - */ - async getPastEvents(contract, eventName, filter = {}, {forceWeb3} = {}) { - function lcfirst(str) { - return str.replace(/[A-Z]+/, (i) => i.toLowerCase()); - } - - const eventABI = contract.abi.filter((i) => i.name === eventName)[0]; - if (!eventABI) throw new Error("Event not found"); - - if (this.config.subgraphQueryEndpoint && !forceWeb3) { - const entityName = lcfirst(`${eventName}Events`); - const fields = eventABI.inputs.map((i) => i.name); - const where = eventABI.inputs - .filter((i) => i.indexed) - .map((i) => { - if (i.name in filter) { - if (filter[i.name] !== null) { - return `${i.name} : "${filter[i.name]}"`; - } else { - return null; - } - } else return null; - }) - .filter((i) => i !== null) - .join(","); - const events = await this.subgraphQuery(`{ - ${entityName} (first: 1000, where: { ${where} }) { - transactionHash - blockNumber - ${fields.join("\n")} - } - }`); - return events[entityName]; - } else if (contract.getPastEvents) { - const result = await contract.getPastEvents(eventName, { - fromBlock: 0, - toBlock: "latest", - filter, - }); - return result.map((i) => ({ - transactionHash: i.transactionHash, - blockNumber: i.blockNumber, - ...i.args, - })); - } else if (contract.queryFilter) { - const filterArgs = eventABI.inputs - .filter((i) => i.indexed) - .map((i) => (i.name in filter ? filter[i.name] : null)); - console.log("filterArgs", filterArgs); - const result = await contract.queryFilter( - contract.filters[eventName](...filterArgs), - 0, - "latest" - ); - return result.map((i) => ({ - transactionHash: i.transactionHash, - blockNumber: i.blockNumber, - ...i.args, - })); - } else throw new Error("No backend found for getPastEvents"); - } - - /** - * @dev call to add a tx in the gas report. Does nothing if gas report type is not set. - * @param {tx oject} tx as returned by truffleContract action - * @param {str} actionName action title for row in report - */ - _pushTxForGasReport(tx, actionName) { - this._gasMetering ? this._gasMetering.pushTx(tx, actionName) : null; - } - - /** - * @dev generate gas report with transactions pushed until this call - * @param {str} name file name for gas report - * @throws if gas report type was not indicated in constructor - */ - generateGasReport(name) { - if (!this._gasMetering) { - throw new Error("No gas metering configured"); - } - this._gasMetering.generateReport(name); - } -}; diff --git a/packages/js-sdk/src/InstantDistributionAgreementV1Helper.d.ts b/packages/js-sdk/src/InstantDistributionAgreementV1Helper.d.ts deleted file mode 100644 index 1634354b5a..0000000000 --- a/packages/js-sdk/src/InstantDistributionAgreementV1Helper.d.ts +++ /dev/null @@ -1,413 +0,0 @@ -import type { Transaction } from "web3-core"; -import type { Framework } from "./Framework"; -import type { LoadedContract } from "./loadContracts"; -import type BN from 'bn.js'; -import { GasOptions } from "./types/gasOptions"; - -// comes from getIndex in IDAv1 contract, -// then passed into _sanitizeIndexData -// then returned from getIndex -export interface IndexData { - exist: boolean; - indexValue: string; - totalUnitsApproved: string; - totalUnitsPending: string; -} - -// comes from getSubscription in IDAv1 contract, -// then passed into _sanitizeSubscriptionData -// then returned from getSubscription -export interface SubscriptionData { - exist: boolean; - approved: boolean; - units: string; - pendingDistribution: string -} - -// comes from listSubscriptions in IDAv1 contract, -// then passed into __sanitizeSubscriptionInfo -// then returned from listSubscriptions -export type SubscriptionInfoList = { - publisher: string; - indexId: number; - units: string; -}[] - -// returned from listSubscribers after mapping -export type SubscriberList = { - subscriber: string; - units: string; -}[] - -// method option params -// useful for projects wrapping the SDK -export interface CreateIndexOptions { - superToken: string; - publisher: string; - indexId: number; - userData?: string; - onTransaction?: () => any; - gasOptions?: GasOptions; -} - -export interface DistributeOptions { - superToken: string; - publisher: string; - indexId: number; - amount: string; - userData?: string; - onTransaction?: () => any; - gasOptions?: GasOptions; -} - -export interface UpdateIndexOptions { - superToken: string; - publisher: string; - indexId: number; - indexValue: string; - userData?: string; - onTransaction?: () => any; - gasOptions?: GasOptions; -} - -export interface UpdateSubscriptionOptions { - superToken: string; - publisher: string; - indexId: number; - subscriber: string; - units: string; - userData?: string; - onTransaction?: () => any; - gasOptions?: GasOptions; -} - -export interface ApproveSubscriptionOptions { - superToken: string; - publisher: string; - indexId: number; - subscriber: string; - userData?: string; - onTransaction?: () => any; - gasOptions?: GasOptions; -} - -export interface RevokeSubscriptionOptions { - superToken: string; - indexId: number; - publisher: string; - subscriber: string; - userData?: string; - onTransaction?: () => any; - gasOptions?: GasOptions; -} - -export interface DeleteSubscriptionOptions { - superToken: string; - indexId: number; - publisher: string; - subscriber: string; - sender: string; - userData?: string; - onTransaction?: () => any; - gasOptions?: GasOptions; -} - -export interface GetSubscriptionOptions { - superToken: string; - publisher: string; - indexId: number; - subscriber: string; -} - -export interface ClaimOptions { - superToken: string; - publisher: string; - indexId: number; - subscriber: string; - sender: string; - userData?: string; - onTransaction?: () => any; - gasOptions?: GasOptions; -} - -export interface GetIndexOptions { - superToken: string; - publisher: string; - indexId: number; -} - -export interface ListIndicesOptions { - superToken: string; - publisher: string; -} - -export interface ListSubcribersOptions { - superToken: string; - publisher: string; - indexId: number; -} - -export interface ListSubscriptionsOptions { - superToken: string; - subscriber: string; -} - -export declare class InstantDistributionAgreementV1Helper { - static _sanitizeIndexData({ exist, indexValue, totalUnitsApproved, totalUnitsPending, }: { - exist: boolean; - indexValue: number | BN; - totalUnitsApproved: number | BN; - totalUnitsPending: number | BN; - }): IndexData; - static _sanitizeSubscriptionData({ exist, approved, units, pendingDistribution, }: { - exist: boolean; - approved: boolean; - units: number | BN; - pendingDistribution: number | BN; - }): SubscriptionData; - static _sanitizeSubscriptionInfo({ publishers, indexIds, unitsList }: { - publishers: any[]; - indexIds: number; // the contract returns uint32, the SDK wraps it in Number(), - unitsList: number[] | BN[]; - }): SubscriptionInfoList; - /** - * @dev Create new helper class - * @param {Framework} sf Superfluid Framework object - * - * NOTE: You should first call async function Framework.initialize to initialize the object. - */ - constructor(sf: Framework); - _sf: Framework; - _ida: LoadedContract; - /** - * @dev Create a new index - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @param {GasOptions} gasOptions pass network gas parameters - * @return {Promise} web3 transaction object - */ - createIndex({ - superToken, - publisher, - indexId, - userData, - onTransaction, - gasOptions, - }: CreateIndexOptions): Promise; -/** - * @dev Distribute tokens to an index - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @param {BN} amount Amount to be distributed - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @return {Promise} web3 transaction object - * @param {GasOptions} gasOptions pass network gas parameters - */ - distribute({ - superToken, - publisher, - indexId, - amount, - userData, - onTransaction, - gasOptions, - }: DistributeOptions): Promise; -/** - * @dev Update the value of a index - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @param {GasOptions} gasOptions pass network gas parameters - * @return {Promise} web3 transaction object - * - * NOTE: - * it has the same effect as doing distribute, but closer to the low level data structure - * of the index. - */ - updateIndex({ - superToken, - publisher, - indexId, - indexValue, - userData, - onTransaction, - gasOptions, - }: UpdateIndexOptions): Promise; -/** - * @dev Update number of units of a subscription by the publisher of the index - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @param {addressParam} subscriber Subscriber of the index - * @param {BN} units Units of the subscription - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @param {GasOptions} gasOptions pass network gas parameters - * @return {Promise} web3 transaction object - */ - updateSubscription({ - superToken, - publisher, - indexId, - subscriber, - units, - userData, - onTransaction, - gasOptions, - }: UpdateSubscriptionOptions): Promise; -/** - * @dev Approve the subscription by a subscriber of the index - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @param {addressParam} subscriber Subscriber of the index - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @param {GasOptions} gasOptions pass network gas parameters - * @return {Promise} web3 transaction object - * - * NOTE: - * By approving, the subscriber can use the balance the moment the publishder distributes - * tokens without doing the extra claim step. - */ - approveSubscription({ - superToken, - publisher, - indexId, - subscriber, - userData, - onTransaction, - gasOptions, - }: ApproveSubscriptionOptions): Promise; -/** - * @dev Revoke the subscription by a subscriber of the index - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @param {addressParam} subscriber Subscriber of the index - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @param {GasOptions} gasOptions pass network gas parameters - * @return {Promise} web3 transaction object - * - * NOTE: - * By revoking, the subscriber will need to do claim step in order to get the tokens. - */ - revokeSubscription({ - superToken, - indexId, - publisher, - subscriber, - userData, - onTransaction, - gasOptions, - }: RevokeSubscriptionOptions): Promise; -/** - * @dev Delete the subscription by the publisher or a subscriber of the index - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @param {addressParam} subscriber Subscriber of the index - * @param {addressParam} sender Publisher or subscriber of the index - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @param {GasOptions} gasOptions pass network gas parameters - * @return {Promise} web3 transaction object - * - * NOTE: - * It means both revoking and clear the units of a subscription. - */ - deleteSubscription({ - superToken, - indexId, - publisher, - subscriber, - sender, - userData, - onTransaction, - gasOptions, - }: DeleteSubscriptionOptions): Promise; - /** - * @dev Get details of a subscription - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @param {addressParam} subscriber Subscriber of the index - * @return {Promise} Subscription data - */ - getSubscription({ - superToken, - publisher, - indexId, - subscriber - }: GetSubscriptionOptions): Promise; -/** - * @dev Claim distributions to a subscriber of the index by anyone. - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @param {addressParam} subscriber Subscriber of the index - * @param {addressParam} sender Any account to claim the distribution for the subscriber - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @param {GasOptions} gasOptions pass network gas parameters - * @return {Promise} web3 transaction object - * - * NOTE: - * If the subscriber has not approved the subscription, anyone can claim the distribution for him. - */ - claim({ - superToken, - publisher, - indexId, - subscriber, - sender, - userData, - onTransaction, - gasOptions, - }: ClaimOptions): Promise; - /** - * @dev Get details of an index - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @return {Promise} Subscription data - */ - getIndex({ - superToken, - publisher, - indexId - }: GetIndexOptions): Promise; - /** - * @dev List indices of a publisher - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @return {Promise} Subscription data - */ - listIndices({ - superToken, - publisher - }: ListIndicesOptions): Promise; - /** - * @dev List subscribers of an index - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @return {Promise} Subscription data - */ - listSubcribers({ - superToken, - publisher, - indexId - }: ListSubcribersOptions): Promise; - /** - * @dev List subscriptions of an account - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @return {Promise} Subscription data - */ - listSubscriptions({ - superToken, - subscriber - }: ListSubscriptionsOptions): Promise; -} diff --git a/packages/js-sdk/src/InstantDistributionAgreementV1Helper.js b/packages/js-sdk/src/InstantDistributionAgreementV1Helper.js deleted file mode 100644 index e75a6ffba9..0000000000 --- a/packages/js-sdk/src/InstantDistributionAgreementV1Helper.js +++ /dev/null @@ -1,604 +0,0 @@ -const autoBind = require("auto-bind"); -const {completeTransaction} = require("./utils/general"); - -/** - * @dev Instant distribution agreement v1 helper class - */ -module.exports = class InstantDistributionAgreementV1Helper { - /** - * @dev Create new helper class - * @param {Framework} sf Superfluid Framework object - * - * NOTE: You should first call async function Framework.initialize to initialize the object. - */ - constructor(sf) { - this._sf = sf; - this._ida = sf.agreements.ida; - autoBind(this); - } - - /** - * @dev Create a new index - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @return {Promise} web3 transaction object - */ - async createIndex({ - superToken, - publisher, - indexId, - userData = "0x", - gasOptions = {}, - onTransaction = () => null, - }) { - const superTokenNorm = await this._sf.utils.normalizeTokenParam( - superToken - ); - const publisherNorm = await this._sf.utils.normalizeAddressParam( - publisher - ); - const tx = await completeTransaction({ - sf: this._sf, - args: [ - this._ida.address, - this._ida.contract.methods - .createIndex(superTokenNorm, indexId, "0x") - .encodeABI(), - userData, - ], - sender: publisherNorm, - method: this._sf.host.callAgreement, - gasOptions: { - maxPriorityFeePerGas: gasOptions.maxPriorityFeePerGas, - maxFeePerGas: gasOptions.maxFeePerGas, - }, - onTransaction, - }); - console.debug("Index created."); - return tx; - } - - /** - * @dev Get details of an index - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @return {Promise} Subscription data - */ - async getIndex({superToken, publisher, indexId}) { - const superTokenNorm = await this._sf.utils.normalizeTokenParam( - superToken - ); - const publisherNorm = await this._sf.utils.normalizeAddressParam( - publisher - ); - const result = await this._ida.getIndex( - superTokenNorm, - publisherNorm, - indexId - ); - return this.constructor._sanitizeIndexData(result); - } - - /** - * @dev List indices of a publisher - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @return {Promise} Subscription data - */ - async listIndices({superToken, publisher}) { - const superTokenNorm = await this._sf.utils.normalizeTokenParam( - superToken - ); - const publisherNorm = await this._sf.utils.normalizeAddressParam( - publisher - ); - return ( - await this._sf.getPastEvents(this._ida, "IndexCreated", { - token: superTokenNorm, - publisher: publisherNorm, - }) - ).map((e) => Number(e.indexId.toString())); - } - - /** - * @dev Distribute tokens to an index - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @param {BN} amount Amount to be distributed - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @return {Promise} web3 transaction object - */ - async distribute({ - superToken, - publisher, - indexId, - amount, - userData = "0x", - gasOptions = {}, - onTransaction = () => null, - }) { - const superTokenNorm = await this._sf.utils.normalizeTokenParam( - superToken - ); - const publisherNorm = await this._sf.utils.normalizeAddressParam( - publisher - ); - const tx = await completeTransaction({ - sf: this._sf, - args: [ - this._ida.address, - this._ida.contract.methods - .distribute(superTokenNorm, indexId, amount, "0x") - .encodeABI(), - userData, - ], - sender: publisherNorm, - method: this._sf.host.callAgreement, - gasOptions: { - maxPriorityFeePerGas: gasOptions.maxPriorityFeePerGas, - maxFeePerGas: gasOptions.maxFeePerGas, - }, - onTransaction, - }); - console.debug("Distribution complete."); - return tx; - } - - /** - * @dev Update the value of a index - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @return {Promise} web3 transaction object - * - * NOTE: - * it has the same effect as doing distribute, but closer to the low level data structure - * of the index. - */ - async updateIndex({ - superToken, - publisher, - indexId, - indexValue, - userData = "0x", - gasOptions = {}, - onTransaction = () => null, - }) { - const superTokenNorm = await this._sf.utils.normalizeTokenParam( - superToken - ); - const publisherNorm = await this._sf.utils.normalizeAddressParam( - publisher - ); - const tx = await completeTransaction({ - sf: this._sf, - args: [ - this._ida.address, - this._ida.contract.methods - .updateIndex(superTokenNorm, indexId, indexValue, "0x") - .encodeABI(), - userData, - ], - sender: publisherNorm, - method: this._sf.host.callAgreement, - gasOptions: { - maxPriorityFeePerGas: gasOptions.maxPriorityFeePerGas, - maxFeePerGas: gasOptions.maxFeePerGas, - }, - onTransaction, - }); - console.debug("Index updated."); - return tx; - } - - /** - * @dev Update number of units of a subscription by the publisher of the index - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @param {addressParam} subscriber Subscriber of the index - * @param {BN} units Units of the subscription - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @return {Promise} web3 transaction object - */ - async updateSubscription({ - superToken, - publisher, - indexId, - subscriber, - units, - userData = "0x", - gasOptions = {}, - onTransaction = () => null, - }) { - const superTokenNorm = await this._sf.utils.normalizeTokenParam( - superToken - ); - const publisherNorm = await this._sf.utils.normalizeAddressParam( - publisher - ); - const subscriberNorm = await this._sf.utils.normalizeAddressParam( - subscriber - ); - const tx = await completeTransaction({ - sf: this._sf, - args: [ - this._ida.address, - this._ida.contract.methods - .updateSubscription( - superTokenNorm, - indexId, - subscriberNorm, - units, - "0x" - ) - .encodeABI(), - userData, - ], - sender: publisherNorm, - method: this._sf.host.callAgreement, - gasOptions: { - maxPriorityFeePerGas: gasOptions.maxPriorityFeePerGas, - maxFeePerGas: gasOptions.maxFeePerGas, - }, - onTransaction, - }); - console.debug("Subscription updated."); - return tx; - } - - /** - * @dev Approve the subscription by a subscriber of the index - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @param {addressParam} subscriber Subscriber of the index - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @return {Promise} web3 transaction object - * - * NOTE: - * By approving, the subscriber can use the balance the moment the publishder distributes - * tokens without doing the extra claim step. - */ - async approveSubscription({ - superToken, - publisher, - indexId, - subscriber, - userData = "0x", - gasOptions = {}, - onTransaction = () => null, - }) { - const superTokenNorm = await this._sf.utils.normalizeTokenParam( - superToken - ); - const publisherNorm = await this._sf.utils.normalizeAddressParam( - publisher - ); - const subscriberNorm = await this._sf.utils.normalizeAddressParam( - subscriber - ); - const tx = await completeTransaction({ - sf: this._sf, - args: [ - this._ida.address, - this._ida.contract.methods - .approveSubscription( - superTokenNorm, - publisherNorm, - indexId, - "0x" - ) - .encodeABI(), - userData, - ], - sender: subscriberNorm, - method: this._sf.host.callAgreement, - gasOptions: { - maxPriorityFeePerGas: gasOptions.maxPriorityFeePerGas, - maxFeePerGas: gasOptions.maxFeePerGas, - }, - onTransaction, - }); - console.debug("Subscription approved."); - return tx; - } - - /** - * @dev Revoke the subscription by a subscriber of the index - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @param {addressParam} subscriber Subscriber of the index - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @return {Promise} web3 transaction object - * - * NOTE: - * By revoking, the subscriber will need to do claim step in order to get the tokens. - */ - async revokeSubscription({ - superToken, - indexId, - publisher, - subscriber, - userData = "0x", - gasOptions = {}, - onTransaction = () => null, - }) { - const superTokenNorm = await this._sf.utils.normalizeTokenParam( - superToken - ); - const publisherNorm = await this._sf.utils.normalizeAddressParam( - publisher - ); - const subscriberNorm = await this._sf.utils.normalizeAddressParam( - subscriber - ); - const tx = await completeTransaction({ - sf: this._sf, - args: [ - this._ida.address, - this._ida.contract.methods - .revokeSubscription( - superTokenNorm, - publisherNorm, - indexId, - "0x" - ) - .encodeABI(), - userData, - ], - sender: subscriberNorm, - method: this._sf.host.callAgreement, - gasOptions: { - maxPriorityFeePerGas: gasOptions.maxPriorityFeePerGas, - maxFeePerGas: gasOptions.maxFeePerGas, - }, - onTransaction, - }); - console.debug("Subscription revoked."); - return tx; - } - - /** - * @dev Delete the subscription by the publisher or a subscriber of the index - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @param {addressParam} subscriber Subscriber of the index - * @param {addressParam} sender Publisher or subscriber of the index - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @return {Promise} web3 transaction object - * - * NOTE: - * It means both revoking and clear the units of a subscription. - */ - async deleteSubscription({ - superToken, - indexId, - publisher, - subscriber, - sender, - userData = "0x", - gasOptions = {}, - onTransaction = () => null, - }) { - const superTokenNorm = await this._sf.utils.normalizeTokenParam( - superToken - ); - const publisherNorm = await this._sf.utils.normalizeAddressParam( - publisher - ); - const subscriberNorm = await this._sf.utils.normalizeAddressParam( - subscriber - ); - const senderNorm = await this._sf.utils.normalizeAddressParam(sender); - const tx = await completeTransaction({ - sf: this._sf, - args: [ - this._ida.address, - this._ida.contract.methods - .deleteSubscription( - superTokenNorm, - publisherNorm, - indexId, - subscriberNorm, - "0x" - ) - .encodeABI(), - userData, - ], - sender: senderNorm, - method: this._sf.host.callAgreement, - gasOptions: { - maxPriorityFeePerGas: gasOptions.maxPriorityFeePerGas, - maxFeePerGas: gasOptions.maxFeePerGas, - }, - onTransaction, - }); - console.debug("Subscription deleted."); - return tx; - } - - /** - * @dev Get details of a subscription - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @param {addressParam} subscriber Subscriber of the index - * @return {Promise} Subscription data - */ - async getSubscription({superToken, publisher, indexId, subscriber}) { - const superTokenNorm = await this._sf.utils.normalizeTokenParam( - superToken - ); - const publisherNorm = await this._sf.utils.normalizeAddressParam( - publisher - ); - const subscriberNorm = await this._sf.utils.normalizeAddressParam( - subscriber - ); - const result = await this._ida.getSubscription.call( - superTokenNorm, - publisherNorm, - indexId, - subscriberNorm - ); - return this.constructor._sanitizeSubscriptionData(result); - } - - /** - * @dev Claim distributions to a subscriber of the index by anyone. - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @param {addressParam} subscriber Subscriber of the index - * @param {addressParam} sender Any account to claim the distribution for the subscriber - * @param {Function} onTransaction function to be called when transaction hash has been generated - * @return {Promise} web3 transaction object - * - * NOTE: - * If the subscriber has not approved the subscription, anyone can claim the distribution for him. - */ - async claim({ - superToken, - publisher, - indexId, - subscriber, - sender, - userData = "0x", - gasOptions = {}, - onTransaction = () => null, - }) { - const superTokenNorm = await this._sf.utils.normalizeTokenParam( - superToken - ); - const publisherNorm = await this._sf.utils.normalizeAddressParam( - publisher - ); - const subscriberNorm = await this._sf.utils.normalizeAddressParam( - subscriber - ); - const senderNorm = await this._sf.utils.normalizeAddressParam(sender); - const tx = await completeTransaction({ - sf: this._sf, - args: [ - this._ida.address, - this._ida.contract.methods - .claim( - superTokenNorm, - publisherNorm, - indexId, - subscriberNorm, - "0x" - ) - .encodeABI(), - userData, - ], - sender: senderNorm, - method: this._sf.host.callAgreement, - gasOptions: { - maxPriorityFeePerGas: gasOptions.maxPriorityFeePerGas, - maxFeePerGas: gasOptions.maxFeePerGas, - }, - onTransaction, - }); - console.debug("Claim complete."); - return tx; - } - - /** - * @dev List subscribers of an index - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @return {Promise} Subscription data - */ - async listSubcribers({superToken, publisher, indexId}) { - const superTokenNorm = await this._sf.utils.normalizeTokenParam( - superToken - ); - const publisherNorm = await this._sf.utils.normalizeAddressParam( - publisher - ); - let updates; - updates = await this._sf.getPastEvents(this._ida, "IndexUnitsUpdated", { - token: superTokenNorm, - publisher: publisherNorm, - indexId, - }); - return Object.values( - updates.reduce((acc, i) => { - acc[i.subscriber] = i; - return acc; - }, {}) - ) - .filter((i) => i.units.toString() != "0") - .map((i) => ({ - subscriber: i.subscriber, - units: i.units.toString(), - })); - } - - /** - * @dev List subscriptions of an account - * @param {tokenParam} superToken SuperToken for the index - * @param {addressParam} publisher Publisher of the index - * @param {int} indexId ID of the index - * @return {Promise} Subscription data - */ - async listSubscriptions({superToken, subscriber}) { - const superTokenNorm = await this._sf.utils.normalizeTokenParam( - superToken - ); - const subscriberNorm = await this._sf.utils.normalizeAddressParam( - subscriber - ); - const result = await this._ida.listSubscriptions( - superTokenNorm, - subscriberNorm - ); - return this.constructor._sanitizeSubscriptionInfo(result); - } - - static _sanitizeIndexData({ - exist, - indexValue, - totalUnitsApproved, - totalUnitsPending, - }) { - return { - exist, - indexValue: indexValue.toString(), - totalUnitsApproved: totalUnitsApproved.toString(), - totalUnitsPending: totalUnitsPending.toString(), - }; - } - - static _sanitizeSubscriptionData({ - exist, - approved, - units, - pendingDistribution, - }) { - return { - exist, - approved, - units: units.toString(), - pendingDistribution: pendingDistribution.toString(), - }; - } - - static _sanitizeSubscriptionInfo({publishers, indexIds, unitsList}) { - return publishers.map((publisher, i) => ({ - publisher, - indexId: Number(indexIds[i].toString()), - units: unitsList[i].toString(), - })); - } -}; diff --git a/packages/js-sdk/src/User.d.ts b/packages/js-sdk/src/User.d.ts deleted file mode 100644 index 7f964c7b28..0000000000 --- a/packages/js-sdk/src/User.d.ts +++ /dev/null @@ -1,62 +0,0 @@ -import type { Framework } from './Framework'; -import type BN from 'bn.js'; -import type { Transaction } from 'web3'; -import type { Flow } from './ConstantFlowAgreementV1Helper'; -import type { Subscription } from './InstantDistributionAgreementV1Helper'; - -// params options types -export interface UserOptions { - sf: Framework; - address: string; - token: string; -} - -// specified User to avoid confusion with CFA CreateFlowOptions -export interface UserFlowOptions { - recipient: string; - flowRate: string; - userData?: string; - onTransaction?: ()=>any; - by?: string; -} - -export interface CreatePoolOptions { - poolId: number; -} - -export interface GiveSharesOptions { - recipient: string; - shares: number | BN; - poolId: number; -} - -export interface DistributeToPoolOptions { - poolId: number; - amount: number | BN; -} - -export interface UserDetails { - cfa: { - flows: FlowList - netFlow: string // numeric string - } - ida: { - subscriptions: Array; - } -} - -export declare class User { - constructor({ sf, address, token }: UserOptions); - sf: Framework; - address: string; - token: string; - details(): Promise; - flow({ - recipient, - flowRate, - ...options - }: UserFlowOptions): Promise; - createPool({ poolId: indexId }: CreatePoolOptions): Promise; - giveShares({ recipient, shares, poolId: indexId }: GiveSharesOptions): Promise; - distributeToPool({ poolId: indexId, amount }: DistributeToPoolOptions): Promise; -} diff --git a/packages/js-sdk/src/User.js b/packages/js-sdk/src/User.js deleted file mode 100644 index 26ec5b50bf..0000000000 --- a/packages/js-sdk/src/User.js +++ /dev/null @@ -1,174 +0,0 @@ -const {getErrorResponse} = require("./utils/error"); - -module.exports = class User { - /** - * @dev Create new Superfluid user object - * @param {Framework} sf Superfluid framework object. - * @param {string} address The EOA address of the user you want to create. - * @param {string} token The address of the supertoken you want to interact with. - */ - constructor({sf, address, token}) { - this.sf = sf; - this.address = address; - this.token = token; - } - - /** - * @dev Returns instantiated details regarding the users' cfa and ida data. - * @returns {object} top-level cfa property contains flows: Flow[] and netFlow: number - * top-level ida property contains subscriptions: Subscription[] - */ - async details() { - try { - const listFlows = this.sf.cfa.listFlows({ - superToken: this.token, - account: this.address, - }); - const getNewFlow = this.sf.cfa - .getNetFlow({ - superToken: this.token, - account: this.address, - }) - .then((x) => x.toString()); - const listSubscriptions = this.sf.ida.listSubscriptions({ - superToken: this.token, - subscriber: this.address, - }); - const [flows, netFlow, subscriptions] = await Promise.all([ - listFlows, - getNewFlow, - listSubscriptions, - ]); - return {cfa: {flows, netFlow}, ida: {subscriptions}}; - } catch (e) { - throw getErrorResponse(e, "user", "details"); - } - } - - /** - * @dev Allows you to create, update or delete a flow from the user you initialized. - * @param {string} recipient the recipient of the flow agreement - * @param {string} flowRate the agreed upon flowRate - * @param {object} options options taken by cfa (userData, onTransaction, by (deleteFlow only)) - * @returns {Promise} web3 transaction object or undefined on error - * NOTE: !0 in JS evaluates to true as 0 is a falsey value. We also stringify the flowRate, - * just in case the user somehow is able to input a number (using JS). - */ - async flow({recipient, flowRate, ...options}) { - try { - if (!recipient || flowRate == null || flowRate == undefined) - throw "You must provide a recipient and flowRate"; - if (typeof flowRate !== "string") - throw "You must provide flowRate as a string"; - const recipientAddress = recipient.address || recipient; - if (flowRate === "0") - return await this.sf.cfa.deleteFlow({ - superToken: this.token, - sender: this.address, - receiver: recipientAddress, - ...options, - }); - - const existingFlow = await this.sf.cfa.getFlow({ - superToken: this.token, - sender: this.address, - receiver: recipientAddress, - }); - if (existingFlow.flowRate !== "0") - return await this.sf.cfa.updateFlow({ - superToken: this.token, - sender: this.address, - receiver: recipientAddress, - flowRate, - ...options, - }); - return await this.sf.cfa.createFlow({ - superToken: this.token, - sender: this.address, - receiver: recipientAddress, - flowRate, - ...options, - }); - } catch (e) { - throw getErrorResponse(e, "user", "flow"); - } - } - - /** - * @dev Create an Index using the IDA. - * @param {number} poolId The id of the index. - * @returns {Promise} web3 transaction object or undefined on error - */ - async createPool({poolId: indexId}) { - try { - if (!indexId) throw "You must provide a poolId"; - const {exist} = await this.sf.ida.getIndex({ - superToken: this.token, - publisher: this.address, - indexId, - }); - if (exist) throw "This pool has already been created"; - - return await this.sf.ida.createIndex({ - superToken: this.token, - publisher: this.address, - indexId, - }); - } catch (e) { - throw getErrorResponse(e, "user", "createPool"); - } - } - - /** - * @dev Gives shares (units) to a recipient. - * @param {string} recipient The recipient of the shares. - * @param {number} shares The number of units the recipient will receive. - * @param {number} poolId The id of the index. - * @returns {Promise} web3 transaction object or undefined on error - */ - async giveShares({recipient, shares, poolId: indexId}) { - try { - if (!recipient || !shares || !indexId) - throw "You must provide a recipient, share amount, and poolId"; - const recipientAddress = recipient.address || recipient; - - const {exist} = await this.sf.ida.getIndex({ - superToken: this.token, - publisher: this.address, - indexId, - }); - if (!exist) throw "This pool has not been created yet"; - - return await this.sf.ida.updateSubscription({ - superToken: this.token, - publisher: this.address, - indexId, - subscriber: recipientAddress, - units: shares, - }); - } catch (e) { - throw getErrorResponse(e, "user", "giveShares"); - } - } - - /** - * @dev Distributes tokens to subscribers who are approved. - * @param {number} poolId The id of the index. - * @param {number} amount The amount of tokens to distribute. - * @returns {Promise} web3 transaction object or undefined on error - */ - async distributeToPool({poolId: indexId, amount}) { - try { - if (!indexId || !amount) - throw "You must provide a poolId and amount"; - return await this.sf.ida.distribute({ - superToken: this.token, - publisher: this.address, - indexId, - amount, - }); - } catch (e) { - throw getErrorResponse(e, "user", "distributeToPool"); - } - } -}; diff --git a/packages/js-sdk/src/Utils.d.ts b/packages/js-sdk/src/Utils.d.ts deleted file mode 100644 index 80646926d7..0000000000 --- a/packages/js-sdk/src/Utils.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { Framework } from "./Framework"; -import type BN from 'bn.js'; -export declare class Utils { - constructor(sf: Framework); - _sf: Framework; - normalizeTokenParam(param: string): string; - normalizeAddressParam(param: string): string; - normalizeFlowRateParam(param: BN|string): string; -} diff --git a/packages/js-sdk/src/Utils.js b/packages/js-sdk/src/Utils.js deleted file mode 100644 index 26d5627605..0000000000 --- a/packages/js-sdk/src/Utils.js +++ /dev/null @@ -1,20 +0,0 @@ -/** - * @dev Utility class - */ -module.exports = class Utils { - constructor(sf) { - this._sf = sf; - } - - normalizeTokenParam(param) { - return param; - } - - normalizeAddressParam(param) { - return param; - } - - normalizeFlowRateParam(param) { - return param.toString(); - } -}; diff --git a/packages/js-sdk/src/batchCall.d.ts b/packages/js-sdk/src/batchCall.d.ts deleted file mode 100644 index c04347c821..0000000000 --- a/packages/js-sdk/src/batchCall.d.ts +++ /dev/null @@ -1,93 +0,0 @@ -// TODO set batchCall return type -import type { Transaction } from 'web3-core' - -// ERC20 Approve/TransferFrom -type ERC20OperationType = 'ERC20_APPROVE'| 'ERC20_TRANSFER_FROM' | 1 | 2; -interface ERC20Operation { - type: ERC20OperationType - data: { - token: string - amount: string - spender: string - } -} - -// SuperToken Upgrade/Downgrade -type SuperTokenOperationType = 'SUPERTOKEN_UPGRADE' | 'SUPERTOKEN_DOWNGRADE' | 101 | 102; -interface SuperTokenOperation { - type: SuperTokenOperationType - data: { - token: string - amount: string - } -} - -// SuperToken Call Agreement -type SuperFluidCallAgreementType = 'SUPERFLUID_CALL_AGREEMENT' | 201; - -// Constant Flow Agreement -type CFAMethodType = - 'createFlow' | - 'updateFlow' | - 'deleteFlow' | - 'getFlow' | - 'getNetFlow' | - 'getAccountFlowInfo' | - 'getFlowEvents'; - -interface SuperTokenCFAData { - agreementType: 'CFA' - method: CFAMethodType - arguments: Array any)> -} - -// Instant Distribution Agreement -type IDAMethodType = - 'createIndex' | - 'distribute' | - 'updateIndex' | - 'updateSubscription' | - 'approveSubscription' | - 'revokeSubscription' | - 'deleteSubscription' | - 'getSubscription' | - 'claim' | - 'getIndex' | - 'listIndices' | - 'listSubcribers' | - 'listSubscriptions'; - -interface SuperTokenIDAData { - agreementType: 'IDA' - method: IDAMethodType - arguments: Array | (()=>any)> -} - -interface SuperFluidCallAgreement { - type: SuperFluidCallAgreementType - data: SuperTokenCFAData | SuperTokenIDAData -} - -// Call App Action -type CallAppActionType = 'CALL_APP_ACTION' | 202; -interface CallAppAction { - type: CallAppActionType - data: { - superApp: string - callData: string - } -} - -// SuperFluid Operation -// Combines superfluid ida/cfa type with call app action type -type SuperFluidOperation = SuperFluidCallAgreement | CallAppAction; - -export type Agreement = ERC20Operation | SuperTokenOperation | SuperFluidOperation; - -export var agreements: Array; - -// return set to 'any' for now -export function batchCall({ agreements, calls }: { - agreements: Array; - calls: Array; -}): any[][]; diff --git a/packages/js-sdk/src/batchCall.js b/packages/js-sdk/src/batchCall.js deleted file mode 100644 index e16c67fd0e..0000000000 --- a/packages/js-sdk/src/batchCall.js +++ /dev/null @@ -1,240 +0,0 @@ -const { - getErrorResponse, - getMissingArgumentError, - getBatchCallHelpText, -} = require("./utils/error"); -const {AbiCoder} = require("@ethersproject/abi"); - -const abiCoder = new AbiCoder(); - -const OPERATION_TYPES = { - ERC20_APPROVE: 1, - ERC20_TRANSFER_FROM: 2, - SUPERTOKEN_UPGRADE: 101, - SUPERTOKEN_DOWNGRADE: 102, - SUPERFLUID_CALL_AGREEMENT: 201, - CALL_APP_ACTION: 202, -}; - -const AGREEMENT_TYPES = { - CFA: "cfa", - IDA: "ida", -}; - -const parseERC20Operation = ({index, operationType, data}) => { - const {token, spender, sender, recipient, amount} = data; - if (!amount) - throw new Error( - getMissingArgumentError("amount", getBatchCallHelpText(index)) - ); - if (!token) - throw new Error( - getMissingArgumentError("token", getBatchCallHelpText(index)) - ); - - /** - * @dev ERC20.approve batch operation type - * Call spec: - * ISuperToken(target).operationApprove( - * abi.decode(data, (address spender, uint256 amount)) - * ) - */ - if (operationType === OPERATION_TYPES.ERC20_APPROVE) { - if (!spender) - throw new Error( - getMissingArgumentError("spender", getBatchCallHelpText(index)) - ); - return [ - operationType, - token, - abiCoder.encode(["address", "uint256"], [spender, amount]), - ]; - } - /** - * @dev ERC20.transferFrom batch operation type - * Call spec: - * ISuperToken(target).operationTransferFrom( - * abi.decode(data, (address sender, address recipient, uint256 amount) - * ) - */ - //assert(operationType === OPERATION_TYPES.ERC20_TRANSFER_FROM); - if (!sender) - throw new Error( - getMissingArgumentError("sender", getBatchCallHelpText(index)) - ); - return [ - operationType, - token, - abiCoder.encode( - ["address", "address", "uint256"], - [sender, recipient, amount] - ), - ]; -}; - -const parseSuperTokenOperation = ({index, operationType, data}) => { - const {amount, token} = data; - if (!amount) - throw new Error( - getMissingArgumentError("amount", getBatchCallHelpText(index)) - ); - if (!token) - throw new Error( - getMissingArgumentError("token", getBatchCallHelpText(index)) - ); - - /** - * @dev SuperToken.upgrade batch operation type - * Call spec: - * ISuperToken(target).operationUpgrade( - * abi.decode(data, (uint256 amount) - * ) - */ - /** - * @dev SuperToken.downgrade batch operation type - * Call spec: - * ISuperToken(target).operationDowngrade( - * abi.decode(data, (uint256 amount) - * ) - */ - return [operationType, token, abiCoder.encode(["uint256"], [amount])]; -}; - -const parseSuperFluidOperation = ({index, operationType, data}) => { - const { - superApp, - agreementType, - method, - arguments: args, - userData = "0x", - callData, - } = data; - /** - * @dev Superfluid.callAgreement batch operation type - * Call spec: - * callAgreement( - * ISuperAgreement(target)), - * abi.decode(data, (bytes calldata, bytes userdata) - * ) - */ - - if (operationType === OPERATION_TYPES.SUPERFLUID_CALL_AGREEMENT) { - if (!agreementType) - throw new Error( - getMissingArgumentError( - "agreementType", - getBatchCallHelpText(index) - ) - ); - if (!method) - throw new Error( - getMissingArgumentError("method", getBatchCallHelpText(index)) - ); - if (!args) - throw new Error( - getMissingArgumentError( - "arguments", - getBatchCallHelpText(index) - ) - ); - if (!Object.keys(AGREEMENT_TYPES).includes(agreementType)) - throw new Error( - `You provided an invalid agreementType${getBatchCallHelpText( - index - )}` - ); - - const agreementAddress = - this.agreements[AGREEMENT_TYPES[agreementType]].address; - const callData = this.agreements[ - AGREEMENT_TYPES[agreementType] - ].contract.methods[method](...args).encodeABI(); - return [ - operationType, - agreementAddress, - abiCoder.encode(["bytes", "bytes"], [callData, userData]), - ]; - } - /** - * @dev Superfluid.callAppAction batch operation type - * Call spec: - * callAppAction( - * ISuperApp(target)), - * data - * ) - */ - if (!superApp) - throw new Error( - getMissingArgumentError("superApp", getBatchCallHelpText(index)) - ); - if (!callData) - throw new Error( - getMissingArgumentError("callData", getBatchCallHelpText(index)) - ); - return [operationType, superApp, callData]; -}; - -const parse = ({index, type, data}) => { - try { - if (!type) - throw new Error( - getMissingArgumentError("type", getBatchCallHelpText(index)) - ); - if (!data) - throw new Error( - getMissingArgumentError("data", getBatchCallHelpText(index)) - ); - - // Opertation type - let operationType = type; - if (typeof type !== Number) { - if (!Object.keys(OPERATION_TYPES).includes(type)) - throw new Error( - `You provided an invalid operation type "${type}"${getBatchCallHelpText( - index - )}` - ); - operationType = OPERATION_TYPES[type]; - } - - if ( - [ - OPERATION_TYPES.ERC20_APPROVE, - OPERATION_TYPES.ERC20_TRANSFER_FROM, - ].includes(operationType) - ) - return parseERC20Operation({index, operationType, data}); - if ( - [ - OPERATION_TYPES.SUPERTOKEN_UPGRADE, - OPERATION_TYPES.SUPERTOKEN_DOWNGRADE, - ].includes(operationType) - ) - return parseSuperTokenOperation({index, operationType, data}); - if ( - [ - OPERATION_TYPES.SUPERFLUID_CALL_AGREEMENT, - OPERATION_TYPES.CALL_APP_ACTION, - ].includes(operationType) - ) - return parseSuperFluidOperation({index, operationType, data}); - throw new Error( - `You provided an invalid operation type "${type}"${getBatchCallHelpText( - index - )}` - ); - } catch (e) { - throw new Error(getErrorResponse(e, "batchCall")); - } -}; - -const batchCall = ({agreements, calls}) => { - if (!calls || !Array.isArray(calls)) - throw new Error( - getErrorResponse("You must provide an array of calls", "batchCall") - ); - this.agreements = agreements; - return calls.map((call, index) => parse({index, ...call})); -}; - -module.exports = {batchCall}; diff --git a/packages/js-sdk/src/batchCall.md b/packages/js-sdk/src/batchCall.md deleted file mode 100644 index 01449c5047..0000000000 --- a/packages/js-sdk/src/batchCall.md +++ /dev/null @@ -1,156 +0,0 @@ -The `@superluid-finance/js-sdk` includes a wrapper function for creating batch calls quickly. For example, to upgrade some DAI to DAIx and transfer it in the same transaction, you can use `sf.batchCall()` like this: - -```js -await sf.batchCall([ - { - type: "SUPERTOKEN_UPGRADE", - data: { - token: "0x111...", - amount: "1000000000000000000", - }, - }, - { - type: "ERC20_TRANSFER_FROM", - data: { - token: "0x111...", - amount: "1000000000000000000", - sender: "0xaaa...", - recipient: "0xbbb...", - }, - }, -]); -``` - -All the `sf.batchCall()` options and available arguments are shown in the table below. - -| Action | Type (required string or number) | Data (required) | -| :-------------------------- | :--------------------------------- | :----------------------------------------------------------------------------------------- | -| ERC20 `approve` | "ERC20_APPROVE" or 1 | `token` Address, `spender` Address, `amount` String | -| ERC20 `transferFrom` | "ERC20_TRANSFER_FROM" or 2 | `token` Address, `sender` Address, `recipient` Address, `amount` String | -| Super Token `upgrade` | "SUPERTOKEN_UPGRADE" or 101 | `token` Address, `amount` String | -| Super Token `downgrade` | "SUPERTOKEN_DOWNGRADE" or 102 | `token` Address, `amount` String | -| Super Fluid `callAgreement` | "SUPERFLUID_CALL_AGREEMENT" or 201 | `agreeementType` "CFA" or "IDA", `method` String, `arguments` array, `userData` (optional) | -| Super Fluid `callAppAction` | "CALL_APP_ACTION" or 202 | `superApp` Address, `callData` see below | - -See the specific sections below for more details. - -## ERC20_APPROVE & ERC20_TRANSFER_FROM - -Note: you can only use `batchCall` ERC20 features with Super Tokens. For example, you cannot perform a regular DAI approval. All non-Super Token ERC20 approvals must occur in a separate transaction. - -```js -await sf.batchCall([ - { - type: "ERC20_APPROVE", - data: { - token: "0x111...", // Super Tokens only - amount: "1000000000000000000", - spender: "0xbbb...", - }, - }, - { - type: "ERC20_TRANSFER_FROM", - data: { - token: "0x111...", // Super Tokens only - amount: "1000000000000000000", - sender: "0xaaa...", - recipient: "0xbbb...", - }, - }, -]); -``` - -## SUPERTOKEN_UPGRADE and SUPERTOKEN_DOWNGRADE - -No tricks here, just provide the Super Token address as `token` and the `amount`. - -```js -await sf.batchCall([ - { - type: "SUPERTOKEN_UPGRADE", - data: { - token: "0x111...", // Super Token address - amount: "1000000000000000000", - }, - }, - { - type: "SUPERTOKEN_DOWNGRADE", - data: { - token: "0x111...", // Super Token address - amount: "1000000000000000000", - }, - }, -]); -``` - -## SUPERFLUID_CALL_AGREEMENT - -To call an agreement, provide the `agreementType` ("CFA" or "IDA"), `method`, and `arguments`. Use the docs for Constant Flow Agreement (TODO LINK) and Instant Distribution Agreement (TODO LINK) to see the proper order for the arguments. - -```js -await sf.batchCall([ - { - type: "SUPERFLUID_CALL_AGREEMENT", - data: { - agreementType: "CFA", - method: "createFlow", - arguments: [ - sf.tokens.fDAIx.address, // Token address - app.address, // Flow recipient - MINIMUM_GAME_FLOW_RATE.toString(), // Flow rate - "0x", - ], - }, - }, -]); -``` - -## CALL_APP_ACTION - -The `@superfluid-finance/js-sdk` isn't aware of your Super App, so you must encode the method arguments yourself. Here is an example using two different libraries: - -```js -// Example Solidity function in your Super App -function deposit(uint256 amount) {} - -// Web3.js -myContract.methods.deposit("1000000000000000000").encodeABI() -``` - -Here is an example which approves a Super App to spend a user's Super Tokens, followed by a Super App function call: - -```js -const SuperfluidSDK = require("@superfluid-finance/js-sdk"); -const Web3 = require("web3"); - -const sf = new SuperfluidSDK.Framework({ - web3: new Web3(window.ethereum), - tokens: ["fDAI"], -}); -await sf.initialize(); - -const bob = sf.user({ address: "0xbbb...", token: sf.tokens.fDAIx.address }); - -// TODO: Create contract - -await sf.batchCall([ - { - type: "ERC20_APPROVE", - data: { - token: sf.tokens.fDAIx.address, - spender: bob.address, - amount: "1000000000000000000", - }, - }, - { - type: "CALL_APP_ACTION", - data: { - superApp: myContract.address, - callData: myContract.interface.encodeFunctionData( - "deposit", - ["1000000000000000000"] - ); - }, - }, -]); -``` diff --git a/packages/js-sdk/src/contracts.json b/packages/js-sdk/src/contracts.json deleted file mode 100644 index 1eaba2480c..0000000000 --- a/packages/js-sdk/src/contracts.json +++ /dev/null @@ -1,23 +0,0 @@ -[ - "Ownable", - "AccessControl", - "UUPSProxiable", - "IERC20", - "TokenInfo", - "ERC20WithTokenInfo", - "IResolver", - "SuperfluidLoader", - "ISuperfluid", - "Superfluid", - "ISuperToken", - "SuperToken", - "ISuperTokenFactory", - "SuperTokenFactory", - "ISuperAgreement", - "ISuperfluidGovernance", - "SuperfluidGovernanceBase", - "IConstantFlowAgreementV1", - "IInstantDistributionAgreementV1", - "TestToken", - "ISETH" -] diff --git a/packages/js-sdk/src/getConfig.d.ts b/packages/js-sdk/src/getConfig.d.ts deleted file mode 100644 index d562680e17..0000000000 --- a/packages/js-sdk/src/getConfig.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -export interface NetworkConfig { - nativeTokenSymbol?: string, - resolverAddress?: string -} - -export function getConfig(chainId: number, version: string): NetworkConfig; diff --git a/packages/js-sdk/src/getConfig.js b/packages/js-sdk/src/getConfig.js deleted file mode 100644 index e504871445..0000000000 --- a/packages/js-sdk/src/getConfig.js +++ /dev/null @@ -1,159 +0,0 @@ -/* eslint-disable no-global-assign */ -const sfMetadata = require("@superfluid-finance/metadata"); - -/* istanbul ignore next */ -if (typeof module === "undefined") module = {}; - -const getConfigData = (chainId) => { - const networkData = sfMetadata.getNetworkByChainId(chainId); - if (!networkData) { - console.log(`no metadata found for network with chainId ${chainId}`); - return { - nativeTokenSymbol: "", - resolverAddress: "", - versions: { - v1: { - subgraphQueryEndpoint: "", - }, - }, - }; - } - - return { - nativeTokenSymbol: networkData.nativeTokenSymbol, - resolverAddress: networkData.contractsV1.resolver, - versions: { - v1: { - subgraphQueryEndpoint: networkData.subgraphV1.hostedEndpoint, - }, - }, - }; -}; - -// eslint-disable-next-line no-undef -Superfluid_getConfig = module.exports = function getConfig(chainId, version) { - const DEFAULT_CONFIGS = { - // - // Local testing - // - 1337: { - // for default ganache setup - nativeTokenSymbol: "ETH", - }, - 4447: { - // for local testing (truffle internal ganache and TestEnvironment) - nativeTokenSymbol: "ETH", - }, - 5777: { - // for local testing (external ganache) - nativeTokenSymbol: "ETH", - }, - 31337: { - // for local testing hardhat - nativeTokenSymbol: "ETH", - }, - - // - // ETHEREUM - // - // goerli - 5: getConfigData(5), - - // - // MATIC: https://docs.matic.network/docs/develop/network-details/network/ - // - // (matic) mainnet - 137: getConfigData(137), - // (matic) mumbai testnet - 80001: getConfigData(80001), - // - // xDAI: https://www.xdaichain.com/for-users/wallets/metamask/metamask-setup - // - 0x64: getConfigData(0x64), - - // - // Optimistic Ethereum: https://community.optimism.io/docs/ - // - // optimism mainnet - 10: getConfigData(10), - // optimism goerli - 420: getConfigData(420), - - // - // Arbitrum: https://developer.offchainlabs.com - // - // arbitrum one mainnet - 42161: getConfigData(42161), - // arbitrum goerli testnet - 421613: getConfigData(421613), - - // - // Avalanche C-Chain: https://docs.avax.network/learn/platform-overview#contract-chain-c-chain - // - // avalanche c-chain mainnet - 43114: getConfigData(43114), - // avalanche c-chain fuji testnet - 43113: getConfigData(43113), - - // - // Binance Smart Chain (BSC): https://docs.binance.org/ - // - 56: getConfigData(56), - - // - // currently unsupported networks - // - 69: { - // optimism kovan testnet - nativeTokenSymbol: "ETH", - resolverAddress: "0x218B65780615Ff134f9Ad810CB98839534D3C0D6", - }, - - 42162: { - // arbitrum rinkeby testnet - nativeTokenSymbol: "ETH", - resolverAddress: "0xa2C0C70A1E922f5f060ec20EE3aF002C163b4567", - }, - - 97: { - // BSC chapel testnet - nativeTokenSymbol: "BNB", - }, - - // ARTIS - 0x03c401: { - // (artis) tau1 testnet - resolverAddress: "0x79D426CD219eDCFEB2dCbcf7ea0F8B3642C56F47", - }, - - // - // Celo: https://github.com/celo-org/celo-monorepo#docs - // - 42220: { - // celo mainnet - nativeTokenSymbol: "CELO", - }, - 44787: { - // celo alfajores testnet - nativeTokenSymbol: "CELO", - }, - }; - - let configs = { - ...DEFAULT_CONFIGS[chainId], - }; - // load version specific configs - if (configs.versions) { - configs = { - ...configs, - ...configs.versions[version], - }; - delete configs.versions; - } - // overriding environment variables - if (global && global.process && global.process.env.RESOLVER_ADDRESS) { - configs.resolverAddress = global.process.env.RESOLVER_ADDRESS; - } - - return configs; -}; diff --git a/packages/js-sdk/src/index.d.ts b/packages/js-sdk/src/index.d.ts deleted file mode 100644 index 5b431be5e0..0000000000 --- a/packages/js-sdk/src/index.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -export * from './getConfig'; -export * from './loadContracts'; -export * from './Framework'; -export * from './utils/gasMetering/gasMetering'; -export * from './utils/gasMetering/gasReporter'; -export * from './utils/error'; -export * from './utils/general'; -export * from './batchCall'; -export * from './ConstantFlowAgreementV1Helper'; -export * from './InstantDistributionAgreementV1Helper'; -export * from './getConfig'; -export * from './User'; diff --git a/packages/js-sdk/src/index.js b/packages/js-sdk/src/index.js deleted file mode 100644 index 2191a7e162..0000000000 --- a/packages/js-sdk/src/index.js +++ /dev/null @@ -1,5 +0,0 @@ -module.exports = { - getConfig: require("./getConfig"), - loadContracts: require("./loadContracts"), - Framework: require("./Framework"), -}; diff --git a/packages/js-sdk/src/loadContracts.d.ts b/packages/js-sdk/src/loadContracts.d.ts deleted file mode 100644 index 06eb39c61c..0000000000 --- a/packages/js-sdk/src/loadContracts.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -import type { Contract as Web3Contract } from "web3-eth-contract"; -import TruffleContract from "@truffle/contract"; -import type Web3 from "web3"; - -type SuperfluidContractNames = - | 'ERC20WithTokenInfo' - | 'IConstantFlowAgreementV1' - | 'IERC20' - | 'IInstantDistributionAgreementV1' - | 'IResolver' - | 'ISETH' - | 'ISuperAgreement' - | 'ISuperToken' - | 'ISuperTokenFactory' - | 'ISuperfluid' - | 'ISuperfluidGovernance' - | 'SuperfluidLoader' - | 'TestToken' - | 'TokenInfo' - | 'UUPSProxiable'; - -export type SuperfluidContractObject = { - abi: ContractInterface; - contractName: SuperfluidContractNames; - at: (address: string) => Contract; -} - -export type SuperfluidContracts = Record -export type LoadedContract = Web3Contract | TruffleContract.Contract -export type AbiContainer = Pick; -export type ContractLoader = (name: string) => AbiContainer; - -declare function setTruffleContractDefaults(c: TruffleContract.Contract, networkId: number, from: string): void; - -declare function defaultContractLoader(name: string): {contractName: string, abi: AbiContainer} - -export declare function loadContracts({ isTruffle, web3, from, additionalContracts, contractLoader, networkId, }: { - isTruffle: boolean; - web3?: Web3; - from: string; - additionalContracts?: string[]; - contractLoader: ContractLoader; - networkId: number; -}): Promise; diff --git a/packages/js-sdk/src/loadContracts.js b/packages/js-sdk/src/loadContracts.js deleted file mode 100644 index d717dec618..0000000000 --- a/packages/js-sdk/src/loadContracts.js +++ /dev/null @@ -1,102 +0,0 @@ -const contractNames = require("./contracts.json"); -const abis = require("./abi"); - -function defaultContractLoader(name) { - if (name in abis) { - return { - contractName: name, - abi: abis[name], - }; - } else throw Error(`Cannot load contract "${name}"`); -} - -function setTruffleContractDefaults(c, {networkId, from}) { - c.autoGas = true; - c.estimateGas = 1.25; - c.setNetwork(networkId); - const defaults = {}; - from && (defaults.from = from); - c.defaults(defaults); -} - -const loadContracts = async ({ - isTruffle, - web3, - from, - additionalContracts, - contractLoader, - networkId, -}) => { - if (!networkId) throw Error("networkId not provided"); - // use set to eliminate duplicated entries - const allContractNames = Array.from( - new Set([...contractNames, ...(additionalContracts || [])]) - ); - contractLoader = contractLoader || defaultContractLoader; - let contracts = {}; - if (web3) { - try { - const TruffleContract = require("@truffle/contract"); - console.debug( - `Using @superfluid-finance/js-sdk in a non-native Truffle environment. - Peer dependency @truffle/contract is required.` - ); - if (from) { - console.log("Set default from address to", from); - } else { - const accounts = await web3.eth.getAccounts(); - from = accounts[0]; - console.log( - "Set default from address to the first account", - from - ); - } - await Promise.all( - allContractNames.map(async (name) => { - const _normalizedObject = await contractLoader(name); - Object.assign(_normalizedObject, { - networks: { - [networkId]: {}, - // setting it for truffle contract detectNetwork method - }, - }); - const c = (contracts[name] = - TruffleContract(_normalizedObject)); - c.setProvider(web3.currentProvider); - setTruffleContractDefaults(c, { - networkId, - from, - }); - }) - ); - } catch (e) { - throw Error( - `could not load non-truffle environment contracts. ${e}` - ); - } - } else if (isTruffle) { - try { - console.debug( - `Using @superfluid-finance/js-sdk within a Truffle native environment. - Truffle artifacts must be present.` - ); - if (from) { - console.log("Set default from address to", from); - } - allContractNames.forEach((name) => { - const c = (contracts[name] = artifacts.require(name)); - setTruffleContractDefaults(c, { - networkId, - from, - }); - }); - } catch (e) { - throw Error(`could not load truffle artifacts. ${e}`); - } - } else { - throw Error("Unknown mode"); - } - return contracts; -}; - -module.exports = loadContracts; diff --git a/packages/js-sdk/src/types/gasOptions.ts b/packages/js-sdk/src/types/gasOptions.ts deleted file mode 100644 index b8b64e9275..0000000000 --- a/packages/js-sdk/src/types/gasOptions.ts +++ /dev/null @@ -1,4 +0,0 @@ -export interface GasOptions { - maxPriorityFeePerGas?: string; // HexString - maxFeePerGas?: string; // HexString -} diff --git a/packages/js-sdk/src/utils/error.d.ts b/packages/js-sdk/src/utils/error.d.ts deleted file mode 100644 index 92c7cdd8df..0000000000 --- a/packages/js-sdk/src/utils/error.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -export function getErrorResponse( - error: Error | string, - className: string, - functionName: string -): string; - -export function getMissingArgumentError( - argumentName: string, - helpText: string -): string; - -export function getBatchCallHelpText(index: number): string; \ No newline at end of file diff --git a/packages/js-sdk/src/utils/error.js b/packages/js-sdk/src/utils/error.js deleted file mode 100644 index db9166d066..0000000000 --- a/packages/js-sdk/src/utils/error.js +++ /dev/null @@ -1,19 +0,0 @@ -const getErrorResponse = (error, className, functionName) => { - const errorText = typeof error === "string" ? error : error.message; - let helperText = ` ${className}`; - if (functionName) helperText = helperText.concat(`.${functionName}() `); - return `Error: @superfluid-finance/js-sdk${helperText}: ${errorText}`; -}; - -const getMissingArgumentError = (argumentName, helpText) => { - return `You did not provide a required argument for "${argumentName}" ${helpText}`; -}; - -const getBatchCallHelpText = (index) => - ` in item #${index} in your batch call array. Please see https://docs.superfluid.finance/superfluid/docs/batch-call for more help`; - -module.exports = { - getErrorResponse, - getMissingArgumentError, - getBatchCallHelpText, -}; diff --git a/packages/js-sdk/src/utils/gasMetering/gasMetering.d.ts b/packages/js-sdk/src/utils/gasMetering/gasMetering.d.ts deleted file mode 100644 index 42093fd99e..0000000000 --- a/packages/js-sdk/src/utils/gasMetering/gasMetering.d.ts +++ /dev/null @@ -1,43 +0,0 @@ -import type BN from 'bn.js' -import type Web3 from 'web3' -import type { GasMeterJSONReporter } from "./gasReporter"; -import type { GasMeterHTMLReporter } from "./gasReporter"; - -export type Record = { - action: string - txHash: string - gas: BN - gasPrice: BN - cost: BN -} - -export declare class GasMeter { - constructor( - web3: Web3, - outputFormat: 'JSON'|'HTML'|'TENDERLY', - gasPrice: string - ); - web3: Web3; - BN: BN; - reporter: GasMeterJSONReporter | GasMeterHTMLReporter | undefined; - gasPrice: string; - records: Record[]; - aggregates: {}; - formatter: Formatter; - _format(): { - aggregates: {}; - executedTxs: {}[]; - }; - pushTx( - tx: Record, - actionName: string - ): void; - generateReport(name: string): void; -} -declare class Formatter { - constructor(web3: Web3); - web3: Web3; - BN: BN; - formatBigNumber(key: string, value: number | BN): string; - formatObject(x: Record): {}; -} diff --git a/packages/js-sdk/src/utils/gasMetering/gasMetering.js b/packages/js-sdk/src/utils/gasMetering/gasMetering.js deleted file mode 100644 index ec15b69025..0000000000 --- a/packages/js-sdk/src/utils/gasMetering/gasMetering.js +++ /dev/null @@ -1,127 +0,0 @@ -const {GasMeterJSONReporter, GasMeterHTMLReporter} = require("./gasReporter"); - -class Formatter { - constructor(web3) { - this.web3 = web3; - this.BN = this.web3.utils.BN; - } - - formatBigNumber(key, value) { - switch (key) { - case "cost": - case "totalCost": - case "avgCost": - value = `${this.web3.utils.fromWei(value)} ETH`; - break; - case "totalTx": - case "gas": - case "totalGas": - case "minGas": - case "maxGas": - case "avgGas": - value = value.toString(10); - break; - case "gasPrice": - value = `${this.web3.utils.fromWei(value, "gwei")} GWEI`; - break; - } - return value; - } - - formatObject(x) { - const result = {}; - Object.keys(x).forEach((key) => { - var value = x[key]; - if (this.BN.isBN(value)) { - value = this.formatBigNumber(key, value); - } - result[key] = value; - }); - return result; - } -} - -module.exports = class GasMeter { - constructor(web3, outputFormat, gasPrice) { - this.web3 = web3; - this.BN = this.web3.utils.BN; - switch (outputFormat) { - case "JSON": - this.reporter = new GasMeterJSONReporter({}); - break; - case "HTML": - this.reporter = new GasMeterHTMLReporter({}); - break; - case "TENDERLY": - // TODO - break; - default: - throw new Error(`Unsuported report type ${outputFormat}`); - } - this.gasPrice = new this.BN(gasPrice); - this.records = []; - this.aggregates = {}; - this.formatter = new Formatter(this.web3); - } - - _format() { - const formattedAggregates = {}; - Object.keys(this.aggregates).forEach((actionName) => { - const bucket = this.aggregates[actionName]; - formattedAggregates[actionName] = {}; - Object.keys(bucket).forEach((key) => { - formattedAggregates[actionName][key] = - this.formatter.formatBigNumber( - key, - bucket[key], - this.fiatCurr - ); - }); - }); - const formattedRecords = this.records.map((x) => { - return this.formatter.formatObject(x, this.fiatCurr); - }); - return { - aggregates: {...formattedAggregates}, - executedTxs: [...formattedRecords], - }; - } - - pushTx(tx, actionName) { - const gas = new this.BN(tx.receipt.gasUsed); - const cost = gas.mul(this.gasPrice); - this.records.push({ - action: actionName, - txHash: tx.tx, - gas: gas, - gasPrice: this.gasPrice, - cost: cost, - }); - if (!(actionName in this.aggregates)) { - this.aggregates[actionName] = { - action: actionName, - avgGas: new this.BN("0"), - avgCost: new this.BN("0"), - minGas: new this.BN("10000000000000000000000"), - maxGas: new this.BN("0"), - totalTx: new this.BN("0"), - totalGas: new this.BN("0"), - totalCost: new this.BN("0"), - }; - } - const bucket = this.aggregates[actionName]; - bucket.totalTx = bucket.totalTx.add(new this.BN("1")); - bucket.totalGas = bucket.totalGas.add(gas); - bucket.totalCost = bucket.totalCost.add(cost); - bucket.avgCost = bucket.totalCost.div(bucket.totalTx); - bucket.avgGas = bucket.totalGas.div(bucket.totalTx); - bucket.minGas = this.BN.min(bucket.minGas, gas); - bucket.maxGas = this.BN.max(bucket.maxGas, gas); - } - - generateReport(name) { - this.reporter.fileName = name; - const formattedReport = this._format(); - this.reporter.generateReport(formattedReport); - } -}; diff --git a/packages/js-sdk/src/utils/gasMetering/gasReporter.d.ts b/packages/js-sdk/src/utils/gasMetering/gasReporter.d.ts deleted file mode 100644 index 9284149e52..0000000000 --- a/packages/js-sdk/src/utils/gasMetering/gasReporter.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -// TODO: fs type, elements type for generator -export class GasMeterJSONReporter extends GasMeterReporter { - generateOutput(report: { aggregates: {}, executedTxs: {}[] }): void; -} -export class GasMeterHTMLReporter extends GasMeterReporter { - _joinStrings(prevVal: string, currVal: string, idx: number): string; - _generateHeaders(element: any): string; - _generateBody(elements: any): string; - generateReport(report: { aggregates: {}, executedTxs: {}[] }): void; -} -declare class GasMeterReporter { - constructor({ fileSystem, fileName }: { - fileSystem: any; - fileName: string; - }); - fs: any; - filePath: string; - fileName: string; -} -export {}; diff --git a/packages/js-sdk/src/utils/gasMetering/gasReporter.js b/packages/js-sdk/src/utils/gasMetering/gasReporter.js deleted file mode 100644 index 08920c8427..0000000000 --- a/packages/js-sdk/src/utils/gasMetering/gasReporter.js +++ /dev/null @@ -1,77 +0,0 @@ -const fs = require("fs"); -const path = require("path"); -class GasMeterReporter { - constructor({fileSystem, fileName}) { - this.fs = fileSystem ? fileSystem : fs; - this.filePath = path.join(process.cwd(), "reports"); - if (!fs.existsSync(this.filePath)) { - fs.mkdirSync(this.filePath); - } - this.fileName = fileName ? fileName : "gasReport"; - } -} - -class GasMeterJSONReporter extends GasMeterReporter { - generateOutput(report) { - const result = JSON.stringify(report); - this.fs.writeFileSync(`${this.filePath}${this.fileName}.json`, result); - } -} - -class GasMeterHTMLReporter extends GasMeterReporter { - _joinStrings(prevVal, currVal, idx) { - return idx == 0 ? currVal : prevVal + currVal; - } - - _generateHeaders(element) { - let keys = Object.keys(element); - - const headers = keys - .map((key) => { - return `${key}`; - }) - .reduce(this._joinStrings); - - return `${headers}`; - } - - _generateBody(elements) { - return elements - .map((tx) => { - let keys = Object.keys(tx); - let tds = keys - .map((key) => { - return `${tx[key]}`; - }) - .reduce(this._joinStrings); - return `${tds}`; - }) - .reduce(this._joinStrings); - } - - generateReport(report) { - const htmlStub = require("./htmlStub"); - const statHeaders = this._generateHeaders( - Object.values(report.aggregates)[0] - ); - const statBody = this._generateBody(Object.values(report.aggregates)); - const txHeaders = this._generateHeaders(report.executedTxs[0]); - const txTableBody = this._generateBody(report.executedTxs); - const result = htmlStub - .replace("{{HEADERS-TX}}", txHeaders) - .replace("{{BODY-TX}}", txTableBody) - .replace("{{HEADERS-STATS}}", statHeaders) - .replace("{{BODY-STATS}}", statBody) - .replace("{{TITLE}}", this.fileName); - - this.fs.writeFileSync( - path.join(this.filePath, `${this.fileName}.html`), - result - ); - } -} - -module.exports = { - GasMeterJSONReporter, - GasMeterHTMLReporter, -}; diff --git a/packages/js-sdk/src/utils/gasMetering/htmlStub.d.ts b/packages/js-sdk/src/utils/gasMetering/htmlStub.d.ts deleted file mode 100644 index 763ab62561..0000000000 --- a/packages/js-sdk/src/utils/gasMetering/htmlStub.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare const _exports: string; -export = _exports; diff --git a/packages/js-sdk/src/utils/gasMetering/htmlStub.js b/packages/js-sdk/src/utils/gasMetering/htmlStub.js deleted file mode 100644 index 7ee9b6194f..0000000000 --- a/packages/js-sdk/src/utils/gasMetering/htmlStub.js +++ /dev/null @@ -1,127 +0,0 @@ -module.exports = ` - - - - - -

{{TITLE}}

- -

Stats

-
- - - - {{HEADERS-STATS}} - - - - {{BODY-STATS}} - -
-
- -

Records

-
- - - - {{HEADERS-TX}} - - - - {{BODY-TX}} - -
-
- -`; diff --git a/packages/js-sdk/src/utils/general.d.ts b/packages/js-sdk/src/utils/general.d.ts deleted file mode 100644 index 4179063814..0000000000 --- a/packages/js-sdk/src/utils/general.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { Framework } from '../Framework'; -import type { Transaction } from 'web3-core'; -import { GasOptions } from "../types/gasOptions"; - -export function validateAddress(address: string): void; -export function isAddress(address: string): boolean; -export function getCleanAddress(address: string): string; -export function completeTransaction({ sf, method, args, sender, onTransaction, gasOptions }: { - sf: Framework; - method: () => Transaction; - args: Array; - sender: string; - onTransaction: () => any; - gasOptions?: GasOptions; -}): Promise; diff --git a/packages/js-sdk/src/utils/general.js b/packages/js-sdk/src/utils/general.js deleted file mode 100644 index e14f3a5f80..0000000000 --- a/packages/js-sdk/src/utils/general.js +++ /dev/null @@ -1,34 +0,0 @@ -const validateAddress = (address) => { - if (!isAddress(address)) throw "Address is invalid"; -}; - -const isAddress = (address) => { - return /^(0x)?[0-9a-f]{40}$/i.test(address); -}; - -const getCleanAddress = (address) => { - validateAddress(address); - return address.toLowerCase(); -}; - -const completeTransaction = async ({ - method, - args, - sender, - onTransaction, - gasOptions = {}, -}) => { - let tx; - tx = await method(...args, {from: sender, ...gasOptions}).on( - "transactionHash", - onTransaction - ); - return tx; -}; - -module.exports = { - validateAddress, - isAddress, - getCleanAddress, - completeTransaction, -}; diff --git a/packages/js-sdk/tasks/build-abi-js.sh b/packages/js-sdk/tasks/build-abi-js.sh deleted file mode 100755 index 1f87856a90..0000000000 --- a/packages/js-sdk/tasks/build-abi-js.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/bash - -cd "$(dirname "$0")/.." - -JQ="../../node_modules/node-jq/bin/jq" - -CONTRACTS=( $($JQ -r .[] ./src/contracts.json) ) -[ $? == 0 ] || exit 1 - -{ - echo "if (typeof module === \"undefined\") module = {};" - echo "Superfluid_ABI = module.exports = {" - for i in "${CONTRACTS[@]}";do - ABI="$($JQ '.abi' ../ethereum-contracts/build/contracts/$i.json)" - [ $? == 0 ] || exit 1 - echo " $i: $ABI," - done - echo "};" -} > src/abi.js diff --git a/packages/js-sdk/tasks/cloc.sh b/packages/js-sdk/tasks/cloc.sh deleted file mode 100644 index 0642213536..0000000000 --- a/packages/js-sdk/tasks/cloc.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/sh - -cd "$(dirname "$0")"/.. -CLOC="cloc --by-file-by-lang" - -$CLOC --not-match-f 'abi.js' --by-file src diff --git a/packages/js-sdk/test/.eslintrc.js b/packages/js-sdk/test/.eslintrc.js deleted file mode 100644 index 1662d31140..0000000000 --- a/packages/js-sdk/test/.eslintrc.js +++ /dev/null @@ -1,18 +0,0 @@ -module.exports = { - globals: { - web3: true, - artifacts: true, - describe: true, - contract: true, - context: true, - before: true, - after: true, - beforeEach: true, - afterEach: true, - it: true, - assert: true, - }, - rules: { - "no-console": "off", - }, -}; diff --git a/packages/js-sdk/test/ConstantFlowAgreementV1Helper.test.js b/packages/js-sdk/test/ConstantFlowAgreementV1Helper.test.js deleted file mode 100644 index 5c439263d4..0000000000 --- a/packages/js-sdk/test/ConstantFlowAgreementV1Helper.test.js +++ /dev/null @@ -1,371 +0,0 @@ -const {toBN} = require("@decentral.ee/web3-helpers"); -const TestEnvironment = require("@superfluid-finance/ethereum-contracts/test/TestEnvironment"); -const {expect} = require("chai"); - -describe("ConstantFlowAgreementV1Helper class", function () { - this.timeout(300e3); - const t = TestEnvironment.getSingleton(); - - let admin, alice, bob, carol; - let sf; - let superToken; - - before(async () => { - await t.beforeTestSuite({ - isTruffle: false, - web3, - nAccounts: 4, - }); - - ({admin, alice, bob, carol} = t.aliases); - sf = t.sf; - - ({superToken} = await t.deployNewToken("TEST2", { - isTruffle: false, - web3, - doUpgrade: true, - })); - await t.pushEvmSnapshot(); - }); - - after(async () => { - await t.popEvmSnapshot(); - }); - - beforeEach(async function () { - await t.beforeEachTestCase(); - }); - - it("eip155 protection check", async () => { - const tx = await sf.cfa.createFlow({ - superToken: superToken.address, - sender: alice, - receiver: bob, - flowRate: "38580246913580", // 100 / mo - }); - const txReceipt = await web3.eth.getTransaction(tx.tx); - // per https://eips.ethereum.org/EIPS/eip-155 - // to use "v" to validate if it is eip-155 enabled transaction - console.log("txReceipt", txReceipt); - assert.isDefined(txReceipt.v); - }); - - it("createFlow", async () => { - const tx = await sf.cfa.createFlow({ - superToken: superToken.address, - sender: alice, - receiver: bob, - flowRate: "38580246913580", // 100 / mo - }); - // validate flow data - const flow = await sf.cfa.getFlow({ - superToken: superToken.address, - sender: alice, - receiver: bob, - }); - const block = await web3.eth.getBlock(tx.receipt.blockNumber); - assert.equal(flow.timestamp.getTime(), block.timestamp * 1000); - assert.equal(flow.flowRate, "38580246913580"); - assert.notEqual(flow.deposit, "0"); - assert.equal(flow.owedDeposit, "0"); - // validate account net flows - assert.equal( - ( - await sf.cfa.getNetFlow({ - superToken: superToken.address, - account: alice, - }) - ).toString(), - "-38580246913580" - ); - assert.equal( - ( - await sf.cfa.getNetFlow({ - superToken: superToken.address, - account: bob, - }) - ).toString(), - "38580246913580" - ); - const aliceFlows = await sf.cfa.getAccountFlowInfo({ - superToken: superToken.address, - account: alice, - }); - assert.equal(aliceFlows.flowRate, "-38580246913580"); - const bobFlows = await sf.cfa.getAccountFlowInfo({ - superToken: superToken.address, - account: bob, - }); - assert.equal(bobFlows.flowRate, "38580246913580"); - assert.equal( - aliceFlows.timestamp.toString(), - bobFlows.timestamp.toString() - ); - }); - - it("createFlow with onTransaction", async () => { - let txHash = ""; - const tx = await sf.cfa.createFlow({ - superToken: superToken.address, - sender: alice, - receiver: bob, - flowRate: "38580246913580", // 100 / mo - onTransaction: (hash) => { - txHash = hash; - }, - }); - assert.equal(txHash, tx.receipt.transactionHash); - }); - - it("updateFlow", async () => { - await sf.cfa.createFlow({ - superToken: superToken.address, - sender: alice, - receiver: bob, - flowRate: "38580246913580", // 100 / mo - }); - await sf.cfa.updateFlow({ - superToken: superToken.address, - sender: alice, - receiver: bob, - flowRate: "19290123456790", // 100 / mo - }); - // validate account net flows - assert.equal( - ( - await sf.cfa.getNetFlow({ - superToken: superToken.address, - account: alice, - }) - ).toString(), - "-19290123456790" - ); - assert.equal( - ( - await sf.cfa.getNetFlow({ - superToken: superToken.address, - account: bob, - }) - ).toString(), - "19290123456790" - ); - }); - - it("updateFlow with onTransaction", async () => { - let txHash = ""; - await sf.cfa.createFlow({ - superToken: superToken.address, - sender: alice, - receiver: bob, - flowRate: "38580246913580", // 100 / mo - }); - const tx = await sf.cfa.updateFlow({ - superToken: superToken.address, - sender: alice, - receiver: bob, - flowRate: "19290123456790", // 100 / mo - onTransaction: (hash) => { - txHash = hash; - }, - }); - assert.equal(txHash, tx.receipt.transactionHash); - }); - - describe("deleteFlow", () => { - beforeEach(async () => { - await sf.cfa.createFlow({ - superToken: superToken.address, - sender: alice, - receiver: bob, - flowRate: "38580246913580", // 100 / mo - }); - }); - - it("by sender", async () => { - const ethBefore = await web3.eth.getBalance(alice); - await sf.cfa.deleteFlow({ - superToken: superToken.address, - sender: alice, - receiver: bob, - }); - const ethAfter = await web3.eth.getBalance(alice); - assert.isTrue(toBN(ethAfter).lt(toBN(ethBefore))); - assert.equal( - ( - await sf.cfa.getNetFlow({ - superToken: superToken.address, - account: alice, - }) - ).toString(), - "0" - ); - assert.equal( - ( - await sf.cfa.getNetFlow({ - superToken: superToken.address, - account: bob, - }) - ).toString(), - "0" - ); - }); - - it("by receiver", async () => { - const ethBefore = await web3.eth.getBalance(bob); - await sf.cfa.deleteFlow({ - superToken: superToken.address, - sender: alice, - receiver: bob, - by: bob, - }); - const ethAfter = await web3.eth.getBalance(bob); - assert.isTrue(toBN(ethAfter).lt(toBN(ethBefore))); - assert.equal( - ( - await sf.cfa.getNetFlow({ - superToken: superToken.address, - account: alice, - }) - ).toString(), - "0" - ); - assert.equal( - ( - await sf.cfa.getNetFlow({ - superToken: superToken.address, - account: bob, - }) - ).toString(), - "0" - ); - }); - - it("by wrong person", async () => { - try { - await sf.cfa.deleteFlow({ - superToken: superToken.address, - sender: alice, - receiver: bob, - by: admin, - }); - } catch (err) { - expect(err.message).to.not.be.null; - } - }); - - it("by sender with onTransaction", async () => { - let txHash = ""; - const tx = await sf.cfa.deleteFlow({ - superToken: superToken.address, - sender: alice, - receiver: bob, - onTransaction: (hash) => { - txHash = hash; - }, - }); - assert.equal(txHash, tx.receipt.transactionHash); - }); - }); - - describe("listFlows", () => { - it("normally", async () => { - await sf.cfa.createFlow({ - superToken: superToken.address, - sender: alice, - receiver: bob, - flowRate: "38580246913580", // 100 / mo - }); - await sf.cfa.createFlow({ - superToken: superToken.address, - sender: bob, - receiver: carol, - flowRate: "19290123456790", // 100 / mo - }); - assert.deepEqual( - await sf.cfa.listFlows({ - superToken: superToken.address, - account: alice, - }), - { - inFlows: [], - outFlows: [ - { - sender: alice, - receiver: bob, - flowRate: "38580246913580", - }, - ], - } - ); - assert.deepEqual( - await sf.cfa.listFlows({ - superToken: superToken.address, - account: bob, - }), - { - inFlows: [ - { - sender: alice, - receiver: bob, - flowRate: "38580246913580", - }, - ], - outFlows: [ - { - sender: bob, - receiver: carol, - flowRate: "19290123456790", - }, - ], - } - ); - }); - - it("onlyInFlows and onlyOutFlows", async () => { - await sf.cfa.createFlow({ - superToken: superToken.address, - sender: alice, - receiver: bob, - flowRate: "38580246913580", // 100 / mo - }); - await sf.cfa.createFlow({ - superToken: superToken.address, - sender: bob, - receiver: carol, - flowRate: "19290123456790", // 100 / mo - }); - assert.deepEqual( - await sf.cfa.listFlows({ - superToken: superToken.address, - account: bob, - onlyOutFlows: true, - }), - { - outFlows: [ - { - sender: bob, - receiver: carol, - flowRate: "19290123456790", - }, - ], - } - ); - assert.deepEqual( - await sf.cfa.listFlows({ - superToken: superToken.address, - account: bob, - onlyInFlows: true, - }), - { - inFlows: [ - { - sender: alice, - receiver: bob, - flowRate: "38580246913580", - }, - ], - } - ); - }); - }); -}); diff --git a/packages/js-sdk/test/Framework.subgraph.test.js b/packages/js-sdk/test/Framework.subgraph.test.js deleted file mode 100644 index 9b323925d7..0000000000 --- a/packages/js-sdk/test/Framework.subgraph.test.js +++ /dev/null @@ -1,115 +0,0 @@ -const path = require("path"); -const Web3 = require("web3"); -const HDWalletProvider = require("@truffle/hdwallet-provider"); -const SuperfluidSDK = require("../src"); - -describe("Framework subgraph (matic) support", function () { - this.timeout(300e3); - - let sf; - - before(async function () { - // make sure no test resolver passed to the testsuite - delete process.env.RESOLVER_ADDRESS; - - try { - require("dotenv").config({ - path: path.join(__dirname, "..", ".env"), - }); - } catch (e) { - // no-empty - } - sf = new SuperfluidSDK.Framework({ - isTruffle: false, - web3: new Web3( - new HDWalletProvider( - "candy maple cake sugar pudding cream honey rich smooth crumble sweet treat", - process.env.POLYGON_MAINNET_PROVIDER_URL || - // use a default one for public pull requests - "https://polygon-rpc.com/", - 0, //address_index - 1 // num_addresses - ) - ), - tokens: ["DAIx", "ETHx"], - version: "v1", - }); - await sf.initialize(); - }); - - // Taking an address from https://docs.ricochet.exchange/docs/network-directory: - // DAI >> WETH - it("subgraphQuery", async () => { - const data = await sf.subgraphQuery(`{ - _meta { - block { - number - } - deployment - } - }`); - assert.isDefined(data._meta.block.number); - assert.isDefined(data._meta.deployment); - }); - - it("getPastEvents SuperTokenLogicUpdated", async () => { - const events = await sf.getPastEvents( - sf.host, - "SuperTokenLogicUpdated" - ); - assert.isTrue(events.length > 0); - assert.isDefined(events[0].token); - assert.isDefined(events[0].code); - }); - - it("cfa.listFlows", async () => { - const flows = await sf.cfa.listFlows({ - superToken: sf.tokens.DAIx.address, - account: "0x9BEf427fa1fF5269b824eeD9415F7622b81244f5", - }); - assert.isTrue(flows.inFlows.length > 0); - }); - - it("ida.listIndices", async () => { - const indexes = await sf.ida.listIndices({ - superToken: sf.tokens.ETHx.address, - publisher: "0x9BEf427fa1fF5269b824eeD9415F7622b81244f5", - }); - assert.equal(indexes.length, 1); - assert.equal(indexes[0], 0); - }); - - it("ida.listSubcribers", async () => { - const subscribers = await sf.ida.listSubcribers({ - superToken: sf.tokens.ETHx.address, - publisher: "0x9BEf427fa1fF5269b824eeD9415F7622b81244f5", - indexId: 0, - }); - assert.isTrue(subscribers.length > 0); - assert.isDefined(subscribers[0].subscriber); - assert.isDefined(subscribers[0].units); - }); - - it("getPastEvents IndexCreated", async () => { - const events = await sf.getPastEvents( - sf.agreements.ida, - "IndexCreated", - { - token: sf.tokens.ETHx.address, - publisher: "0x9BEf427fa1fF5269b824eeD9415F7622b81244f5", - indexId: 0, - } - ); - assert.isTrue(events.length > 0); - assert.equal( - events[0].token.toLowerCase(), - sf.tokens.ETHx.address.toLowerCase() - ); - assert.equal( - events[0].publisher.toLowerCase(), - "0x9BEf427fa1fF5269b824eeD9415F7622b81244f5".toLowerCase() - ); - assert.equal(events[0].indexId, 0); - assert.equal(events[0].userData, "0x"); - }); -}); diff --git a/packages/js-sdk/test/Framework.test.js b/packages/js-sdk/test/Framework.test.js deleted file mode 100644 index 354207d510..0000000000 --- a/packages/js-sdk/test/Framework.test.js +++ /dev/null @@ -1,383 +0,0 @@ -const {expectRevert} = require("@openzeppelin/test-helpers"); - -const Web3 = require("web3"); - -const TestEnvironment = require("@superfluid-finance/ethereum-contracts/test/TestEnvironment"); -const deployTestToken = require("@superfluid-finance/ethereum-contracts/scripts/deploy-test-token"); -const deploySuperToken = require("@superfluid-finance/ethereum-contracts/scripts/deploy-super-token"); -const SuperfluidSDK = require("../src"); - -describe("Framework class", function () { - this.timeout(300e3); - const t = TestEnvironment.getSingleton(); - - let admin; - - before(async function () { - await t.beforeTestSuite({ - isTruffle: false, - web3, - nAccounts: 1, - }); - - ({admin} = t.aliases); - - await deployTestToken(t.createErrorHandler(), [":", "fDAI"], { - isTruffle: false, - web3, - }); - await deployTestToken(t.createErrorHandler(), [":", "fUSDC"], { - isTruffle: false, - web3, - }); - await deploySuperToken(t.createErrorHandler(), [":", "ETH"], { - isTruffle: false, - web3, - }); - await deploySuperToken(t.createErrorHandler(), [":", "fDAI"], { - isTruffle: false, - web3, - }); - await deploySuperToken(t.createErrorHandler(), [":", "fUSDC"], { - isTruffle: false, - web3, - }); - await t.pushEvmSnapshot(); - }); - - after(async () => { - await t.popEvmSnapshot(); - }); - - beforeEach(async function () { - await t.beforeEachTestCase(); - }); - - describe("initialization", () => { - function testLoadedContracts(sf) { - const { - IERC20, - IResolver, - TokenInfo, - ISuperfluid, - ISuperToken, - ISuperTokenFactory, - IConstantFlowAgreementV1, - IInstantDistributionAgreementV1, - } = sf.contracts; - - assert.isDefined(IERC20.abi); - assert.equal(IERC20.contractName, "IERC20"); - assert.isTrue( - IERC20.abi.filter((i) => i.name === "Transfer").length > 0 - ); - - assert.isDefined(IResolver.abi); - assert.equal(IResolver.contractName, "IResolver"); - assert.isTrue( - IResolver.abi.filter((i) => i.name === "get").length > 0 - ); - - assert.isDefined(TokenInfo.abi); - assert.equal(TokenInfo.contractName, "TokenInfo"); - assert.isTrue( - TokenInfo.abi.filter((i) => i.name === "symbol").length > 0 - ); - - assert.isDefined(ISuperfluid.abi); - assert.equal(ISuperfluid.contractName, "ISuperfluid"); - assert.isTrue( - ISuperfluid.abi.filter((i) => i.name === "callAgreement") - .length > 0 - ); - - assert.isDefined(ISuperToken.abi); - assert.equal(ISuperToken.contractName, "ISuperToken"); - assert.isTrue( - ISuperToken.abi.filter((i) => i.name === "upgrade").length > 0 - ); - - assert.isDefined(ISuperTokenFactory.abi); - assert.equal(ISuperTokenFactory.contractName, "ISuperTokenFactory"); - assert.isTrue( - ISuperTokenFactory.abi.filter( - (i) => i.name === "createERC20Wrapper" - ).length > 0 - ); - - assert.isDefined(IConstantFlowAgreementV1.abi); - assert.equal( - IConstantFlowAgreementV1.contractName, - "IConstantFlowAgreementV1" - ); - assert.isTrue( - IConstantFlowAgreementV1.abi.filter( - (i) => i.name === "updateFlow" - ).length > 0 - ); - - assert.isDefined(IInstantDistributionAgreementV1.abi); - assert.equal( - IInstantDistributionAgreementV1.contractName, - "IInstantDistributionAgreementV1" - ); - assert.isTrue( - IInstantDistributionAgreementV1.abi.filter( - (i) => i.name === "createIndex" - ).length > 0 - ); - } - - it("with native truffle environment", async () => { - const sf = new SuperfluidSDK.Framework({ - isTruffle: true, - version: "test", - }); - await sf.initialize(); - testLoadedContracts(sf); - }); - - it("with non-native truffle environment", async () => { - const sf = new SuperfluidSDK.Framework({ - web3: new Web3(web3.currentProvider), - version: "test", - }); - await sf.initialize(); - testLoadedContracts(sf); - }); - - it("Fail generating gas report without setting gas report type", async () => { - const sf = new SuperfluidSDK.Framework({ - isTruffle: true, - version: "test", - }); - await sf.initialize(); - try { - sf.generateGasReport("noname"); - } catch (e) { - assert.equal(e.message, "No gas metering configured"); - } - }); - - it("defaults to version v1", () => { - const sf = new SuperfluidSDK.Framework({ - isTruffle: true, - }); - assert.equal(sf.version, "v1"); - }); - - describe("token loading", () => { - it("isSuperTokenListed", async () => { - const sf = new SuperfluidSDK.Framework({ - isTruffle: true, - tokens: ["ETH", "fUSDC", "fDAI"], - version: "test", - }); - await sf.initialize(); - - assert.isTrue(await sf.isSuperTokenListed("ETHx")); - assert.isTrue(await sf.isSuperTokenListed("fUSDCx")); - assert.isTrue(await sf.isSuperTokenListed("fDAIx")); - - assert.isFalse(await sf.isSuperTokenListed("ETH")); - assert.isFalse(await sf.isSuperTokenListed("fUSDC")); - assert.isFalse(await sf.isSuperTokenListed("fDAI")); - assert.isFalse(await sf.isSuperTokenListed("fTUSDx")); - assert.isFalse(await sf.isSuperTokenListed("ABC")); - - assert.isFalse(await sf.isSuperTokenListed(sf.address)); - assert.isFalse( - await sf.isSuperTokenListed(sf.tokens.fUSDC.address) - ); - assert.isTrue( - await sf.isSuperTokenListed(sf.tokens.fUSDCx.address) - ); - }); - - it("load all tokens", async () => { - const sf = new SuperfluidSDK.Framework({ - isTruffle: true, - tokens: ["ETH", "fUSDC", "fDAI"], - version: "test", - }); - await sf.initialize(); - - assert.equal(sf.superTokens.ETHx, sf.tokens.ETHx); - assert.equal(await sf.superTokens.ETHx.symbol(), "ETHx"); - assert.isUndefined(sf.superTokens.ETHx.underlyingToken); - - assert.equal(sf.superTokens.fUSDCx, sf.tokens.fUSDCx); - assert.equal(await sf.superTokens.fUSDCx.symbol(), "fUSDCx"); - assert.equal(await sf.tokens.fUSDC.symbol(), "fUSDC"); - assert.equal(sf.tokens.fUSDCx.underlyingToken, sf.tokens.fUSDC); - - assert.equal(sf.superTokens.ETHx, sf.tokens.ETHx); - assert.equal(await sf.superTokens.fDAIx.symbol(), "fDAIx"); - assert.equal(await sf.tokens.fDAI.symbol(), "fDAI"); - assert.equal(sf.tokens.fDAIx.underlyingToken, sf.tokens.fDAI); - }); - - it("load by superToken key", async () => { - const sf = new SuperfluidSDK.Framework({ - isTruffle: true, - tokens: ["fDAIx"], - version: "test", - }); - await sf.initialize(); - - assert.equal(sf.superTokens.fDAIx, sf.tokens.fDAIx); - assert.equal(await sf.superTokens.fDAIx.symbol(), "fDAIx"); - assert.equal( - await sf.tokens.fDAIx.underlyingToken.symbol(), - "fDAI" - ); - }); - - it("load by native token symbol", async () => { - const sf = new SuperfluidSDK.Framework({ - isTruffle: true, - tokens: ["ETH"], - version: "test", - }); - await sf.initialize(); - - assert.equal(sf.superTokens.ETHx, sf.tokens.ETHx); - assert.equal(sf.superTokens.ETHx.superTokenCustomType, "SETH"); - assert.equal(await sf.superTokens.ETHx.symbol(), "ETHx"); - }); - - it("use loadSuperNativeToken option", async () => { - const sf = new SuperfluidSDK.Framework({ - isTruffle: true, - loadSuperNativeToken: true, - version: "test", - }); - await sf.initialize(); - - assert.equal(sf.superTokens.ETHx, sf.tokens.ETHx); - assert.equal(sf.superTokens.ETHx.superTokenCustomType, "SETH"); - assert.equal(await sf.superTokens.ETHx.symbol(), "ETHx"); - }); - - it("load by native token symbol plus x", async () => { - const sf = new SuperfluidSDK.Framework({ - isTruffle: true, - tokens: ["ETHx"], - version: "test", - }); - await sf.initialize(); - - assert.equal(sf.superTokens.ETHx, sf.tokens.ETHx); - assert.equal(sf.superTokens.ETHx.superTokenCustomType, "SETH"); - assert.equal(await sf.superTokens.ETHx.symbol(), "ETHx"); - }); - - it("load by superToken address", async () => { - const sf = new SuperfluidSDK.Framework({ - isTruffle: true, - version: "test", - }); - await sf.initialize(); - - const fDAIxAddress = ( - await sf.resolver.get("supertokens.test.fDAIx") - ).toLowerCase(); - await sf.loadToken(fDAIxAddress); - - assert.equal( - sf.superTokens[fDAIxAddress].address.toLowerCase(), - fDAIxAddress - ); - assert.equal( - await sf.superTokens[fDAIxAddress].symbol(), - "fDAIx" - ); - assert.isUndefined(await sf.tokens.fDAI); - assert.isUndefined(await sf.tokens.fDAIx); - assert.equal( - await sf.superTokens[fDAIxAddress].underlyingToken.symbol(), - "fDAI" - ); - }); - - it("registered in resolver", async () => { - const sf = new SuperfluidSDK.Framework({ - isTruffle: true, - tokens: ["fUSDCx", "fDAIx"], - version: "test", - }); - await sf.initialize(); - assert.equal(await sf.tokens.fUSDC.symbol(), "fUSDC"); - assert.equal(await sf.tokens.fDAI.symbol(), "fDAI"); - assert.equal(await sf.tokens.fUSDCx.symbol(), "fUSDCx"); - assert.equal(await sf.tokens.fDAIx.symbol(), "fDAIx"); - }); - - it("failed due to unregistered in resolver", async () => { - const sf = new SuperfluidSDK.Framework({ - tokens: ["fML"], - isTruffle: true, - version: "test", - }); - await expectRevert( - sf.initialize(), - "Super Token for fML cannot be found" - ); - }); - - it("failed due to no super token wrapper", async () => { - await deployTestToken( - t.createErrorHandler(), - [":", "SASHIMI"], - { - from: admin, - isTruffle: true, - } - ); - const sf = new SuperfluidSDK.Framework({ - isTruffle: true, - tokens: ["SASHIMI"], - version: "test", - }); - await expectRevert( - sf.initialize(), - "Super Token for SASHIMI cannot be found" - ); - }); - }); - }); - - describe("createERC20Wrapper", () => { - let sf; - - beforeEach(async () => { - sf = new SuperfluidSDK.Framework({ - isTruffle: true, - gasReportType: "HTML", - version: "test", - }); - - await sf.initialize(); - }); - - it("create new super token", async () => { - await deployTestToken(t.createErrorHandler(), [":", "MISO"], { - isTruffle: true, - from: admin, - }); - const misoAddress = await sf.resolver.get("tokens.MISO"); - const misoToken = await sf.contracts.TokenInfo.at(misoAddress); - const superMisoToken = await sf.createERC20Wrapper(misoToken, { - from: admin, - }); - assert.equal( - await superMisoToken.getUnderlyingToken.call(), - misoAddress - ); - }); - - after(() => { - sf.generateGasReport("Framework.test"); - }); - }); -}); diff --git a/packages/js-sdk/test/InstantDistributionAgreementV1Helper.test.js b/packages/js-sdk/test/InstantDistributionAgreementV1Helper.test.js deleted file mode 100644 index c0952e6f4b..0000000000 --- a/packages/js-sdk/test/InstantDistributionAgreementV1Helper.test.js +++ /dev/null @@ -1,529 +0,0 @@ -const {toWad} = require("@decentral.ee/web3-helpers"); -const TestEnvironment = require("@superfluid-finance/ethereum-contracts/test/TestEnvironment"); - -describe("InstantDistributionAgreementV1Helper class", function () { - this.timeout(300e3); - const t = TestEnvironment.getSingleton(); - - let alice, bob, carol; - let sf; - let superToken; - - before(async () => { - await t.beforeTestSuite({ - isTruffle: false, - web3, - nAccounts: 4, - }); - - ({alice, bob, carol} = t.aliases); - sf = t.sf; - - ({superToken} = await t.deployNewToken("TEST2", { - isTruffle: false, - web3, - doUpgrade: true, - })); - await t.pushEvmSnapshot(); - }); - - after(async () => { - await t.popEvmSnapshot(); - }); - - beforeEach(async function () { - await t.beforeEachTestCase(); - }); - - describe("index", async () => { - it("createIndex", async () => { - const indexId = 1; - await sf.ida.createIndex({ - superToken: superToken.address, - publisher: alice, - indexId, - }); - - const index = await sf.ida.getIndex({ - superToken: superToken.address, - publisher: alice, - indexId, - }); - assert.equal(index.exist, true); - }); - - it("updateIndex", async () => { - const indexId = 1; - await sf.ida.createIndex({ - superToken: superToken.address, - publisher: alice, - indexId, - }); - - const indexValue = 100; - await sf.ida.updateIndex({ - superToken: superToken.address, - publisher: alice, - indexId, - indexValue, - }); - - const index = await sf.ida.getIndex({ - superToken: superToken.address, - publisher: alice, - indexId, - }); - assert.equal(index.indexValue, indexValue); - }); - - it("claim", async () => { - const indexId = 1; - const subscriber = bob; - const publisher = alice; - - await sf.ida.createIndex({ - superToken: superToken.address, - publisher, - indexId, - }); - - await sf.ida.updateSubscription({ - superToken: superToken.address, - publisher, - indexId, - subscriber, - units: toWad("0.001").toString(), - }); - - await sf.ida.updateIndex({ - superToken: superToken.address, - publisher, - indexId, - indexValue: "1000", - }); - - const balanceBefore = await superToken.balanceOf(subscriber); - assert.equal(balanceBefore.toString(), toWad("100").toString()); - - await sf.ida.claim({ - superToken: superToken.address, - publisher, - indexId, - subscriber, - sender: subscriber, - }); - - const balanceAfter = await superToken.balanceOf(subscriber); - assert.equal(balanceAfter.toString(), toWad("101").toString()); - }); - }); - - describe("subscriptions", () => { - const indexId = 1; - let subscriber, publisher; - - before(() => { - subscriber = bob; - publisher = alice; - }); - - beforeEach(async () => { - await sf.ida.createIndex({ - superToken: superToken.address, - publisher, - indexId, - }); - }); - - it("updateSubscription", async () => { - const units = 100; - await sf.ida.updateSubscription({ - superToken: superToken.address, - publisher, - indexId, - subscriber, - units, - }); - - const subscription = await sf.ida.getSubscription({ - superToken: superToken.address, - publisher, - indexId, - subscriber, - }); - assert.equal(subscription.exist, true); - assert.equal(subscription.units, units); - assert.equal(subscription.approved, false); - }); - - it("approveSubscription", async () => { - const units = 100; - await sf.ida.updateSubscription({ - superToken: superToken.address, - publisher, - indexId, - subscriber, - units, - }); - - await sf.ida.approveSubscription({ - superToken: superToken.address, - indexId, - publisher, - subscriber, - }); - - const subscription = await sf.ida.getSubscription({ - superToken: superToken.address, - publisher, - indexId, - subscriber, - }); - assert.equal(subscription.exist, true); - assert.equal(subscription.approved, true); - }); - - it("revokeSubscription", async () => { - const units = 100; - await sf.ida.updateSubscription({ - superToken: superToken.address, - publisher, - indexId, - subscriber, - units, - }); - - await sf.ida.approveSubscription({ - superToken: superToken.address, - indexId, - publisher, - subscriber, - }); - - await sf.ida.revokeSubscription({ - superToken: superToken.address, - indexId, - publisher, - subscriber, - }); - - const subscription = await sf.ida.getSubscription({ - superToken: superToken.address, - publisher, - indexId, - subscriber, - }); - assert.equal(subscription.exist, true); - assert.equal(subscription.approved, false); - }); - - it("deleteSubscription from publisher", async () => { - const units = 100; - await sf.ida.updateSubscription({ - superToken: superToken.address, - publisher, - indexId, - subscriber, - units, - }); - - await sf.ida.deleteSubscription({ - superToken: superToken.address, - indexId, - publisher, - subscriber, - sender: publisher, - }); - - const subscription = await sf.ida.getSubscription({ - superToken: superToken.address, - publisher, - indexId, - subscriber, - }); - assert.equal(subscription.exist, false); - }); - }); - - describe("distribution", () => { - const indexId = 1; - let publisher, subscriber1, subscriber2; - const subscriber1Units = toWad("9"); - const subscriber2Units = toWad("1"); - - before(() => { - publisher = alice; - subscriber1 = bob; - subscriber2 = carol; - }); - - beforeEach(async () => { - await sf.ida.createIndex({ - superToken: superToken.address, - publisher, - indexId, - }); - await sf.ida.updateSubscription({ - superToken: superToken.address, - publisher, - indexId, - subscriber: subscriber1, - units: subscriber1Units.toString(), - }); - await sf.ida.approveSubscription({ - superToken: superToken.address, - indexId, - publisher, - subscriber: subscriber1, - }); - }); - - it("distribute - simple case", async () => { - const amount = toWad(100); - await sf.ida.distribute({ - superToken: superToken.address, - publisher, - indexId, - amount: amount.toString(), - }); - const balance = await superToken.balanceOf(subscriber2); - assert.equal(balance.toString(), toWad(100).toString()); - }); - - it("distribute - multiple subscribers", async () => { - const amount = toWad(100); - // Add the second additional subscriber - await sf.ida.updateSubscription({ - superToken: superToken.address, - publisher, - indexId, - subscriber: subscriber2, - units: subscriber2Units.toString(), - }); - - await sf.ida.approveSubscription({ - superToken: superToken.address, - indexId, - publisher, - subscriber: subscriber2, - }); - - await sf.ida.distribute({ - superToken: superToken.address, - publisher, - indexId, - amount: amount.toString(), - }); - const balance1 = await superToken.balanceOf(subscriber1); - const balance2 = await superToken.balanceOf(subscriber2); - assert.equal(balance1.toString(), toWad(190).toString()); - assert.equal(balance2.toString(), toWad(110).toString()); - }); - }); - - describe("details", () => { - it("getIndex", async () => { - const indexId = 1; - const halfUnits = 50; - const publisher = alice; - - await sf.ida.createIndex({ - superToken: superToken.address, - publisher, - indexId, - }); - - await sf.ida.updateSubscription({ - superToken: superToken.address, - publisher, - indexId, - subscriber: bob, - units: halfUnits, - }); - - await sf.ida.updateSubscription({ - superToken: superToken.address, - publisher, - indexId, - subscriber: carol, - units: halfUnits, - }); - - await sf.ida.approveSubscription({ - superToken: superToken.address, - indexId, - publisher, - subscriber: bob, - }); - - // Carol doesn't approve, so her units are still "pending" - - const index = await sf.ida.getIndex({ - superToken: superToken.address, - publisher, - indexId, - }); - const indexDetails = { - exist: true, - indexValue: "0", - totalUnitsApproved: halfUnits.toString(), - totalUnitsPending: halfUnits.toString(), - }; - assert.deepEqual(index, indexDetails); - }); - - it("listSubscriptions", async () => { - const indexId = 1; - const units = toWad(100); - const publisher = alice; - const subscriber = bob; - await sf.ida.createIndex({ - superToken: superToken.address, - publisher, - indexId, - }); - - await sf.ida.updateSubscription({ - superToken: superToken.address, - publisher, - indexId, - subscriber, - units: units.toString(), - }); - - await sf.ida.approveSubscription({ - superToken: superToken.address, - indexId, - publisher, - subscriber: subscriber, - }); - - assert.deepEqual( - await sf.ida.listSubscriptions({ - superToken: superToken.address, - subscriber, - }), - [ - { - publisher, - indexId, - units: units.toString(), - }, - ] - ); - }); - - it("listSubcribers", async () => { - const units = toWad(100).toString(); - const publisher = alice; - await sf.ida.createIndex({ - superToken: superToken.address, - publisher, - indexId: 1, - }); - await sf.ida.createIndex({ - superToken: superToken.address, - publisher, - indexId: 2, - }); - - await sf.ida.updateSubscription({ - superToken: superToken.address, - publisher, - indexId: 1, - subscriber: bob, - units, - }); - await sf.ida.updateSubscription({ - superToken: superToken.address, - publisher, - indexId: 1, - subscriber: carol, - units, - }); - - assert.deepEqual( - await sf.ida.listSubcribers({ - superToken: superToken.address, - publisher, - indexId: 1, - }), - [ - { - subscriber: bob, - units, - }, - { - subscriber: carol, - units, - }, - ] - ); - - await sf.ida.updateSubscription({ - superToken: superToken.address, - publisher, - indexId: 1, - subscriber: carol, - units: "0", - }); - - assert.deepEqual( - await sf.ida.listSubcribers({ - superToken: superToken.address, - publisher, - indexId: 1, - }), - [ - { - subscriber: bob, - units, - }, - ] - ); - - assert.deepEqual( - await sf.ida.listSubcribers({ - superToken: superToken.address, - publisher, - indexId: 2, - }), - [] - ); - }); - - it("listIndices", async () => { - await sf.ida.createIndex({ - superToken: superToken.address, - publisher: alice, - indexId: 1, - }); - await sf.ida.createIndex({ - superToken: superToken.address, - publisher: alice, - indexId: 2, - }); - await sf.ida.createIndex({ - superToken: superToken.address, - publisher: bob, - indexId: 2, - }); - - assert.deepEqual( - await sf.ida.listIndices({ - superToken: superToken.address, - publisher: alice, - }), - [1, 2] - ); - - assert.deepEqual( - await sf.ida.listIndices({ - superToken: superToken.address, - publisher: bob, - }), - [2] - ); - }); - }); -}); diff --git a/packages/js-sdk/test/User.test.js b/packages/js-sdk/test/User.test.js deleted file mode 100644 index 3f41c475f8..0000000000 --- a/packages/js-sdk/test/User.test.js +++ /dev/null @@ -1,362 +0,0 @@ -const {toBN, toWad} = require("@decentral.ee/web3-helpers"); -const TestEnvironment = require("@superfluid-finance/ethereum-contracts/test/TestEnvironment"); - -const chai = require("chai"); -const chaiAsPromised = require("chai-as-promised"); -chai.use(chaiAsPromised); -const expect = chai.expect; - -const emptyIda = { - ida: { - subscriptions: [], - }, -}; - -describe("User helper class", function () { - this.timeout(300e3); - const t = TestEnvironment.getSingleton(); - - let adminAddress, aliceAddress, bobAddress, carolAddress; - let alice, bob, carol; - let sf; - let superToken; - - before(async () => { - await t.beforeTestSuite({ - isTruffle: false, - web3, - nAccounts: 4, - }); - - ({ - admin: adminAddress, - alice: aliceAddress, - bob: bobAddress, - carol: carolAddress, - } = t.aliases); - ({superToken} = await t.deployNewToken("TEST2", { - isTruffle: false, - web3, - doUpgrade: true, - })); - sf = t.sf; - - await t.pushEvmSnapshot(); - }); - - after(async () => { - await t.popEvmSnapshot(); - }); - - beforeEach(async function () { - await t.beforeEachTestCase(); - alice = sf.user({address: aliceAddress, token: superToken.address}); - bob = sf.user({address: bobAddress, token: superToken.address}); - carol = sf.user({address: carolAddress, token: superToken.address}); - }); - - describe("initialize", () => { - it("user", async () => { - const admin = sf.user({ - address: adminAddress, - token: superToken.address, - }); - assert.equal(admin.address, adminAddress); - assert.equal(admin.token, superToken.address); - assert.equal(admin.sf, sf); - }); - }); - - describe("details", () => { - it("shows user details", async () => { - await alice.flow({ - recipient: bob.address, - flowRate: "38580246913580", // 100 / mo - }); - await bob.flow({ - recipient: carol.address, - flowRate: "19290123456790", // 50 / mo - }); - assert.deepEqual(await alice.details(), { - cfa: { - flows: { - inFlows: [], - outFlows: [ - { - sender: alice.address, - receiver: bob.address, - flowRate: "38580246913580", - }, - ], - }, - netFlow: "-38580246913580", - }, - ...emptyIda, - }); - assert.deepEqual(await bob.details(), { - cfa: { - flows: { - inFlows: [ - { - sender: alice.address, - receiver: bob.address, - flowRate: "38580246913580", - }, - ], - outFlows: [ - { - sender: bob.address, - receiver: carol.address, - flowRate: "19290123456790", - }, - ], - }, - netFlow: "19290123456790", - }, - ...emptyIda, - }); - console.log(JSON.stringify(await bob.details())); - }); - }); - describe("new flows", () => { - it("fail with null recipient", async () => { - await expect( - alice.flow({ - recipient: null, - flowRate: "0", - }) - ).to.be.rejectedWith(/You must provide a recipient and flowRate/); - }); - it("fail with undefined recipient", async () => { - await expect( - alice.flow({ - flowRate: "0", - }) - ).to.be.rejectedWith(/You must provide a recipient and flowRate/); - }); - it("fail with empty string recipient", async () => { - await expect( - alice.flow({ - recipient: "", - flowRate: "0", - }) - ).to.be.rejectedWith(/You must provide a recipient and flowRate/); - }); - it("fail with null flowRate", async () => { - // Using https://github.com/domenic/chai-as-promised - await expect( - alice.flow({ - recipient: adminAddress, - flowRate: null, - }) - ).to.be.rejectedWith(/You must provide a recipient and flowRate/); - }); - it("fail with undefined flowRate", async () => { - // Using https://github.com/domenic/chai-as-promised - await expect( - alice.flow({ - recipient: adminAddress, - }) - ).to.be.rejectedWith(/You must provide a recipient and flowRate/); - }); - it("fail with a number flowRate", async () => { - // Using https://github.com/domenic/chai-as-promised - await expect( - alice.flow({ - recipient: adminAddress, - flowRate: 0, - }) - ).to.be.rejectedWith(/You must provide flowRate as a string/); - }); - it("create a new flow", async () => { - const tx = await alice.flow({ - recipient: bob.address, - flowRate: "38580246913580", // 100 / mo - }); - // validate flow data - const flow = await sf.cfa.getFlow({ - superToken: superToken.address, - sender: alice.address, - receiver: bob.address, - }); - const block = await web3.eth.getBlock(tx.receipt.blockNumber); - assert.equal(flow.timestamp.getTime(), block.timestamp * 1000); - assert.equal(flow.flowRate, "38580246913580"); - assert.notEqual(flow.deposit, "0"); - assert.equal(flow.owedDeposit, "0"); - // validate account net flows - assert.equal( - ( - await sf.cfa.getNetFlow({ - superToken: superToken.address, - account: alice.address, - }) - ).toString(), - "-38580246913580" - ); - assert.equal( - ( - await sf.cfa.getNetFlow({ - superToken: superToken.address, - account: bob.address, - }) - ).toString(), - "38580246913580" - ); - }); - it("create a new flow with onTransaction", async () => { - let txHash; - const tx = await alice.flow({ - recipient: bob.address, - flowRate: "38580246913580", // 100 / mo - onTransaction: (hash) => { - txHash = hash; - }, - }); - assert.equal(txHash, tx.receipt.transactionHash); - }); - it("create a new flow with User object argument", async () => { - const tx = await alice.flow({ - // "bob" rather than "bob.address" - recipient: bob, - flowRate: "38580246913580", // 100 / mo - }); - const flow = await sf.cfa.getFlow({ - superToken: superToken.address, - sender: alice.address, - receiver: bob.address, - }); - const block = await web3.eth.getBlock(tx.receipt.blockNumber); - assert.equal(flow.timestamp.getTime(), block.timestamp * 1000); - assert.equal(flow.flowRate, "38580246913580"); - }); - }); - describe("existing flows", () => { - beforeEach(async () => { - const tx = await alice.flow({ - recipient: bob.address, - flowRate: "38580246913580", // 100 / mo - }); - const flow = await sf.cfa.getFlow({ - superToken: superToken.address, - sender: alice.address, - receiver: bob.address, - }); - const block = await web3.eth.getBlock(tx.receipt.blockNumber); - assert.equal(flow.timestamp.getTime(), block.timestamp * 1000); - assert.equal(flow.flowRate, "38580246913580"); - }); - it("modify an existing flow", async () => { - const tx = await alice.flow({ - recipient: bob.address, - flowRate: "19290123456790", // 50 / mo - }); - - const flow = await sf.cfa.getFlow({ - superToken: superToken.address, - sender: alice.address, - receiver: bob.address, - }); - const block = await web3.eth.getBlock(tx.receipt.blockNumber); - assert.equal(flow.timestamp.getTime(), block.timestamp * 1000); - assert.equal(flow.flowRate, "19290123456790"); - }); - it("modify an existing flow with onTransaction", async () => { - let txHash; - const tx = await alice.flow({ - recipient: bob.address, - flowRate: "19290123456790", // 100 / mo - onTransaction: (hash) => { - txHash = hash; - }, - }); - assert.equal(txHash, tx.receipt.transactionHash); - }); - it("stop an existing flow", async () => { - const ethBefore = await web3.eth.getBalance(alice.address); - await alice.flow({ - recipient: bob.address, - flowRate: "0", // 0 / mo - }); - const ethAfter = await web3.eth.getBalance(alice.address); - assert.isTrue(toBN(ethAfter).lt(toBN(ethBefore))); - assert.equal( - ( - await sf.cfa.getNetFlow({ - superToken: superToken.address, - account: alice.address, - }) - ).toString(), - "0" - ); - assert.equal( - ( - await sf.cfa.getNetFlow({ - superToken: superToken.address, - account: bob.address, - }) - ).toString(), - "0" - ); - }); - it("stop an existing flow with onTransaction", async () => { - let txHash; - const tx = await alice.flow({ - recipient: bob.address, - flowRate: "0", // 100 / mo - onTransaction: (hash) => { - txHash = hash; - }, - }); - assert.equal(txHash, tx.receipt.transactionHash); - }); - }); - describe("pools", () => { - const poolId = 1; - beforeEach(async () => { - await alice.createPool({poolId}); - }); - it("create a new ppol", async () => { - const {exist} = await sf.ida.getIndex({ - superToken: superToken.address, - publisher: aliceAddress, - indexId: poolId, - }); - assert.equal(exist, true); - }); - it("giveShares", async () => { - await alice.giveShares({ - poolId, - shares: 100, - recipient: bobAddress, - }); - const {totalUnitsPending} = await sf.ida.getIndex({ - superToken: superToken.address, - publisher: aliceAddress, - indexId: poolId, - }); - assert.equal(totalUnitsPending, 100); - }); - it("distributeToPool", async () => { - await alice.giveShares({ - poolId, - shares: 100, - recipient: bobAddress, - }); - - await sf.ida.approveSubscription({ - superToken: superToken.address, - publisher: aliceAddress, - indexId: poolId, - subscriber: bobAddress, - }); - - await alice.distributeToPool({ - poolId, - amount: toWad(100).toString(), - }); - const balance = await superToken.balanceOf(bobAddress); - assert.equal(balance.toString(), toWad(200).toString()); - }); - }); -}); diff --git a/packages/js-sdk/test/batchCall.test.js b/packages/js-sdk/test/batchCall.test.js deleted file mode 100644 index ae608e2f0f..0000000000 --- a/packages/js-sdk/test/batchCall.test.js +++ /dev/null @@ -1,505 +0,0 @@ -const TestEnvironment = require("@superfluid-finance/ethereum-contracts/test/TestEnvironment"); - -const { - getErrorResponse, - getMissingArgumentError, - getBatchCallHelpText, -} = require("../src/utils/error"); - -const {batchCall} = require("../src/batchCall"); - -describe("batchCall helper class", function () { - this.timeout(300e3); - const t = TestEnvironment.getSingleton(); - - let adminAddress, aliceAddress; - let sf; - let testToken; - let superToken; - - before(async () => { - await t.beforeTestSuite({ - isTruffle: false, - web3, - nAccounts: 2, - }); - - ({admin: adminAddress, alice: aliceAddress} = t.aliases); - testToken = t.sf.tokens.TEST; - superToken = t.sf.tokens.TESTx; - - sf = t.sf; - sf.batchCall = (calls) => { - console.log(batchCall({agreements: sf.agreements, calls: calls})); - return sf.host.batchCall( - batchCall({agreements: sf.agreements, calls: calls}) - ); - }; - }); - - beforeEach(async function () { - await t.beforeEachTestCase(); - }); - - const exampleERC20TransferFromData = { - token: "0x111...", - amount: "1000000000000000000", - sender: "0xaaa...", - recipient: "0xbbb...", - }; - - describe("Generic bad-case", () => { - it("Calls not provided", async () => { - try { - await sf.batchCall({}); - } catch (err) { - assert.equal( - err.message, - getErrorResponse( - "You must provide an array of calls", - "batchCall" - ) - ); - } - }); - - it("Data not provided", async () => { - try { - await sf.batchCall([{type: 1}]); - } catch (err) { - assert.equal( - err.message, - // eslint-disable-next-line - 'Error: @superfluid-finance/js-sdk batchCall: You did not provide a required argument for "data" in item #0 in your batch call array. Please see https://docs.superfluid.finance/superfluid/docs/batch-call for more help' - ); - } - }); - - it("Type not provided", async () => { - try { - await sf.batchCall([{data: exampleERC20TransferFromData}]); - } catch (err) { - assert.equal( - err.message, - getErrorResponse( - getMissingArgumentError( - "type", - getBatchCallHelpText(0) - ), - "batchCall" - ) - ); - } - }); - - it("Invalid operation", async () => { - const NO_OP_STRING = "NO_OP"; - const NO_OP_NUMBER = 10000; - try { - await sf.batchCall([ - { - type: NO_OP_NUMBER, - data: exampleERC20TransferFromData, - }, - ]); - } catch (err) { - assert.equal( - err.message, - getErrorResponse( - `You provided an invalid operation type "${NO_OP_NUMBER}"${getBatchCallHelpText( - 0 - )}`, - "batchCall" - ) - ); - } - - try { - await sf.batchCall([ - { - type: NO_OP_STRING, - data: exampleERC20TransferFromData, - }, - ]); - } catch (err) { - assert.equal( - err.message, - getErrorResponse( - `You provided an invalid operation type "${NO_OP_STRING}"${getBatchCallHelpText( - 0 - )}`, - "batchCall" - ) - ); - } - }); - }); - describe("ERC20 bad-case", () => { - it("amount not provided", async () => { - try { - await sf.batchCall([ - { - type: "ERC20_APPROVE", - data: { - token: "0x", - }, - }, - ]); - } catch (err) { - assert.equal( - err.message, - getErrorResponse( - getMissingArgumentError( - "amount", - getBatchCallHelpText(0) - ), - "batchCall" - ) - ); - } - }); - it("token not provided", async () => { - try { - await sf.batchCall([ - { - type: "ERC20_APPROVE", - data: { - amount: "1", - }, - }, - ]); - } catch (err) { - assert.equal( - err.message, - getErrorResponse( - getMissingArgumentError( - "token", - getBatchCallHelpText(0) - ), - "batchCall" - ) - ); - } - }); - it("ERC20_APPROVE spender not provided", async () => { - try { - await sf.batchCall([ - { - type: "ERC20_APPROVE", - data: { - token: "0x", - amount: "1", - }, - }, - ]); - } catch (err) { - assert.equal( - err.message, - getErrorResponse( - getMissingArgumentError( - "spender", - getBatchCallHelpText(0) - ), - "batchCall" - ) - ); - } - }); - - it("ERC20_TRANSFER_FROM sender not provided", async () => { - try { - await sf.batchCall([ - { - type: "ERC20_TRANSFER_FROM", - data: { - token: "0x", - amount: "1", - }, - }, - ]); - } catch (err) { - assert.equal( - err.message, - getErrorResponse( - getMissingArgumentError( - "sender", - getBatchCallHelpText(0) - ), - "batchCall" - ) - ); - } - }); - }); - describe("Super Token bad-case", () => { - it("amount not provided", async () => { - try { - await sf.batchCall([ - { - type: "SUPERTOKEN_UPGRADE", - data: { - token: "0x", - }, - }, - ]); - } catch (err) { - assert.equal( - err.message, - getErrorResponse( - getMissingArgumentError( - "amount", - getBatchCallHelpText(0) - ), - "batchCall" - ) - ); - } - }); - - it("token not provided", async () => { - try { - await sf.batchCall([ - { - type: "SUPERTOKEN_UPGRADE", - data: { - amount: "1", - }, - }, - ]); - } catch (err) { - assert.equal( - err.message, - getErrorResponse( - getMissingArgumentError( - "token", - getBatchCallHelpText(0) - ), - "batchCall" - ) - ); - } - }); - }); - describe("Call Agreement bad-case", () => { - it("agreementType not provided", async () => { - try { - await sf.batchCall([ - { - type: "SUPERFLUID_CALL_AGREEMENT", - data: { - method: "createFlow", - arguments: [ - "0x", // Token address - "0x", // Flow recipient - "1", // Flow rate - "0x", - ], - }, - }, - ]); - } catch (err) { - assert.equal( - err.message, - getErrorResponse( - getMissingArgumentError( - "agreementType", - getBatchCallHelpText(0) - ), - "batchCall" - ) - ); - } - }); - - it("Invalid agreementType", async () => { - try { - await sf.batchCall([ - { - type: "SUPERFLUID_CALL_AGREEMENT", - data: { - agreementType: "NO_OP", - method: "createFlow", - arguments: [ - "0x", // Token address - "0x", // Flow recipient - "1", // Flow rate - "0x", - ], - }, - }, - ]); - } catch (err) { - assert.equal( - err.message, - getErrorResponse( - "You provided an invalid agreementType" + - getBatchCallHelpText(0), - "batchCall" - ) - ); - } - }); - - it("method not provided", async () => { - try { - await sf.batchCall([ - { - type: "SUPERFLUID_CALL_AGREEMENT", - data: { - agreementType: "CFA", - arguments: [ - "0x", // Token address - "0x", // Flow recipient - "1", // Flow rate - "0x", - ], - }, - }, - ]); - } catch (err) { - assert.equal( - err.message, - getErrorResponse( - getMissingArgumentError( - "method", - getBatchCallHelpText(0) - ), - "batchCall" - ) - ); - } - }); - it("arguments not provided", async () => { - try { - await sf.batchCall([ - { - type: "SUPERFLUID_CALL_AGREEMENT", - data: { - agreementType: "CFA", - method: "createFlow", - }, - }, - ]); - } catch (err) { - assert.equal( - err.message, - getErrorResponse( - getMissingArgumentError( - "arguments", - getBatchCallHelpText(0) - ), - "batchCall" - ) - ); - } - }); - }); - describe("Super App bad-case", () => { - it("superApp not provided", async () => { - try { - await sf.batchCall([ - { - type: "CALL_APP_ACTION", - data: { - callData: "0x", - }, - }, - ]); - } catch (err) { - assert.equal( - err.message, - getErrorResponse( - getMissingArgumentError( - "superApp", - getBatchCallHelpText(0) - ), - "batchCall" - ) - ); - } - }); - - it("callData not provided", async () => { - try { - await sf.batchCall([ - { - type: "CALL_APP_ACTION", - data: { - superApp: "CFA", - }, - }, - ]); - } catch (err) { - assert.equal( - err.message, - getErrorResponse( - getMissingArgumentError( - "callData", - getBatchCallHelpText(0) - ), - "batchCall" - ) - ); - } - }); - }); - - describe("Tokens Operations", () => { - it("Upgrade and Approve", async () => { - await testToken.approve(superToken.address, "1000000000000000000"); - await sf.batchCall([ - { - type: "SUPERTOKEN_UPGRADE", - data: { - token: superToken.address, - amount: "1000000000000000000", - }, - }, - { - type: "ERC20_APPROVE", - data: { - token: superToken.address, - spender: aliceAddress, - amount: "1000000000000000000", - }, - }, - ]); - await superToken.transferFrom( - adminAddress, - aliceAddress, - "1000000000000000000", - {from: aliceAddress} - ); - assert.equal( - (await superToken.balanceOf(aliceAddress)).toString(), - "1000000000000000000", - "no right balance amount" - ); - }); - - it("Get funds and start stream", async () => { - await sf.batchCall([ - { - type: "SUPERTOKEN_UPGRADE", - data: { - token: superToken.address, - amount: "1000000000000000000", - }, - }, - { - type: "SUPERFLUID_CALL_AGREEMENT", - data: { - agreementType: "CFA", - method: "createFlow", - arguments: [ - superToken.address, - aliceAddress, - "1000000000", - "0x", - ], - }, - }, - ]); - }); - }); -}); diff --git a/packages/js-sdk/test/getConfig.test.js b/packages/js-sdk/test/getConfig.test.js deleted file mode 100644 index 0e2975d501..0000000000 --- a/packages/js-sdk/test/getConfig.test.js +++ /dev/null @@ -1,40 +0,0 @@ -const {assert} = require("chai"); -const SuperfluidSDK = require("../src"); - -describe("getConfig", () => { - before(() => { - delete process.env.RESOLVER_ADDRESS; - }); - - it("goerli v1", async () => { - // goerli - const goerliConfig = SuperfluidSDK.getConfig(5, "v1"); - assert.isNotEmpty(goerliConfig.resolverAddress); - assert.isNotEmpty(goerliConfig.subgraphQueryEndpoint); - assert.isUndefined(goerliConfig.versions); - }); - - it("goerli test", async () => { - // goerli - const goerliConfig = SuperfluidSDK.getConfig(5, "test"); - assert.isNotEmpty(goerliConfig.resolverAddress); - assert.isUndefined(goerliConfig.subgraphQueryEndpoint); - assert.isUndefined(goerliConfig.versions); - }); - - it("defaultConfig", async () => { - // defaultConfig - const defaultConfig = SuperfluidSDK.getConfig(8888); - assert.isUndefined(defaultConfig.resolverAddress); - assert.isUndefined(defaultConfig.versions); - }); - - it("defaultConfig overriding RESOLVER_ADDRESS", async () => { - // test environment - process.env.RESOLVER_ADDRESS = "0x42"; - const testConfig = SuperfluidSDK.getConfig(5555); - assert.equal(testConfig.resolverAddress, "0x42"); - assert.isUndefined(testConfig.versions); - delete process.env.RESOLVER_ADDRESS; - }); -}); diff --git a/packages/js-sdk/test/utils/gasMetering.test.js b/packages/js-sdk/test/utils/gasMetering.test.js deleted file mode 100644 index caa69bee3f..0000000000 --- a/packages/js-sdk/test/utils/gasMetering.test.js +++ /dev/null @@ -1,117 +0,0 @@ -const {expect} = require("chai"); -const {BN} = require("@openzeppelin/test-helpers"); -const GasMetering = require("../../src/utils/gasMetering/gasMetering"); - -describe("GasMetering", function () { - beforeEach(async () => { - this.tx = { - tx: "0xf12344cf8a52ea36e2ba325c15b8faf6147d7fb98c900f39f50fec853f506286", - receipt: { - transactionHash: - "0xf12344cf8a52ea36e2ba325c15b8faf6147d7fb98c900f39f50fec853f506286", - transactionIndex: 0, - blockHash: - "0x362333884391810d9a675c8639b4062abeb990604b25ff9ef3db6199d8901874", - blockNumber: 35, - from: "0xf17f52151ebef6c7334fad080c5704d77216b732", - to: "0x9fbda871d559710256a2502a2517b794b482db40", - gasUsed: 100000, - cumulativeGasUsed: 100000, - contractAddress: null, - logs: [], - status: true, - logsBloom: "0x00...", - rawLogs: [[{}]], - }, - logs: [], - }; - - this.gasPrice = "1000000000"; // 1gwei - }); - - it("should add transaction log", async () => { - const gasMeter = new GasMetering(web3, "JSON", this.gasPrice); - - gasMeter.pushTx(this.tx, "SomeAction"); - const record = gasMeter.records[0]; - expect(record.action).to.be.equal("SomeAction"); - expect(record.txHash).to.be.equal(this.tx.tx); - expect(record.gas).to.be.bignumber.equal(new BN(100000)); - const expectedCost = new BN(100000).mul(new BN(this.gasPrice)); - expect(record.cost).to.be.bignumber.equal(expectedCost); - }); - - it("should calculate aggregates", async () => { - const gasMeter = new GasMetering(web3, "JSON", this.gasPrice); - - gasMeter.pushTx(this.tx, "SomeAction"); - gasMeter.pushTx(this.tx, "SomeAction"); - gasMeter.pushTx(this.tx, "SomeAction2"); - const bucket = gasMeter.aggregates.SomeAction; - expect(bucket.totalGas).to.be.bignumber.equal(new BN(200000)); - expect(bucket.totalTx).to.be.bignumber.equal(new BN(2)); - const expectedCost = new BN(200000).mul(new BN(this.gasPrice)); - expect(bucket.totalCost).to.be.bignumber.equal(expectedCost); - const avgGas = new BN(200000).div(new BN(2)); - expect(bucket.avgGas).to.be.bignumber.equal(avgGas); - const avgCost = expectedCost.div(new BN(2)); - expect(bucket.avgCost).to.be.bignumber.equal(avgCost); - }); - - it("should format correctly", async () => { - const gasMeter = new GasMetering(web3, "JSON", this.gasPrice); - - gasMeter.pushTx(this.tx, "SomeAction"); - gasMeter.pushTx(this.tx, "SomeAction"); - gasMeter.pushTx(this.tx, "SomeAction2"); - const result = gasMeter._format(); - - expect(result).to.be.deep.equal({ - aggregates: { - SomeAction: { - action: "SomeAction", - totalTx: "2", - totalGas: "200000", - avgGas: "100000", - maxGas: "100000", - minGas: "100000", - totalCost: "0.0002 ETH", - avgCost: "0.0001 ETH", - }, - SomeAction2: { - action: "SomeAction2", - avgCost: "0.0001 ETH", - avgGas: "100000", - maxGas: "100000", - minGas: "100000", - totalCost: "0.0001 ETH", - totalGas: "100000", - totalTx: "1", - }, - }, - executedTxs: [ - { - action: "SomeAction", - txHash: "0xf12344cf8a52ea36e2ba325c15b8faf6147d7fb98c900f39f50fec853f506286", - gas: "100000", - gasPrice: "1 GWEI", - cost: "0.0001 ETH", - }, - { - action: "SomeAction", - txHash: "0xf12344cf8a52ea36e2ba325c15b8faf6147d7fb98c900f39f50fec853f506286", - gas: "100000", - gasPrice: "1 GWEI", - cost: "0.0001 ETH", - }, - { - action: "SomeAction2", - txHash: "0xf12344cf8a52ea36e2ba325c15b8faf6147d7fb98c900f39f50fec853f506286", - gas: "100000", - gasPrice: "1 GWEI", - cost: "0.0001 ETH", - }, - ], - }); - }); -}); diff --git a/packages/js-sdk/truffle-config.js b/packages/js-sdk/truffle-config.js deleted file mode 100644 index 1dbc873978..0000000000 --- a/packages/js-sdk/truffle-config.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * This truffle-config is only used for testing the js-sdk. - * - * See the @superfluid-finance/ethereum-contracts package for a good example. - **/ -const path = require("path"); -module.exports = { - // use pre-built artifacts from ethereum-contracts - contracts_build_directory: path.join( - __dirname, - "../ethereum-contracts/build/contracts" - ), - // Configure your compilers - compilers: { - solc: { - version: "0.8.16", // Fetch exact version from solc-bin (default: truffle's version) - settings: { - // See the solidity docs for advice about optimization and evmVersion - optimizer: { - enabled: true, - runs: 200, - }, - // evmVersion: use default - }, - }, - }, - networks: { - /// For truffle development environment - development: { - host: "127.0.0.1", - network_id: "4447", - port: 47545, - - // workaround to improve testing speed - // see https://github.com/trufflesuite/truffle/issues/3522 - disableConfirmationListener: true, - }, - }, -}; diff --git a/packages/js-sdk/tsconfig.json b/packages/js-sdk/tsconfig.json deleted file mode 100644 index eac8d2afaf..0000000000 --- a/packages/js-sdk/tsconfig.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "include": [ - "./src/**/*.d.ts" - ], - "exclude": [ - "dist", - "node_modules", - "reports", - ], - "compilerOptions": { - /* Visit https://aka.ms/tsconfig.json to read more about this file */ - "types": [ - "bn.js", - "node" - ], - /* Basic Options */ - // "incremental": true, /* Enable incremental compilation */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ - "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ - // "lib": [], /* Specify library files to be included in the compilation. */ - "allowJs": true, /* Allow javascript files to be compiled. */ - // "checkJs": true, /* Report errors in .js files. */ - // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */ - // "declaration": true, /* Generates corresponding '.d.ts' file. */ - // "emitDeclarationOnly": true, - // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ - // "sourceMap": true, /* Generates corresponding '.map' file. */ - // "outFile": "./", /* Concatenate and emit output to single file. */ - // "outDir": "./", /* Redirect output structure to the directory. */ - // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ - // "composite": true, /* Enable project compilation */ - // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ - // "removeComments": true, /* Do not emit comments to output. */ - // "noEmit": true, /* Do not emit outputs. */ - // "importHelpers": true, /* Import emit helpers from 'tslib'. */ - // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ - // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ - - /* Strict Type-Checking Options */ - "strict": true, /* Enable all strict type-checking options. */ - "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ - "strictNullChecks": true, /* Enable strict null checks. */ - // "strictFunctionTypes": true, /* Enable strict checking of function types. */ - // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ - // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ - // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ - // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ - - /* Additional Checks */ - // "noUnusedLocals": true, /* Report errors on unused locals. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ - // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ - // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */ - - /* Module Resolution Options */ - // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ - // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ - // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ - // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ - // "typeRoots": [], /* List of folders to include type definitions from. */ - // "types": [], /* Type declaration files to be included in compilation. */ - // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ - "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ - // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - - /* Source Map Options */ - // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ - // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ - - /* Experimental Options */ - // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ - // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - - /* Advanced Options */ - "skipLibCheck": true, /* Skip type checking of declaration files. */ - "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ - } -} diff --git a/packages/js-sdk/webpack.config.js b/packages/js-sdk/webpack.config.js deleted file mode 100644 index 08e3490d5f..0000000000 --- a/packages/js-sdk/webpack.config.js +++ /dev/null @@ -1,32 +0,0 @@ -const path = require("path"); -/* eslint-disable no-unused-vars */ -const webpack = require("webpack"); -/* eslint-enable no-unused-vars */ -module.exports = { - mode: "development", - entry: "./src/index.js", - output: { - path: path.resolve(__dirname, "dist"), - filename: "index.js", - library: "@superfluid-finance/js-sdk", - libraryTarget: "umd", - umdNamedDefine: true, - }, - resolve: { - fallback: { - // Webpack 5, we must explicitly exclude @truffle/contract polyfills - os: false, - fs: false, - url: false, - assert: false, - path: false, - stream: false, - https: false, - http: false, - crypto: false, - }, - }, - externals: { - "@truffle/contract": "@truffle/contract", - }, -}; diff --git a/packages/sdk-core/tasks/setupTestEnvironment.sh b/packages/sdk-core/tasks/setupTestEnvironment.sh index 0e2c8f2176..7a4f09802e 100755 --- a/packages/sdk-core/tasks/setupTestEnvironment.sh +++ b/packages/sdk-core/tasks/setupTestEnvironment.sh @@ -3,11 +3,6 @@ # make sure that if any step fails, the script fails set -xe -# build ABIs for local contract deployment -cd ../js-sdk -chmod +x ./tasks/build-abi-js.sh -./tasks/build-abi-js.sh - # uses built ABIs for local contract deployment cd ../subgraph yarn deploy-contracts-local diff --git a/packages/subgraph/README.md b/packages/subgraph/README.md index 8ca5271866..6a5fdd579d 100644 --- a/packages/subgraph/README.md +++ b/packages/subgraph/README.md @@ -3,9 +3,6 @@
Superfluid logo

- - Version - License: MIT @@ -281,24 +278,6 @@ Try running sudo killall containerd-shim ``` -### Contracts - -Poke around at the contracts using truffle console. See our docs [Using Superfluid with truffle console](https://docs.superfluid.finance/superfluid/docs/setup-truffle-console) for more help. - -```bash -truffle console --network ganache - -const SuperfluidSDK = require("@superfluid-finance/js-sdk"); -# For ganache -sf = new SuperfluidSDK.Framework({web3, version: "test"}); -# For xDAI / testnets / etc -sf = new SuperfluidSDK.Framework({web3, resolver: "0xD2009765189164b495c110D61e4D301729079911"}); - -await sf.initialize(); - -const [admin, bob, carol, dan] = accounts; -``` - ### Subgraph Another way to perform a sanity check is using a http query with the following: diff --git a/packages/subgraph/tasks/testenv-ctl.sh b/packages/subgraph/tasks/testenv-ctl.sh index e24d71d9a8..2d8af62cbd 100755 --- a/packages/subgraph/tasks/testenv-ctl.sh +++ b/packages/subgraph/tasks/testenv-ctl.sh @@ -17,10 +17,6 @@ if [ "$CMD" == "start" ];then cd ../subgraph yarn getAbi yarn run generate-ethers-types - cd ../js-sdk - # Get abi.js file for js-sdk to deploy locally - chmod +x ./tasks/build-abi-js.sh - ./tasks/build-abi-js.sh cd ../sdk-core # build sdk-core because of auto linking to dependency yarn build diff --git a/tasks/check-changeset.sh b/tasks/check-changeset.sh index 6074089334..b894dc2442 100755 --- a/tasks/check-changeset.sh +++ b/tasks/check-changeset.sh @@ -39,12 +39,7 @@ if ! [ -z "$GITHUB_ENV" ];then if grep -E "^packages/ethereum-contracts/(contracts/|scripts/|test/|truffle-config.js|package.json)" changed-files.list;then BUILD_ETHEREUM_CONTRACTS=1 BUILD_SUBGRAPH=1 - echo Ethereum contracts, JS-SDK, and Subgraph will be tested. - fi - # if js-sdk package changed - if grep -E "^packages/js-sdk/(src/|scripts/|test/|truffle-config.js|package.json)" changed-files.list;then - BUILD_ETHEREUM_CONTRACTS=1 - echo JS-SDK and Ethereum contracts will be tested. + echo Ethereum contracts and Subgraph will be tested. fi # if sdk-core package changed if grep -E "^packages/sdk-core/(src/|test/|package.json)" changed-files.list;then