├── .eslintignore ├── .eslintrc ├── .github └── workflows │ └── build.yml ├── .gitignore ├── .vscode └── settings.json ├── LICENSE ├── README.md ├── fixup.sh ├── package.json ├── src ├── cache │ ├── browser-cache-provider.ts │ └── index.ts ├── config │ ├── abis │ │ └── index.ts │ ├── constants.ts │ ├── index.ts │ ├── internal.ts │ ├── networks │ │ ├── arbitrum.ts │ │ ├── base-goerli.ts │ │ ├── bsc.ts │ │ ├── ethereum.ts │ │ ├── fuji.ts │ │ ├── index.ts │ │ └── mumbai.ts │ └── store │ │ ├── definition.ts │ │ └── index.ts ├── core │ ├── claimsProcessor.ts │ ├── cover.ts │ ├── cxToken.ts │ ├── governance.ts │ ├── index.ts │ ├── liquidity.ts │ ├── policy.ts │ ├── reassurance.ts │ └── resolution.ts ├── entities │ ├── Token.ts │ └── index.ts ├── index.ts ├── net │ ├── index.ts │ └── ipfs-client.ts ├── packages │ └── ethers-multicall │ │ ├── LICENSE │ │ ├── README.md │ │ └── src │ │ ├── abi.ts │ │ ├── abi │ │ └── multicall.ts │ │ ├── call.ts │ │ ├── calls.ts │ │ ├── contract.ts │ │ ├── index.ts │ │ ├── provider.ts │ │ └── types.ts ├── registry │ ├── BondPool.ts │ ├── CachedStoreAddress.ts │ ├── ClaimsProcessor.ts │ ├── Cover.ts │ ├── Governance.ts │ ├── IERC20.ts │ ├── IUniswapV2FactoryLike.ts │ ├── IUniswapV2PairLike.ts │ ├── IUniswapV2RouterLike.ts │ ├── MemberResolver.ts │ ├── NPMToken.ts │ ├── PolicyContract.ts │ ├── Protocol.ts │ ├── Reassurance.ts │ ├── Resolution.ts │ ├── Stablecoin.ts │ ├── Staking.ts │ ├── StakingPools.ts │ ├── Store.ts │ ├── Vault.ts │ └── index.ts ├── types │ ├── ChainId.ts │ ├── CoverStatus.ts │ ├── Exceptions │ │ ├── BaseError.ts │ │ ├── DuplicateCoverError.ts │ │ ├── GenericError.ts │ │ ├── InvalidAccountError.ts │ │ ├── InvalidChainIdError.ts │ │ ├── InvalidCoverKeyError.ts │ │ ├── InvalidProductKeyError.ts │ │ ├── InvalidReportError.ts │ │ ├── InvalidSignerError.ts │ │ ├── InvalidStoreError.ts │ │ ├── UnsupportedBlockchainError.ts │ │ └── index.ts │ ├── IApproveTransactionArgs.ts │ ├── ICacheProvider.ts │ ├── ICoverInfo.ts │ ├── ICoverInfoStorage.ts │ ├── INetwork.ts │ ├── IPolicyFeeArgs.ts │ ├── IProductInfo.ts │ ├── IProductInfoStorage.ts │ ├── IReportingInfo.ts │ ├── IReportingInfoStorage.ts │ ├── IStoreCandidate.ts │ ├── IToken.ts │ ├── IWrappedResult.ts │ ├── PolicyDuration.ts │ ├── SDKInternalStorage.ts │ ├── Status.ts │ └── index.ts └── utils │ ├── contract.ts │ ├── date.ts │ ├── erc20-utils.ts │ ├── index.ts │ ├── ipfs.ts │ ├── key-util.ts │ ├── local-storage.ts │ ├── numbers.ts │ ├── pricing │ ├── index.ts │ ├── lp.ts │ ├── pod.ts │ └── token.ts │ ├── signer.ts │ ├── store.ts │ └── uniswap-v2 │ ├── index.ts │ └── pair.ts ├── tsconfig-base.json ├── tsconfig-cjs.json ├── tsconfig.json └── yarn.lock /.eslintignore: -------------------------------------------------------------------------------- 1 | dist 2 | node_modules 3 | src/packages/**/*.ts -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "overrides": [ 3 | { 4 | "files": [ 5 | "*.js", 6 | "*.jsx", 7 | "*.ts", 8 | "*.tsx" 9 | ], 10 | "extends": "standard-with-typescript" 11 | } 12 | ], 13 | "rules": { 14 | "import/extensions": [ 15 | "error", 16 | "always" 17 | ] 18 | } 19 | } -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: '**' 6 | pull_request: 7 | # The branches below must be a subset of the branches above 8 | branches: [main, develop] 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - name: Checkout 16 | uses: actions/checkout@v3 17 | 18 | - name: Setup Volta 19 | uses: volta-cli/action@v4 20 | 21 | - name: Check versions 22 | run: node -v && npm -v && yarn -v 23 | 24 | - name: Install dependencies 25 | run: yarn install --frozen-lockfile 26 | 27 | - name: Lint 28 | run: yarn run lint 29 | 30 | - name: Build 31 | run: yarn run build 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .* 2 | node_modules 3 | yarn-error.log 4 | dist -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.tabSize": 2, 3 | "editor.foldingStrategy": "indentation", 4 | "editor.wrappingIndent": "indent", 5 | "editor.insertSpaces": true, 6 | "editor.defaultFormatter": "vscode.typescript-language-features", 7 | "editor.autoIndent": "none", 8 | "editor.formatOnSaveMode": "file", 9 | "editor.padding.top": 24, 10 | "editor.formatOnSave": true, 11 | "[typescript]": { 12 | "editor.formatOnSave": false, 13 | "editor.defaultFormatter": "vscode.typescript-language-features", 14 | "editor.codeActionsOnSave": { 15 | "source.fixAll": "explicit" 16 | } 17 | }, 18 | "javascript.format.semicolons": "remove", 19 | "typescript.format.enable": true, 20 | "typescript.format.insertSpaceBeforeFunctionParenthesis": true, 21 | "tsImportSorter.configuration.development.enableDebug": false, 22 | "tsImportSorter.configuration.hasSemicolon": false, 23 | "tsImportSorter.configuration.trailingComma": "none", 24 | "cSpell.words": [ 25 | "arbitrum", 26 | "cxtoken", 27 | "distrib", 28 | "ethersproject", 29 | "ierc", 30 | "ipfs", 31 | "keccak", 32 | "microbundle", 33 | "neptunemutual", 34 | "Pausable", 35 | "tsconfigs", 36 | "Unstakable", 37 | "unstake", 38 | "unstaken", 39 | "wbnb", 40 | "wmatic" 41 | ] 42 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 tokyo 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Neptune Mutual SDK 2 | 3 | The Neptune Mutual SDK assists developers to build on top of Neptune Mutual protocol. The SDK supports any Javascript environment so that you can interact with the SDK from both frontend and backend. 4 | 5 | **Install Package** 6 | 7 | ``` 8 | npm install @neptunemutual/sdk 9 | ``` 10 | 11 | **Requirements** 12 | 13 | - Node version: >= v18 14 | 15 | ## Multiple Blockchain Support 16 | 17 | Since the SDK supports multiple blockchains, you may want to quickly check the list of supported blockchains before you actually implement anything. 18 | 19 | ```javascript 20 | import { ChainId } from '@neptunemutual/sdk' 21 | 22 | console.info('Supported Chains %s', ChainId) 23 | 24 | /******************************************** 25 | Supported Chains { 26 | '1': 'Ethereum', 27 | '42161': 'Arbitrum', 28 | '3': 'Ropsten', 29 | '56': 'BinanceSmartChain', 30 | '43113': 'Fuji', 31 | '80001': 'Mumbai', 32 | Ethereum: 1, 33 | Arbitrum: 42161, 34 | Ropsten: 3, 35 | BinanceSmartChain: 56, 36 | Fuji: 43113, 37 | Mumbai: 80001 38 | } 39 | ********************************************/ 40 | ``` 41 | 42 | ## Signer or Provider 43 | 44 | The SDK automatically creates a default readonly provider for you. Therefore, you do not need to specify a signer or provider for such operations. However, for write operations, you must pass a signer as the last argument. 45 | 46 | **Getting Cover Info by Passing a Provider** 47 | 48 | ```javascript 49 | import { JsonRpcProvider } from '@ethersproject/providers' 50 | import { Wallet } from '@ethersproject/wallet' 51 | import { ChainId, cover } from '@neptunemutual/sdk' 52 | 53 | const myProvider = () => { 54 | const fakePrivateKey = '0586782a6b30a2526f960bfde45db0470c51919c0ac2ae9ad5ad39b847955109' 55 | const provider = new JsonRpcProvider('https://rpc-mumbai.maticvigil.com') 56 | return new Wallet(fakePrivateKey, provider) 57 | } 58 | 59 | const readCoverInfo = async () => { 60 | const key = '0x70726f746f3a636f6e7472616374733a636f7665723a6366633a303100000001' 61 | const provider = myProvider() 62 | 63 | const coverInfo = await cover.getCoverInfo(ChainId.Mumbai, key, provider) 64 | console.log(coverInfo) 65 | } 66 | 67 | readCoverInfo() 68 | ``` 69 | 70 | In this case, you're only reading from the blockchain. The above code can be simplified to this: 71 | 72 | 73 | ```javascript 74 | import { ChainId, cover } from '@neptunemutual/sdk' 75 | 76 | const readCoverInfo = async () => { 77 | const key = '0x70726f746f3a636f6e7472616374733a636f7665723a6366633a303100000001' 78 | 79 | const coverInfo = await cover.getCoverInfo(ChainId.Mumbai, key) 80 | console.log(coverInfo) 81 | } 82 | 83 | readCoverInfo() 84 | ``` 85 | 86 | ## Initialize 87 | 88 | Certain functionality of the SDK depends on store smart contract. Store contract address can be set using the `initialize` function 89 | 90 | ```js 91 | import sdk, { ChainId } from '@neptunemutual/sdk' 92 | 93 | sdk.initialize({ 94 | store: { 95 | [ChainId.Mumbai]: '0x...' 96 | } 97 | }) 98 | 99 | const coverKey = sdk.utils.keyUtil.toBytes32('binance') 100 | const coverInfo = await sdk.cover.getCoverInfo(ChainId.Mumbai, coverKey, provider) 101 | 102 | console.log(coverInfo); 103 | ``` 104 | 105 | [Read the Full Documentation](https://neptunemutual.com/docs/sdk/quickstart/) 106 | -------------------------------------------------------------------------------- /fixup.sh: -------------------------------------------------------------------------------- 1 | # chmod u+x fixup.sh 2 | echo "Fixing build files..." 3 | 4 | cat >dist/cjs/package.json <dist/mjs/package.json <=10" 12 | }, 13 | "type": "module", 14 | "main": "dist/cjs/index.js", 15 | "module": "dist/mjs/index.js", 16 | "types": "dist/mjs/index.d.ts", 17 | "exports": { 18 | ".": { 19 | "import": "./dist/mjs/index.js", 20 | "require": "./dist/cjs/index.js" 21 | } 22 | }, 23 | "scripts": { 24 | "build": "rm -rf ./dist && yarn compile", 25 | "compile": "tsc -p tsconfig.json && tsc -p tsconfig-cjs.json && ./fixup.sh", 26 | "dev": "nodemon --watch src -e ts --exec \"npm run compile\"", 27 | "lint": "eslint .", 28 | "fix": "eslint . --fix", 29 | "prepublishOnly": "npm run build" 30 | }, 31 | "dependencies": { 32 | "@ethersproject/abstract-signer": "5.4.1", 33 | "@ethersproject/constants": "5.4.0", 34 | "@ethersproject/contracts": "5.4.1", 35 | "@ethersproject/providers": "5.4.5", 36 | "@ethersproject/solidity": "5.4.0", 37 | "@ethersproject/strings": "5.4.0", 38 | "tslib": "^2.6.2", 39 | "uuid": "8.3.2" 40 | }, 41 | "devDependencies": { 42 | "@types/node": "18.11.11", 43 | "@types/uuid": "8.3.4", 44 | "@typescript-eslint/eslint-plugin": "^6.4.0", 45 | "@typescript-eslint/parser": "^6.11.0", 46 | "eslint": "^8.0.1", 47 | "eslint-config-standard-with-typescript": "^39.1.1", 48 | "eslint-plugin-import": "^2.25.2", 49 | "eslint-plugin-n": "^15.0.0", 50 | "eslint-plugin-promise": "^6.0.0", 51 | "typescript": "^5.2.2" 52 | }, 53 | "repository": { 54 | "type": "git", 55 | "url": "git+https://github.com/neptune-mutual-blue/sdk.git" 56 | }, 57 | "bugs": { 58 | "url": "https://github.com/neptune-mutual-blue/sdk/issues" 59 | }, 60 | "homepage": "https://github.com/neptune-mutual-blue/sdk#readme", 61 | "volta": { 62 | "node": "18.12.0", 63 | "yarn": "1.22.19" 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/cache/browser-cache-provider.ts: -------------------------------------------------------------------------------- 1 | import { type ICacheProvider } from '../types/ICacheProvider.js' 2 | 3 | class BrowserCacheProvider implements ICacheProvider { 4 | maxAge: number 5 | suffix: string 6 | 7 | constructor () { 8 | this.maxAge = 1000 * 60 * 60 // 1 hour 9 | this.suffix = '-max-age' 10 | } 11 | 12 | getExpiryKey (key: string): string { 13 | return key + this.suffix 14 | } 15 | 16 | get (key: string): string | null { 17 | const value = sessionStorage.getItem(key) 18 | 19 | const now = new Date().getTime() 20 | const expiryKey = this.getExpiryKey(key) 21 | const expired = parseInt(sessionStorage.getItem(expiryKey) ?? '0') 22 | 23 | if (now > expired) { 24 | this.remove(key) 25 | this.remove(expiryKey) 26 | } 27 | 28 | return value 29 | } 30 | 31 | set (key: string, value: string): void { 32 | const expires = new Date().getTime() + this.maxAge 33 | const expiryKey = this.getExpiryKey(key) 34 | 35 | sessionStorage.setItem(key, value) 36 | sessionStorage.setItem(expiryKey, expires.toString()) 37 | } 38 | 39 | remove (key: string): void { 40 | sessionStorage.removeItem(key) 41 | } 42 | } 43 | 44 | export { BrowserCacheProvider } 45 | -------------------------------------------------------------------------------- /src/cache/index.ts: -------------------------------------------------------------------------------- 1 | import { keccak256 as solidityKeccak256 } from '@ethersproject/solidity' 2 | 3 | import { getStoreAddressFromEnvironment } from '../config/store/index.js' 4 | import { type ChainId } from '../types/ChainId.js' 5 | import { type ICacheProvider } from '../types/ICacheProvider.js' 6 | import { localStorageAvailable } from '../utils/local-storage.js' 7 | import { BrowserCacheProvider } from './browser-cache-provider.js' 8 | 9 | const getProvider = (): ICacheProvider | null => { 10 | if (localStorageAvailable()) { 11 | return new BrowserCacheProvider() 12 | } 13 | 14 | return null 15 | } 16 | 17 | const genKey = (chainId: ChainId, nsKey: string): string => { 18 | const store = getStoreAddressFromEnvironment(chainId) 19 | return solidityKeccak256(['uint256', 'address', 'bytes32'], [chainId.toString(), store, nsKey]) 20 | } 21 | 22 | const get = (key: string): string | null => { 23 | const provider = getProvider() 24 | 25 | if (provider != null) { 26 | return provider.get(key) 27 | } 28 | 29 | return null 30 | } 31 | 32 | const set = (key: string, value: string): void => { 33 | const provider = getProvider() 34 | 35 | if (provider != null) { 36 | provider.set(key, value) 37 | } 38 | } 39 | 40 | const remove = (key: string): void => { 41 | const provider = getProvider() 42 | 43 | if (provider != null) { 44 | provider.remove(key) 45 | } 46 | } 47 | 48 | export { genKey, get, remove, set } 49 | -------------------------------------------------------------------------------- /src/config/abis/index.ts: -------------------------------------------------------------------------------- 1 | const IAaveV2LendingPoolLike = [ 2 | 'function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode)', 3 | 'function withdraw(address asset, uint256 amount, address to) returns (uint256)' 4 | ] 5 | 6 | const IBondPool = [ 7 | 'event BondClaimed(address indexed account, uint256 amount)', 8 | 'event BondCreated(address indexed account, uint256 lpTokens, uint256 npmToVest, uint256 unlockDate)', 9 | 'event BondPoolSetup(tuple(address lpToken, address treasury, uint256 bondDiscountRate, uint256 maxBondAmount, uint256 vestingTerm, uint256 npmToTopUpNow) args)', 10 | 'function calculateTokensForLp(uint256 lpTokens) view returns (uint256)', 11 | 'function claimBond()', 12 | 'function createBond(uint256 lpTokens, uint256 minNpmDesired)', 13 | 'function getInfo(address forAccount) view returns (tuple(address lpToken, uint256 marketPrice, uint256 discountRate, uint256 vestingTerm, uint256 maxBond, uint256 totalNpmAllocated, uint256 totalNpmDistributed, uint256 npmAvailable, uint256 bondContribution, uint256 claimable, uint256 unlockDate) info)', 14 | 'function getName() pure returns (bytes32)', 15 | 'function getNpmMarketPrice() view returns (uint256)', 16 | 'function setup(tuple(address lpToken, address treasury, uint256 bondDiscountRate, uint256 maxBondAmount, uint256 vestingTerm, uint256 npmToTopUpNow) args)', 17 | 'function version() pure returns (bytes32)' 18 | ] 19 | 20 | const IClaimsProcessor = [ 21 | 'event BlacklistSet(bytes32 indexed coverKey, bytes32 indexed productKey, uint256 indexed incidentDate, address account, bool status)', 22 | 'event ClaimPeriodSet(bytes32 indexed coverKey, uint256 previous, uint256 current)', 23 | 'event Claimed(address cxToken, bytes32 indexed coverKey, bytes32 indexed productKey, uint256 incidentDate, address indexed account, address reporter, uint256 amount, uint256 reporterFee, uint256 platformFee, uint256 claimed)', 24 | 'function claim(address cxToken, bytes32 coverKey, bytes32 productKey, uint256 incidentDate, uint256 amount)', 25 | 'function getClaimExpiryDate(bytes32 coverKey, bytes32 productKey) view returns (uint256)', 26 | 'function getName() pure returns (bytes32)', 27 | 'function isBlacklisted(bytes32 coverKey, bytes32 productKey, uint256 incidentDate, address account) view returns (bool)', 28 | 'function setBlacklist(bytes32 coverKey, bytes32 productKey, uint256 incidentDate, address[] accounts, bool[] statuses)', 29 | 'function setClaimPeriod(bytes32 coverKey, uint256 value)', 30 | 'function validate(address cxToken, bytes32 coverKey, bytes32 productKey, uint256 incidentDate, uint256 amount) view returns (bool)', 31 | 'function version() pure returns (bytes32)' 32 | ] 33 | 34 | const ICompoundERC20DelegatorLike = [ 35 | 'function mint(uint256 mintAmount) returns (uint256)', 36 | 'function redeem(uint256 redeemTokens) returns (uint256)' 37 | ] 38 | 39 | const ICover = [ 40 | 'event CoverCreated(bytes32 indexed coverKey, string info, string tokenName, string tokenSymbol, bool indexed supportsProducts, bool indexed requiresWhitelist)', 41 | 'event CoverCreationFeeSet(uint256 previous, uint256 current)', 42 | 'event CoverCreatorWhitelistUpdated(address account, bool status)', 43 | 'event CoverInitialized(address indexed stablecoin, bytes32 withName)', 44 | 'event CoverUpdated(bytes32 indexed coverKey, string info)', 45 | 'event CoverUserWhitelistUpdated(bytes32 indexed coverKey, bytes32 indexed productKey, address indexed account, bool status)', 46 | 'event MinCoverCreationStakeSet(uint256 previous, uint256 current)', 47 | 'event MinStakeToAddLiquiditySet(uint256 previous, uint256 current)', 48 | 'event ProductCreated(bytes32 indexed coverKey, bytes32 productKey, string info)', 49 | 'event ProductStateUpdated(bytes32 indexed coverKey, bytes32 indexed productKey, address indexed updatedBy, bool status, string reason)', 50 | 'event ProductUpdated(bytes32 indexed coverKey, bytes32 productKey, string info)', 51 | 'function addCover(tuple(bytes32 coverKey, string info, string tokenName, string tokenSymbol, bool supportsProducts, bool requiresWhitelist, uint256 stakeWithFee, uint256 initialReassuranceAmount, uint256 minStakeToReport, uint256 reportingPeriod, uint256 cooldownPeriod, uint256 claimPeriod, uint256 floor, uint256 ceiling, uint256 reassuranceRate, uint256 leverageFactor) args) returns (address)', 52 | 'function addCovers(tuple(bytes32 coverKey, string info, string tokenName, string tokenSymbol, bool supportsProducts, bool requiresWhitelist, uint256 stakeWithFee, uint256 initialReassuranceAmount, uint256 minStakeToReport, uint256 reportingPeriod, uint256 cooldownPeriod, uint256 claimPeriod, uint256 floor, uint256 ceiling, uint256 reassuranceRate, uint256 leverageFactor)[] args) returns (address[] vaults)', 53 | 'function addProduct(tuple(bytes32 coverKey, bytes32 productKey, string info, bool requiresWhitelist, uint256 productStatus, uint256 efficiency) args)', 54 | 'function addProducts(tuple(bytes32 coverKey, bytes32 productKey, string info, bool requiresWhitelist, uint256 productStatus, uint256 efficiency)[] args)', 55 | 'function checkIfWhitelistedCoverCreator(address account) view returns (bool)', 56 | 'function checkIfWhitelistedUser(bytes32 coverKey, bytes32 productKey, address account) view returns (bool)', 57 | 'function disablePolicy(bytes32 coverKey, bytes32 productKey, bool status, string reason)', 58 | 'function getName() pure returns (bytes32)', 59 | 'function initialize(address stablecoin, bytes32 friendlyName)', 60 | 'function setCoverCreationFee(uint256 value)', 61 | 'function setMinCoverCreationStake(uint256 value)', 62 | 'function setMinStakeToAddLiquidity(uint256 value)', 63 | 'function updateCover(bytes32 coverKey, string info)', 64 | 'function updateCoverCreatorWhitelist(address[] account, bool[] whitelisted)', 65 | 'function updateCoverUsersWhitelist(bytes32 coverKey, bytes32 productKey, address[] accounts, bool[] statuses)', 66 | 'function updateProduct(tuple(bytes32 coverKey, bytes32 productKey, string info, uint256 productStatus, uint256 efficiency) args)', 67 | 'function version() pure returns (bytes32)' 68 | ] 69 | 70 | const ICoverReassurance = [ 71 | 'event PoolCapitalized(bytes32 indexed coverKey, bytes32 indexed productKey, uint256 indexed incidentDate, uint256 amount)', 72 | 'event ReassuranceAdded(bytes32 indexed coverKey, address indexed onBehalfOf, uint256 amount)', 73 | 'event WeightSet(bytes32 indexed coverKey, uint256 weight)', 74 | 'function addReassurance(bytes32 coverKey, address onBehalfOf, uint256 amount)', 75 | 'function capitalizePool(bytes32 coverKey, bytes32 productKey, uint256 incidentDate)', 76 | 'function getName() pure returns (bytes32)', 77 | 'function getReassurance(bytes32 coverKey) view returns (uint256)', 78 | 'function setWeight(bytes32 coverKey, uint256 weight)', 79 | 'function version() pure returns (bytes32)' 80 | ] 81 | 82 | const ICoverStake = [ 83 | 'event FeeBurned(bytes32 indexed coverKey, uint256 amount)', 84 | 'event StakeAdded(bytes32 indexed coverKey, address indexed account, uint256 amount)', 85 | 'event StakeRemoved(bytes32 indexed coverKey, address indexed account, uint256 amount)', 86 | 'function decreaseStake(bytes32 coverKey, uint256 amount)', 87 | 'function getName() pure returns (bytes32)', 88 | 'function increaseStake(bytes32 coverKey, address account, uint256 amount, uint256 fee)', 89 | 'function stakeOf(bytes32 coverKey, address account) view returns (uint256)', 90 | 'function version() pure returns (bytes32)' 91 | ] 92 | 93 | const ICoverUpdate = [ 94 | 'event CoverDeleted(bytes32 indexed coverKey)', 95 | 'event ProductDeleted(bytes32 indexed coverKey, bytes32 indexed productKey)', 96 | 'function deleteCover(bytes32 coverKey)', 97 | 'function deleteProduct(bytes32 coverKey, bytes32 productKey)', 98 | 'function getName() pure returns (bytes32)', 99 | 'function version() pure returns (bytes32)' 100 | ] 101 | 102 | const ICxToken = [ 103 | 'event Approval(address indexed owner, address indexed spender, uint256 value)', 104 | 'event CoverageStartSet(uint256 policyId, bytes32 coverKey, bytes32 productKey, address account, uint256 effectiveFrom, uint256 amount)', 105 | 'event Transfer(address indexed from, address indexed to, uint256 value)', 106 | 'function COVER_KEY() view returns (bytes32)', 107 | 'function PRODUCT_KEY() view returns (bytes32)', 108 | 'function allowance(address owner, address spender) view returns (uint256)', 109 | 'function approve(address spender, uint256 amount) returns (bool)', 110 | 'function balanceOf(address account) view returns (uint256)', 111 | 'function burn(uint256 amount)', 112 | 'function createdOn() view returns (uint256)', 113 | 'function expiresOn() view returns (uint256)', 114 | 'function getClaimablePolicyOf(address account) view returns (uint256)', 115 | 'function getCoverageStartsFrom(address account, uint256 date) view returns (uint256)', 116 | 'function mint(uint256 policyId, bytes32 coverKey, bytes32 productKey, address to, uint256 amount)', 117 | 'function totalSupply() view returns (uint256)', 118 | 'function transfer(address recipient, uint256 amount) returns (bool)', 119 | 'function transferFrom(address sender, address recipient, uint256 amount) returns (bool)' 120 | ] 121 | 122 | const ICxTokenFactory = [ 123 | 'event CxTokenDeployed(address cxToken, address store, bytes32 indexed coverKey, bytes32 indexed productKey, string tokenName, uint256 indexed expiryDate)', 124 | 'function deploy(bytes32 coverKey, bytes32 productKey, string tokenName, uint256 expiryDate) returns (address)', 125 | 'function getName() pure returns (bytes32)', 126 | 'function version() pure returns (bytes32)' 127 | ] 128 | 129 | const IERC20 = [ 130 | 'event Approval(address indexed owner, address indexed spender, uint256 value)', 131 | 'event Transfer(address indexed from, address indexed to, uint256 value)', 132 | 'function allowance(address owner, address spender) view returns (uint256)', 133 | 'function approve(address spender, uint256 amount) returns (bool)', 134 | 'function balanceOf(address account) view returns (uint256)', 135 | 'function totalSupply() view returns (uint256)', 136 | 'function transfer(address recipient, uint256 amount) returns (bool)', 137 | 'function transferFrom(address sender, address recipient, uint256 amount) returns (bool)' 138 | ] 139 | 140 | const IERC20Detailed = [ 141 | 'event Approval(address indexed owner, address indexed spender, uint256 value)', 142 | 'event Transfer(address indexed from, address indexed to, uint256 value)', 143 | 'function allowance(address owner, address spender) view returns (uint256)', 144 | 'function approve(address spender, uint256 amount) returns (bool)', 145 | 'function balanceOf(address account) view returns (uint256)', 146 | 'function decimals() view returns (uint8)', 147 | 'function mint(uint256 amount)', 148 | 'function name() view returns (string)', 149 | 'function symbol() view returns (string)', 150 | 'function totalSupply() view returns (uint256)', 151 | 'function transfer(address recipient, uint256 amount) returns (bool)', 152 | 'function transferFrom(address sender, address recipient, uint256 amount) returns (bool)' 153 | ] 154 | 155 | const IFinalization = [ 156 | 'event Finalized(bytes32 indexed coverKey, bytes32 indexed productKey, address finalizer, uint256 indexed incidentDate)', 157 | 'function finalize(bytes32 coverKey, bytes32 productKey, uint256 incidentDate)' 158 | ] 159 | 160 | const IGovernance = [ 161 | 'event Attested(bytes32 indexed coverKey, bytes32 indexed productKey, address witness, uint256 indexed incidentDate, uint256 stake)', 162 | 'event Disputed(bytes32 indexed coverKey, bytes32 indexed productKey, address reporter, uint256 indexed incidentDate, string info, uint256 initialStake)', 163 | 'event FirstReportingStakeSet(bytes32 coverKey, uint256 previous, uint256 current)', 164 | 'event Refuted(bytes32 indexed coverKey, bytes32 indexed productKey, address witness, uint256 indexed incidentDate, uint256 stake)', 165 | 'event Reported(bytes32 indexed coverKey, bytes32 indexed productKey, address reporter, uint256 indexed incidentDate, string info, uint256 initialStake, uint256 resolutionTimestamp)', 166 | 'event ReporterCommissionSet(uint256 previous, uint256 current)', 167 | 'event ReportingBurnRateSet(uint256 previous, uint256 current)', 168 | 'function attest(bytes32 coverKey, bytes32 productKey, uint256 incidentDate, uint256 stake)', 169 | 'function dispute(bytes32 coverKey, bytes32 productKey, uint256 incidentDate, string info, uint256 stake)', 170 | 'function getActiveIncidentDate(bytes32 coverKey, bytes32 productKey) view returns (uint256)', 171 | 'function getAttestation(bytes32 coverKey, bytes32 productKey, address who, uint256 incidentDate) view returns (uint256 myStake, uint256 totalStake)', 172 | 'function getFirstReportingStake(bytes32 coverKey) view returns (uint256)', 173 | 'function getName() pure returns (bytes32)', 174 | 'function getRefutation(bytes32 coverKey, bytes32 productKey, address who, uint256 incidentDate) view returns (uint256 myStake, uint256 totalStake)', 175 | 'function getReporter(bytes32 coverKey, bytes32 productKey, uint256 incidentDate) view returns (address)', 176 | 'function getResolutionTimestamp(bytes32 coverKey, bytes32 productKey) view returns (uint256)', 177 | 'function getStakes(bytes32 coverKey, bytes32 productKey, uint256 incidentDate) view returns (uint256, uint256)', 178 | 'function getStakesOf(bytes32 coverKey, bytes32 productKey, uint256 incidentDate, address account) view returns (uint256, uint256)', 179 | 'function getStatus(bytes32 coverKey, bytes32 productKey) view returns (uint256)', 180 | 'function isCoverNormal(bytes32 coverKey) view returns (bool)', 181 | 'function refute(bytes32 coverKey, bytes32 productKey, uint256 incidentDate, uint256 stake)', 182 | 'function report(bytes32 coverKey, bytes32 productKey, string info, uint256 stake)', 183 | 'function setFirstReportingStake(bytes32 coverKey, uint256 value)', 184 | 'function setReporterCommission(uint256 value)', 185 | 'function setReportingBurnRate(uint256 value)', 186 | 'function version() pure returns (bytes32)' 187 | ] 188 | 189 | const ILendingStrategy = [ 190 | 'event Deposited(bytes32 indexed key, address indexed onBehalfOf, uint256 stablecoinDeposited, uint256 certificateTokenIssued)', 191 | 'event Drained(address indexed asset, uint256 amount)', 192 | 'event LogDeposit(bytes32 indexed name, uint256 counter, uint256 amount, uint256 certificateReceived, uint256 depositTotal, uint256 withdrawalTotal)', 193 | 'event LogWithdrawal(bytes32 indexed name, uint256 counter, uint256 stablecoinWithdrawn, uint256 certificateRedeemed, uint256 depositTotal, uint256 withdrawalTotal)', 194 | 'event Withdrawn(bytes32 indexed key, address indexed sendTo, uint256 stablecoinWithdrawn, uint256 certificateTokenRedeemed)', 195 | 'function deposit(bytes32 coverKey, uint256 amount) returns (uint256 certificateReceived)', 196 | 'function getDepositAsset() view returns (address)', 197 | 'function getDepositCertificate() view returns (address)', 198 | 'function getInfo(bytes32 coverKey) view returns (tuple(uint256 deposits, uint256 withdrawals) info)', 199 | 'function getKey() pure returns (bytes32)', 200 | 'function getName() pure returns (bytes32)', 201 | 'function getWeight() pure returns (uint256)', 202 | 'function version() pure returns (bytes32)', 203 | 'function withdraw(bytes32 coverKey) returns (uint256 stablecoinWithdrawn)' 204 | ] 205 | 206 | const ILiquidityEngine = [ 207 | 'event LiquidityStateUpdateIntervalSet(uint256 duration)', 208 | 'event MaxLendingRatioSet(uint256 ratio)', 209 | 'event RiskPoolingPeriodSet(bytes32 indexed coverKey, uint256 lendingPeriod, uint256 withdrawalWindow)', 210 | 'event StrategyAdded(address indexed strategy)', 211 | 'event StrategyDeleted(address indexed strategy)', 212 | 'event StrategyDisabled(address indexed strategy)', 213 | 'function addBulkLiquidity(tuple(bytes32 coverKey, uint256 amount, uint256 npmStakeToAdd, bytes32 referralCode)[] args)', 214 | 'function addStrategies(address[] strategies)', 215 | 'function deleteStrategy(address strategy)', 216 | 'function disableStrategy(address strategy)', 217 | 'function getActiveStrategies() view returns (address[] strategies)', 218 | 'function getDisabledStrategies() view returns (address[] strategies)', 219 | 'function getMaxLendingRatio() view returns (uint256 ratio)', 220 | 'function getName() pure returns (bytes32)', 221 | 'function getRiskPoolingPeriods(bytes32 coverKey) view returns (uint256 lendingPeriod, uint256 withdrawalWindow)', 222 | 'function setLiquidityStateUpdateInterval(uint256 value)', 223 | 'function setMaxLendingRatio(uint256 ratio)', 224 | 'function setRiskPoolingPeriods(bytes32 coverKey, uint256 lendingPeriod, uint256 withdrawalWindow)', 225 | 'function version() pure returns (bytes32)' 226 | ] 227 | 228 | const IMember = [ 229 | 'function getName() pure returns (bytes32)', 230 | 'function version() pure returns (bytes32)' 231 | ] 232 | 233 | const IPausable = [ 234 | 'function paused() view returns (bool)' 235 | ] 236 | 237 | const IPolicy = [ 238 | 'event CoverPurchased(tuple(address onBehalfOf, bytes32 coverKey, bytes32 productKey, uint256 coverDuration, uint256 amountToCover, bytes32 referralCode) args, address indexed cxToken, uint256 fee, uint256 platformFee, uint256 expiresOn, uint256 policyId)', 239 | 'function getAvailableLiquidity(bytes32 coverKey) view returns (uint256)', 240 | 'function getCommitment(bytes32 coverKey, bytes32 productKey) view returns (uint256)', 241 | 'function getCoverFeeInfo(bytes32 coverKey, bytes32 productKey, uint256 coverDuration, uint256 amountToCover) view returns (tuple(uint256 fee, uint256 utilizationRatio, uint256 totalAvailableLiquidity, uint256 floor, uint256 ceiling, uint256 rate))', 242 | 'function getCoverPoolSummary(bytes32 coverKey, bytes32 productKey) view returns (tuple(uint256 totalAmountInPool, uint256 totalCommitment, uint256 reassuranceAmount, uint256 reassurancePoolWeight, uint256 productCount, uint256 leverage, uint256 productCapitalEfficiency) summary)', 243 | 'function getCxToken(bytes32 coverKey, bytes32 productKey, uint256 coverDuration) view returns (address cxToken, uint256 expiryDate)', 244 | 'function getCxTokenByExpiryDate(bytes32 coverKey, bytes32 productKey, uint256 expiryDate) view returns (address cxToken)', 245 | 'function getExpiryDate(uint256 today, uint256 coverDuration) pure returns (uint256)', 246 | 'function getName() pure returns (bytes32)', 247 | 'function purchaseCover(tuple(address onBehalfOf, bytes32 coverKey, bytes32 productKey, uint256 coverDuration, uint256 amountToCover, bytes32 referralCode) args) returns (address, uint256)', 248 | 'function version() pure returns (bytes32)' 249 | ] 250 | 251 | const IPolicyAdmin = [ 252 | 'event CoverPolicyRateSet(bytes32 indexed coverKey, uint256 floor, uint256 ceiling)', 253 | 'event CoverageLagSet(bytes32 indexed coverKey, uint256 window)', 254 | 'function getCoverageLag(bytes32 coverKey) view returns (uint256)', 255 | 'function getName() pure returns (bytes32)', 256 | 'function getPolicyRates(bytes32 coverKey) view returns (uint256 floor, uint256 ceiling)', 257 | 'function setCoverageLag(bytes32 coverKey, uint256 window)', 258 | 'function setPolicyRatesByKey(bytes32 coverKey, uint256 floor, uint256 ceiling)', 259 | 'function version() pure returns (bytes32)' 260 | ] 261 | 262 | const IPriceOracle = [ 263 | 'function consult(address token, uint256 amountIn) view returns (uint256 amountOut)', 264 | 'function consultPair(uint256 amountIn) view returns (uint256)', 265 | 'function update()' 266 | ] 267 | 268 | const IProtocol = [ 269 | 'event ContractAdded(bytes32 indexed namespace, bytes32 indexed key, address indexed contractAddress)', 270 | 'event ContractUpgraded(bytes32 indexed namespace, bytes32 indexed key, address previous, address indexed current)', 271 | 'event Initialized(tuple(address burner, address uniswapV2RouterLike, address uniswapV2FactoryLike, address npm, address treasury, address priceOracle, uint256 coverCreationFee, uint256 minCoverCreationStake, uint256 minStakeToAddLiquidity, uint256 firstReportingStake, uint256 claimPeriod, uint256 reportingBurnRate, uint256 governanceReporterCommission, uint256 claimPlatformFee, uint256 claimReporterCommission, uint256 flashLoanFee, uint256 flashLoanFeeProtocol, uint256 resolutionCoolDownPeriod, uint256 stateUpdateInterval, uint256 maxLendingRatio, uint256 lendingPeriod, uint256 withdrawalWindow, uint256 policyFloor, uint256 policyCeiling) args)', 272 | 'event MemberAdded(address member)', 273 | 'event MemberRemoved(address member)', 274 | 'event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole)', 275 | 'event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender)', 276 | 'event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender)', 277 | 'function addContract(bytes32 namespace, address contractAddress)', 278 | 'function addContractWithKey(bytes32 namespace, bytes32 coverKey, address contractAddress)', 279 | 'function addContracts(bytes32[] namespaces, bytes32[] keys, address[] contractAddresses)', 280 | 'function addMember(address member)', 281 | 'function getName() pure returns (bytes32)', 282 | 'function getRoleAdmin(bytes32 role) view returns (bytes32)', 283 | 'function grantRole(bytes32 role, address account)', 284 | 'function grantRoles(tuple(address account, bytes32[] roles)[] detail)', 285 | 'function hasRole(bytes32 role, address account) view returns (bool)', 286 | 'function initialize(tuple(address burner, address uniswapV2RouterLike, address uniswapV2FactoryLike, address npm, address treasury, address priceOracle, uint256 coverCreationFee, uint256 minCoverCreationStake, uint256 minStakeToAddLiquidity, uint256 firstReportingStake, uint256 claimPeriod, uint256 reportingBurnRate, uint256 governanceReporterCommission, uint256 claimPlatformFee, uint256 claimReporterCommission, uint256 flashLoanFee, uint256 flashLoanFeeProtocol, uint256 resolutionCoolDownPeriod, uint256 stateUpdateInterval, uint256 maxLendingRatio, uint256 lendingPeriod, uint256 withdrawalWindow, uint256 policyFloor, uint256 policyCeiling) args)', 287 | 'function removeMember(address member)', 288 | 'function renounceRole(bytes32 role, address account)', 289 | 'function revokeRole(bytes32 role, address account)', 290 | 'function upgradeContract(bytes32 namespace, address previous, address current)', 291 | 'function upgradeContractWithKey(bytes32 namespace, bytes32 coverKey, address previous, address current)', 292 | 'function version() pure returns (bytes32)' 293 | ] 294 | 295 | const IRecoverable = [ 296 | 'function recoverEther(address sendTo)', 297 | 'function recoverToken(address token, address sendTo)', 298 | 'function s() view returns (address)' 299 | ] 300 | 301 | const IReporter = [ 302 | 'event Disputed(bytes32 indexed coverKey, bytes32 indexed productKey, address reporter, uint256 indexed incidentDate, string info, uint256 initialStake)', 303 | 'event FirstReportingStakeSet(bytes32 coverKey, uint256 previous, uint256 current)', 304 | 'event Reported(bytes32 indexed coverKey, bytes32 indexed productKey, address reporter, uint256 indexed incidentDate, string info, uint256 initialStake, uint256 resolutionTimestamp)', 305 | 'event ReporterCommissionSet(uint256 previous, uint256 current)', 306 | 'event ReportingBurnRateSet(uint256 previous, uint256 current)', 307 | 'function dispute(bytes32 coverKey, bytes32 productKey, uint256 incidentDate, string info, uint256 stake)', 308 | 'function getActiveIncidentDate(bytes32 coverKey, bytes32 productKey) view returns (uint256)', 309 | 'function getAttestation(bytes32 coverKey, bytes32 productKey, address who, uint256 incidentDate) view returns (uint256 myStake, uint256 totalStake)', 310 | 'function getFirstReportingStake(bytes32 coverKey) view returns (uint256)', 311 | 'function getRefutation(bytes32 coverKey, bytes32 productKey, address who, uint256 incidentDate) view returns (uint256 myStake, uint256 totalStake)', 312 | 'function getReporter(bytes32 coverKey, bytes32 productKey, uint256 incidentDate) view returns (address)', 313 | 'function getResolutionTimestamp(bytes32 coverKey, bytes32 productKey) view returns (uint256)', 314 | 'function report(bytes32 coverKey, bytes32 productKey, string info, uint256 stake)', 315 | 'function setFirstReportingStake(bytes32 coverKey, uint256 value)', 316 | 'function setReporterCommission(uint256 value)', 317 | 'function setReportingBurnRate(uint256 value)' 318 | ] 319 | 320 | const IResolution = [ 321 | 'event CooldownPeriodConfigured(bytes32 indexed coverKey, uint256 period)', 322 | 'event Finalized(bytes32 indexed coverKey, bytes32 indexed productKey, address finalizer, uint256 indexed incidentDate)', 323 | 'event GovernanceBurned(bytes32 indexed coverKey, bytes32 indexed productKey, address caller, address indexed burner, uint256 originalReward, uint256 burnedAmount)', 324 | 'event ReportClosed(bytes32 indexed coverKey, bytes32 indexed productKey, address indexed closedBy, uint256 incidentDate)', 325 | 'event ReporterRewardDistributed(bytes32 indexed coverKey, bytes32 indexed productKey, address caller, address indexed reporter, uint256 originalReward, uint256 reporterReward)', 326 | 'event Resolved(bytes32 indexed coverKey, bytes32 indexed productKey, uint256 incidentDate, uint256 resolutionDeadline, bool decision, bool emergency, uint256 claimBeginsFrom, uint256 claimExpiresAt)', 327 | 'event Unstaken(bytes32 indexed coverKey, bytes32 indexed productKey, address indexed caller, uint256 originalStake, uint256 reward)', 328 | 'function closeReport(bytes32 coverKey, bytes32 productKey, uint256 incidentDate)', 329 | 'function configureCoolDownPeriod(bytes32 coverKey, uint256 period)', 330 | 'function emergencyResolve(bytes32 coverKey, bytes32 productKey, uint256 incidentDate, bool decision)', 331 | 'function finalize(bytes32 coverKey, bytes32 productKey, uint256 incidentDate)', 332 | 'function getCoolDownPeriod(bytes32 coverKey) view returns (uint256)', 333 | 'function getName() pure returns (bytes32)', 334 | 'function getResolutionDeadline(bytes32 coverKey, bytes32 productKey) view returns (uint256)', 335 | 'function getUnstakeInfoFor(address account, bytes32 coverKey, bytes32 productKey, uint256 incidentDate) view returns (tuple(uint256 totalStakeInWinningCamp, uint256 totalStakeInLosingCamp, uint256 myStakeInWinningCamp, uint256 toBurn, uint256 toReporter, uint256 myReward, uint256 unstaken))', 336 | 'function resolve(bytes32 coverKey, bytes32 productKey, uint256 incidentDate)', 337 | 'function unstake(bytes32 coverKey, bytes32 productKey, uint256 incidentDate)', 338 | 'function unstakeWithClaim(bytes32 coverKey, bytes32 productKey, uint256 incidentDate)', 339 | 'function version() pure returns (bytes32)' 340 | ] 341 | 342 | const IResolvable = [ 343 | 'event CooldownPeriodConfigured(bytes32 indexed coverKey, uint256 period)', 344 | 'event ReportClosed(bytes32 indexed coverKey, bytes32 indexed productKey, address indexed closedBy, uint256 incidentDate)', 345 | 'event Resolved(bytes32 indexed coverKey, bytes32 indexed productKey, uint256 incidentDate, uint256 resolutionDeadline, bool decision, bool emergency, uint256 claimBeginsFrom, uint256 claimExpiresAt)', 346 | 'function closeReport(bytes32 coverKey, bytes32 productKey, uint256 incidentDate)', 347 | 'function configureCoolDownPeriod(bytes32 coverKey, uint256 period)', 348 | 'function emergencyResolve(bytes32 coverKey, bytes32 productKey, uint256 incidentDate, bool decision)', 349 | 'function getCoolDownPeriod(bytes32 coverKey) view returns (uint256)', 350 | 'function getResolutionDeadline(bytes32 coverKey, bytes32 productKey) view returns (uint256)', 351 | 'function resolve(bytes32 coverKey, bytes32 productKey, uint256 incidentDate)' 352 | ] 353 | 354 | const IStakingPools = [ 355 | 'event Deposited(bytes32 indexed key, address indexed account, address indexed token, uint256 amount)', 356 | 'event PoolClosed(bytes32 indexed key, string name)', 357 | 'event PoolUpdated(bytes32 indexed key, tuple(bytes32 key, string name, uint8 poolType, address stakingToken, address uniStakingTokenDollarPair, address rewardToken, address uniRewardTokenDollarPair, uint256 stakingTarget, uint256 maxStake, uint256 platformFee, uint256 rewardPerBlock, uint256 lockupPeriod, uint256 rewardTokenToDeposit) args)', 358 | 'event RewardsWithdrawn(bytes32 indexed key, address indexed account, address indexed token, uint256 rewards, uint256 platformFee)', 359 | 'event Withdrawn(bytes32 indexed key, address indexed account, address indexed token, uint256 amount)', 360 | 'function addOrEditPool(tuple(bytes32 key, string name, uint8 poolType, address stakingToken, address uniStakingTokenDollarPair, address rewardToken, address uniRewardTokenDollarPair, uint256 stakingTarget, uint256 maxStake, uint256 platformFee, uint256 rewardPerBlock, uint256 lockupPeriod, uint256 rewardTokenToDeposit) args)', 361 | 'function calculateRewards(bytes32 key, address account) view returns (uint256)', 362 | 'function closePool(bytes32 key)', 363 | 'function deposit(bytes32 key, uint256 amount)', 364 | 'function getInfo(bytes32 key, address you) view returns (tuple(string name, address stakingToken, address stakingTokenStablecoinPair, address rewardToken, address rewardTokenStablecoinPair, uint256 totalStaked, uint256 target, uint256 maximumStake, uint256 stakeBalance, uint256 cumulativeDeposits, uint256 rewardPerBlock, uint256 platformFee, uint256 lockupPeriod, uint256 rewardTokenBalance, uint256 accountStakeBalance, uint256 totalBlockSinceLastReward, uint256 rewards, uint256 canWithdrawFromBlockHeight, uint256 lastDepositHeight, uint256 lastRewardHeight) info)', 365 | 'function getName() pure returns (bytes32)', 366 | 'function version() pure returns (bytes32)', 367 | 'function withdraw(bytes32 key, uint256 amount)', 368 | 'function withdrawRewards(bytes32 key)' 369 | ] 370 | 371 | const IStore = [ 372 | 'event PausersSet(address indexed addedBy, address[] accounts, bool[] statuses)', 373 | 'function addUint(bytes32 k, uint256 v)', 374 | 'function countAddressArrayItems(bytes32 k) view returns (uint256)', 375 | 'function countBytes32ArrayItems(bytes32 k) view returns (uint256)', 376 | 'function deleteAddress(bytes32 k)', 377 | 'function deleteAddressArrayItem(bytes32 k, address v)', 378 | 'function deleteAddressArrayItemByIndex(bytes32 k, uint256 i)', 379 | 'function deleteBool(bytes32 k)', 380 | 'function deleteBytes(bytes32 k)', 381 | 'function deleteBytes32(bytes32 k)', 382 | 'function deleteBytes32ArrayItem(bytes32 k, bytes32 v)', 383 | 'function deleteBytes32ArrayItemByIndex(bytes32 k, uint256 i)', 384 | 'function deleteInt(bytes32 k)', 385 | 'function deleteString(bytes32 k)', 386 | 'function deleteUint(bytes32 k)', 387 | 'function deleteUints(bytes32 k)', 388 | 'function getAddress(bytes32 k) view returns (address)', 389 | 'function getAddressArray(bytes32 k) view returns (address[])', 390 | 'function getAddressArrayItemByIndex(bytes32 k, uint256 i) view returns (address)', 391 | 'function getAddressArrayItemPosition(bytes32 k, address toFind) view returns (uint256)', 392 | 'function getAddressBoolean(bytes32 k, address a) view returns (bool)', 393 | 'function getAddressValues(bytes32[] keys) view returns (address[] values)', 394 | 'function getBool(bytes32 k) view returns (bool)', 395 | 'function getBytes(bytes32 k) view returns (bytes)', 396 | 'function getBytes32(bytes32 k) view returns (bytes32)', 397 | 'function getBytes32Array(bytes32 k) view returns (bytes32[])', 398 | 'function getBytes32ArrayItemByIndex(bytes32 k, uint256 i) view returns (bytes32)', 399 | 'function getBytes32ArrayItemPosition(bytes32 k, bytes32 toFind) view returns (uint256)', 400 | 'function getInt(bytes32 k) view returns (int256)', 401 | 'function getString(bytes32 k) view returns (string)', 402 | 'function getUint(bytes32 k) view returns (uint256)', 403 | 'function getUintValues(bytes32[] keys) view returns (uint256[] values)', 404 | 'function getUints(bytes32 k) view returns (uint256[])', 405 | 'function setAddress(bytes32 k, address v)', 406 | 'function setAddressArrayItem(bytes32 k, address v)', 407 | 'function setAddressBoolean(bytes32 k, address a, bool v)', 408 | 'function setBool(bytes32 k, bool v)', 409 | 'function setBytes(bytes32 k, bytes v)', 410 | 'function setBytes32(bytes32 k, bytes32 v)', 411 | 'function setBytes32ArrayItem(bytes32 k, bytes32 v)', 412 | 'function setInt(bytes32 k, int256 v)', 413 | 'function setPausers(address[] accounts, bool[] statuses)', 414 | 'function setString(bytes32 k, string v)', 415 | 'function setUint(bytes32 k, uint256 v)', 416 | 'function setUints(bytes32 k, uint256[] v)', 417 | 'function subtractUint(bytes32 k, uint256 v)' 418 | ] 419 | 420 | const IUniswapV2FactoryLike = [ 421 | 'event PairCreated(address indexed token0, address indexed token1, address pair, uint256)', 422 | 'function getPair(address tokenA, address tokenB) view returns (address pair)' 423 | ] 424 | 425 | const IUniswapV2PairLike = [ 426 | 'function getReserves() view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast)', 427 | 'function token0() view returns (address)', 428 | 'function token1() view returns (address)', 429 | 'function totalSupply() view returns (uint256)' 430 | ] 431 | 432 | const IUniswapV2RouterLike = [ 433 | 'function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) returns (uint256 amountA, uint256 amountB, uint256 liquidity)', 434 | 'function factory() view returns (address)', 435 | 'function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) pure returns (uint256 amountIn)', 436 | 'function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) pure returns (uint256 amountOut)', 437 | 'function getAmountsIn(uint256 amountOut, address[] path) view returns (uint256[] amounts)', 438 | 'function getAmountsOut(uint256 amountIn, address[] path) view returns (uint256[] amounts)', 439 | 'function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) pure returns (uint256 amountB)' 440 | ] 441 | 442 | const IUnstakable = [ 443 | 'event GovernanceBurned(bytes32 indexed coverKey, bytes32 indexed productKey, address caller, address indexed burner, uint256 originalReward, uint256 burnedAmount)', 444 | 'event ReporterRewardDistributed(bytes32 indexed coverKey, bytes32 indexed productKey, address caller, address indexed reporter, uint256 originalReward, uint256 reporterReward)', 445 | 'event Unstaken(bytes32 indexed coverKey, bytes32 indexed productKey, address indexed caller, uint256 originalStake, uint256 reward)', 446 | 'function getUnstakeInfoFor(address account, bytes32 coverKey, bytes32 productKey, uint256 incidentDate) view returns (tuple(uint256 totalStakeInWinningCamp, uint256 totalStakeInLosingCamp, uint256 myStakeInWinningCamp, uint256 toBurn, uint256 toReporter, uint256 myReward, uint256 unstaken))', 447 | 'function unstake(bytes32 coverKey, bytes32 productKey, uint256 incidentDate)', 448 | 'function unstakeWithClaim(bytes32 coverKey, bytes32 productKey, uint256 incidentDate)' 449 | ] 450 | 451 | const IVault = [ 452 | 'event Approval(address indexed owner, address indexed spender, uint256 value)', 453 | 'event Entered(bytes32 indexed coverKey, address indexed account)', 454 | 'event Exited(bytes32 indexed coverKey, address indexed account)', 455 | 'event FlashLoanBorrowed(address indexed lender, address indexed borrower, address indexed stablecoin, uint256 amount, uint256 fee)', 456 | 'event GovernanceTransfer(address indexed to, uint256 amount)', 457 | 'event InterestAccrued(bytes32 indexed coverKey)', 458 | 'event NpmStaken(address indexed account, uint256 amount)', 459 | 'event NpmUnstaken(address indexed account, uint256 amount)', 460 | 'event PodsIssued(address indexed account, uint256 issued, uint256 liquidityAdded, bytes32 indexed referralCode)', 461 | 'event PodsRedeemed(address indexed account, uint256 redeemed, uint256 liquidityReleased)', 462 | 'event StrategyReceipt(address indexed token, address indexed strategy, bytes32 indexed name, uint256 amount, uint256 income, uint256 loss)', 463 | 'event StrategyTransfer(address indexed token, address indexed strategy, bytes32 indexed name, uint256 amount)', 464 | 'event Transfer(address indexed from, address indexed to, uint256 value)', 465 | 'function accrueInterest()', 466 | 'function addLiquidity(tuple(bytes32 coverKey, uint256 amount, uint256 npmStakeToAdd, bytes32 referralCode) args)', 467 | 'function allowance(address owner, address spender) view returns (uint256)', 468 | 'function approve(address spender, uint256 amount) returns (bool)', 469 | 'function balanceOf(address account) view returns (uint256)', 470 | 'function calculateLiquidity(uint256 podsToBurn) view returns (uint256)', 471 | 'function calculatePods(uint256 forStablecoinUnits) view returns (uint256)', 472 | 'function getInfo(address forAccount) view returns (tuple(uint256 totalPods, uint256 balance, uint256 extendedBalance, uint256 totalReassurance, uint256 myPodBalance, uint256 myShare, uint256 withdrawalOpen, uint256 withdrawalClose) info)', 473 | 'function getName() pure returns (bytes32)', 474 | 'function getStablecoinBalanceOf() view returns (uint256)', 475 | 'function key() view returns (bytes32)', 476 | 'function receiveFromStrategy(address token, bytes32 coverKey, bytes32 strategyName, uint256 amount)', 477 | 'function removeLiquidity(bytes32 coverKey, uint256 amount, uint256 npmStake, bool exit)', 478 | 'function sc() view returns (address)', 479 | 'function totalSupply() view returns (uint256)', 480 | 'function transfer(address recipient, uint256 amount) returns (bool)', 481 | 'function transferFrom(address sender, address recipient, uint256 amount) returns (bool)', 482 | 'function transferGovernance(bytes32 coverKey, address to, uint256 amount)', 483 | 'function transferToStrategy(address token, bytes32 coverKey, bytes32 strategyName, uint256 amount)', 484 | 'function version() pure returns (bytes32)' 485 | ] 486 | 487 | const IVaultDelegate = [ 488 | 'function accrueInterestImplementation(address caller, bytes32 coverKey)', 489 | 'function calculateLiquidityImplementation(bytes32 coverKey, uint256 podsToBurn) view returns (uint256)', 490 | 'function calculatePodsImplementation(bytes32 coverKey, uint256 forStablecoinUnits) view returns (uint256)', 491 | 'function getFlashFee(address caller, bytes32 coverKey, address token, uint256 amount) view returns (uint256)', 492 | 'function getInfoImplementation(bytes32 coverKey, address forAccount) view returns (tuple(uint256 totalPods, uint256 balance, uint256 extendedBalance, uint256 totalReassurance, uint256 myPodBalance, uint256 myShare, uint256 withdrawalOpen, uint256 withdrawalClose))', 493 | 'function getMaxFlashLoan(address caller, bytes32 coverKey, address token) view returns (uint256)', 494 | 'function getName() pure returns (bytes32)', 495 | 'function getStablecoinBalanceOfImplementation(bytes32 coverKey) view returns (uint256)', 496 | 'function postAddLiquidity(address caller, bytes32 coverKey, uint256 amount, uint256 npmStake)', 497 | 'function postFlashLoan(address caller, bytes32 coverKey, address receiver, address token, uint256 amount, bytes data)', 498 | 'function postReceiveFromStrategy(address caller, address token, bytes32 coverKey, bytes32 strategyName, uint256 amount) returns (uint256 income, uint256 loss)', 499 | 'function postRemoveLiquidity(address caller, bytes32 coverKey, uint256 amount, uint256 npmStake, bool exit)', 500 | 'function postTransferGovernance(address caller, bytes32 coverKey, address to, uint256 amount)', 501 | 'function postTransferToStrategy(address caller, address token, bytes32 coverKey, bytes32 strategyName, uint256 amount)', 502 | 'function preAddLiquidity(address caller, bytes32 coverKey, uint256 amount, uint256 npmStake) returns (uint256 podsToMint, uint256 previousNpmStake)', 503 | 'function preFlashLoan(address caller, bytes32 coverKey, address receiver, address token, uint256 amount, bytes data) returns (address stablecoin, uint256 fee, uint256 protocolFee)', 504 | 'function preReceiveFromStrategy(address caller, address token, bytes32 coverKey, bytes32 strategyName, uint256 amount)', 505 | 'function preRemoveLiquidity(address caller, bytes32 coverKey, uint256 amount, uint256 npmStake, bool exit) returns (address stablecoin, uint256 stableCoinToRelease)', 506 | 'function preTransferGovernance(address caller, bytes32 coverKey, address to, uint256 amount) returns (address stablecoin)', 507 | 'function preTransferToStrategy(address caller, address token, bytes32 coverKey, bytes32 strategyName, uint256 amount)', 508 | 'function version() pure returns (bytes32)' 509 | ] 510 | 511 | const IVaultFactory = [ 512 | 'event VaultDeployed(address vault, bytes32 indexed coverKey, string name, string symbol)', 513 | 'function deploy(bytes32 coverKey, string name, string symbol) returns (address)', 514 | 'function getName() pure returns (bytes32)', 515 | 'function version() pure returns (bytes32)' 516 | ] 517 | 518 | const IWitness = [ 519 | 'event Attested(bytes32 indexed coverKey, bytes32 indexed productKey, address witness, uint256 indexed incidentDate, uint256 stake)', 520 | 'event Refuted(bytes32 indexed coverKey, bytes32 indexed productKey, address witness, uint256 indexed incidentDate, uint256 stake)', 521 | 'function attest(bytes32 coverKey, bytes32 productKey, uint256 incidentDate, uint256 stake)', 522 | 'function getStakes(bytes32 coverKey, bytes32 productKey, uint256 incidentDate) view returns (uint256, uint256)', 523 | 'function getStakesOf(bytes32 coverKey, bytes32 productKey, uint256 incidentDate, address account) view returns (uint256, uint256)', 524 | 'function getStatus(bytes32 coverKey, bytes32 productKey) view returns (uint256)', 525 | 'function isCoverNormal(bytes32 coverKey) view returns (bool)', 526 | 'function refute(bytes32 coverKey, bytes32 productKey, uint256 incidentDate, uint256 stake)' 527 | ] 528 | 529 | export { 530 | IAaveV2LendingPoolLike, 531 | IBondPool, 532 | IClaimsProcessor, 533 | ICompoundERC20DelegatorLike, 534 | ICover, 535 | ICoverReassurance, 536 | ICoverStake, 537 | ICoverUpdate, 538 | ICxToken, 539 | ICxTokenFactory, 540 | IERC20, 541 | IERC20Detailed, 542 | IFinalization, 543 | IGovernance, 544 | ILendingStrategy, 545 | ILiquidityEngine, 546 | IMember, 547 | IPausable, 548 | IPolicy, 549 | IPolicyAdmin, 550 | IPriceOracle, 551 | IProtocol, 552 | IRecoverable, 553 | IReporter, 554 | IResolution, 555 | IResolvable, 556 | IStakingPools, 557 | IStore, 558 | IUniswapV2FactoryLike, 559 | IUniswapV2PairLike, 560 | IUniswapV2RouterLike, 561 | IUnstakable, 562 | IVault, 563 | IVaultDelegate, 564 | IVaultFactory, 565 | IWitness 566 | } 567 | -------------------------------------------------------------------------------- /src/config/constants.ts: -------------------------------------------------------------------------------- 1 | import { 2 | AddressZero, 3 | HashZero 4 | } from '@ethersproject/constants' 5 | 6 | const MULTIPLIER = 10_000 7 | const ZERO_ADDRESS = AddressZero 8 | const ZERO_BYTES32 = HashZero 9 | 10 | export { MULTIPLIER, ZERO_ADDRESS, ZERO_BYTES32 } 11 | -------------------------------------------------------------------------------- /src/config/index.ts: -------------------------------------------------------------------------------- 1 | import * as abis from './abis/index.js' 2 | import * as constants from './constants.js' 3 | import * as networks from './networks/index.js' 4 | import * as store from './store/index.js' 5 | 6 | export { abis, constants, networks, store } 7 | -------------------------------------------------------------------------------- /src/config/internal.ts: -------------------------------------------------------------------------------- 1 | import { type SDKInternalStorage } from '../types/SDKInternalStorage.js' 2 | 3 | const _STORAGE: SDKInternalStorage = { 4 | initialized: false 5 | } 6 | 7 | export const initialize = ({ store }: { store: SDKInternalStorage['store'] }): void => { 8 | _STORAGE.initialized = true 9 | 10 | _STORAGE.store = store 11 | } 12 | 13 | export const getStorageValue = (key: T): SDKInternalStorage[T] => { 14 | if (!_STORAGE.initialized) { 15 | console.error('SDK not initialized') 16 | } 17 | 18 | return _STORAGE[key] 19 | } 20 | -------------------------------------------------------------------------------- /src/config/networks/arbitrum.ts: -------------------------------------------------------------------------------- 1 | import { Token } from '../../entities/Token.js' 2 | import { 3 | ChainId, 4 | type INetwork, 5 | type IToken 6 | } from '../../types/index.js' 7 | import { getStoreAddressFromEnvironment } from '../store/index.js' 8 | 9 | const weth = new Token(ChainId.Arbitrum, '0x82aF49447D8a07e3bd95BD0d56f35241523fBab1', 'Wrapped Ether', 'WETH') 10 | 11 | class Arbitrum implements INetwork { 12 | chainId: ChainId 13 | chain: string 14 | approximateBlockTime: number 15 | store: string 16 | uniswap: { 17 | factory: string | null 18 | router: string | null 19 | masterChef: string | null 20 | } 21 | 22 | tokens: { 23 | WETH: IToken 24 | } 25 | 26 | hostname: string 27 | 28 | constructor () { 29 | this.chainId = ChainId.Arbitrum 30 | this.chain = 'Arbitrum One Network' 31 | this.approximateBlockTime = 1 32 | 33 | this.store = getStoreAddressFromEnvironment(ChainId.Arbitrum) 34 | 35 | this.tokens = { 36 | WETH: weth 37 | } 38 | this.uniswap = { 39 | factory: '0xc35DADB65012eC5796536bD9864eD8773aBc74C4', 40 | router: '0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506', 41 | masterChef: null 42 | } 43 | this.hostname = 'arbitrum.neptunemutual.net' 44 | } 45 | } 46 | 47 | export { Arbitrum } 48 | -------------------------------------------------------------------------------- /src/config/networks/base-goerli.ts: -------------------------------------------------------------------------------- 1 | import { Token } from '../../entities/Token.js' 2 | import { 3 | ChainId, 4 | type INetwork, 5 | type IToken 6 | } from '../../types/index.js' 7 | import { getStoreAddressFromEnvironment } from '../store/index.js' 8 | 9 | const weth = new Token(ChainId.BaseGoerli, '0x330Eb67E7Cf8aFd2C32109E1628b050472A183fa', 'Wrapped Ether', 'WETH') 10 | 11 | class BaseGoerli implements INetwork { 12 | chainId: ChainId 13 | chain: string 14 | approximateBlockTime: number 15 | store: string 16 | uniswap: { 17 | factory: string | null 18 | router: string | null 19 | masterChef: string | null 20 | } 21 | 22 | tokens: { 23 | WETH: IToken 24 | } 25 | 26 | hostname: string 27 | 28 | constructor () { 29 | this.chainId = ChainId.BaseGoerli 30 | this.chain = 'Base Goerli' 31 | this.approximateBlockTime = 2 32 | 33 | this.store = getStoreAddressFromEnvironment(ChainId.BaseGoerli) 34 | 35 | this.tokens = { 36 | WETH: weth 37 | } 38 | this.uniswap = { 39 | factory: '0x8286A48086BEeba59FDe71FFBfA66B005f22D121', 40 | router: '0x6136dDE4BECBfBd6885d89c61574ED4dCaF16f54', 41 | masterChef: null 42 | } 43 | this.hostname = 'test.neptunemutual.com' 44 | } 45 | } 46 | 47 | export { BaseGoerli } 48 | -------------------------------------------------------------------------------- /src/config/networks/bsc.ts: -------------------------------------------------------------------------------- 1 | import { Token } from '../../entities/Token.js' 2 | import { 3 | ChainId, 4 | type INetwork, 5 | type IToken 6 | } from '../../types/index.js' 7 | import { getStoreAddressFromEnvironment } from '../store/index.js' 8 | 9 | const weth = new Token(ChainId.BSC, '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c', 'Wrapped Ether', 'WETH') 10 | 11 | class BSC implements INetwork { 12 | chainId: ChainId 13 | chain: string 14 | approximateBlockTime: number 15 | store: string 16 | uniswap: { 17 | factory: string | null 18 | router: string | null 19 | masterChef: string | null 20 | } 21 | 22 | tokens: { 23 | WETH: IToken 24 | } 25 | 26 | hostname: string 27 | 28 | constructor () { 29 | this.chainId = ChainId.BSC 30 | this.chain = 'BNB Smart Chain' 31 | this.approximateBlockTime = 2 32 | 33 | this.store = getStoreAddressFromEnvironment(ChainId.BSC) 34 | 35 | this.tokens = { 36 | WETH: weth 37 | } 38 | this.uniswap = { 39 | factory: '0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73', 40 | router: '0x10ED43C718714eb63d5aA57B78B54704E256024E', 41 | masterChef: null 42 | } 43 | this.hostname = 'bsc.neptunemutual.net' 44 | } 45 | } 46 | 47 | export { BSC } 48 | -------------------------------------------------------------------------------- /src/config/networks/ethereum.ts: -------------------------------------------------------------------------------- 1 | import { Token } from '../../entities/Token.js' 2 | import { 3 | ChainId, 4 | type INetwork, 5 | type IToken 6 | } from '../../types/index.js' 7 | import { getStoreAddressFromEnvironment } from '../store/index.js' 8 | 9 | const weth = new Token(ChainId.Ethereum, '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 'Wrapped Ether', 'WETH') 10 | 11 | class Ethereum implements INetwork { 12 | chainId: ChainId 13 | chain: string 14 | approximateBlockTime: number 15 | store: string 16 | uniswap: { 17 | factory: string | null 18 | router: string | null 19 | masterChef: string | null 20 | } 21 | 22 | tokens: { 23 | WETH: IToken 24 | } 25 | 26 | hostname: string 27 | 28 | constructor () { 29 | this.chainId = ChainId.Ethereum 30 | this.chain = 'Main Ethereum Network' 31 | this.approximateBlockTime = 12 32 | 33 | this.store = getStoreAddressFromEnvironment(ChainId.Ethereum) 34 | 35 | this.tokens = { 36 | WETH: weth 37 | } 38 | this.uniswap = { 39 | factory: '0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f', 40 | router: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', 41 | masterChef: null 42 | } 43 | this.hostname = 'ethereum.neptunemutual.net' 44 | } 45 | } 46 | 47 | export { Ethereum } 48 | -------------------------------------------------------------------------------- /src/config/networks/fuji.ts: -------------------------------------------------------------------------------- 1 | import { Token } from '../../entities/Token.js' 2 | import { 3 | ChainId, 4 | type INetwork, 5 | type IToken 6 | } from '../../types/index.js' 7 | import { getStoreAddressFromEnvironment } from '../store/index.js' 8 | 9 | const weth = new Token(ChainId.Fuji, '0xD9D01A9F7C810EC035C0e42cB9E80Ef44D7f8692', 'Wrapped AVAX', 'WAVAX') 10 | 11 | class Fuji implements INetwork { 12 | chainId: ChainId 13 | chain: string 14 | approximateBlockTime: number 15 | store: string 16 | uniswap: { 17 | factory: string | null 18 | router: string | null 19 | masterChef: string | null 20 | } 21 | 22 | tokens: { 23 | WETH: IToken 24 | } 25 | 26 | hostname: string 27 | 28 | constructor () { 29 | this.chainId = ChainId.Fuji 30 | this.chain = 'Fuji Test Network (Avalanche)' 31 | this.approximateBlockTime = 3 32 | 33 | this.store = getStoreAddressFromEnvironment(ChainId.Fuji) 34 | 35 | this.tokens = { 36 | WETH: weth 37 | } 38 | this.uniswap = { 39 | factory: '0xe4a575550c2b460d2307b82dcd7afe84ad1484dd', 40 | router: '0x2D99ABD9008Dc933ff5c0CD271B88309593aB921', 41 | masterChef: null 42 | } 43 | 44 | this.hostname = 'test.neptunemutual.com' 45 | } 46 | } 47 | 48 | export { Fuji } 49 | -------------------------------------------------------------------------------- /src/config/networks/index.ts: -------------------------------------------------------------------------------- 1 | import { 2 | UnsupportedBlockchainError 3 | } from '../../types/Exceptions/UnsupportedBlockchainError.js' 4 | import { 5 | ChainId, 6 | type INetwork 7 | } from '../../types/index.js' 8 | import { Arbitrum } from './arbitrum.js' 9 | import { BaseGoerli } from './base-goerli.js' 10 | import { BSC } from './bsc.js' 11 | import { Ethereum } from './ethereum.js' 12 | import { Fuji } from './fuji.js' 13 | import { Mumbai } from './mumbai.js' 14 | 15 | const getChainConfig = (chainId: ChainId): INetwork => { 16 | switch (chainId) { 17 | case ChainId.Ethereum: 18 | return new Ethereum() 19 | case ChainId.Mumbai: 20 | return new Mumbai() 21 | case ChainId.Fuji: 22 | return new Fuji() 23 | case ChainId.Arbitrum: 24 | return new Arbitrum() 25 | case ChainId.BSC: 26 | return new BSC() 27 | case ChainId.BaseGoerli: 28 | return new BaseGoerli() 29 | } 30 | 31 | throw new UnsupportedBlockchainError(`The ChainId: ${chainId} isn't supported yet`) 32 | } 33 | 34 | export { getChainConfig } 35 | -------------------------------------------------------------------------------- /src/config/networks/mumbai.ts: -------------------------------------------------------------------------------- 1 | import { Token } from '../../entities/Token.js' 2 | import { 3 | ChainId, 4 | type INetwork, 5 | type IToken 6 | } from '../../types/index.js' 7 | import { getStoreAddressFromEnvironment } from '../store/index.js' 8 | 9 | const wmatic = new Token(ChainId.Mumbai, '0xaf75BBD137e6f2dc92668a89b1a6d0E70B03da10', 'Wrapped Matic', 'WMATIC') 10 | 11 | class Mumbai implements INetwork { 12 | chainId: ChainId 13 | chain: string 14 | approximateBlockTime: number 15 | store: string 16 | uniswap: { 17 | factory: string | null 18 | router: string | null 19 | masterChef: string | null 20 | } 21 | 22 | tokens: { 23 | WETH: IToken 24 | } 25 | 26 | hostname: string 27 | 28 | constructor () { 29 | this.chainId = ChainId.Mumbai 30 | this.chain = 'Mumbai Test Network (Polygon)' 31 | this.approximateBlockTime = 3 32 | 33 | this.store = getStoreAddressFromEnvironment(ChainId.Mumbai) 34 | 35 | this.tokens = { 36 | WETH: wmatic 37 | } 38 | this.uniswap = { 39 | factory: '0xa22ac46e83Be5c2B947B604A85fF52DB0a0E01e8', 40 | router: '0x0AEb349be52A1F95395AC0Fa8dCC63b17A492D6d', 41 | masterChef: null 42 | } 43 | this.hostname = 'mumbai.neptunemutual.com' 44 | } 45 | } 46 | 47 | export { Mumbai } 48 | -------------------------------------------------------------------------------- /src/config/store/definition.ts: -------------------------------------------------------------------------------- 1 | import { ChainId } from '../../types/ChainId.js' 2 | 3 | export const getDefinition = (): Record, Record<'env' | 'next' | 'fallback', string | undefined>> => { 4 | return { 5 | [ChainId.Ethereum]: { 6 | env: process.env.NPM_ETHEREUM_STORE, 7 | next: process.env.NEXT_PUBLIC_ETHEREUM_STORE, 8 | fallback: undefined 9 | }, 10 | [ChainId.Arbitrum]: { 11 | env: process.env.NPM_ARBITRUM_STORE, 12 | next: process.env.NEXT_PUBLIC_ARBITRUM_STORE, 13 | fallback: undefined 14 | }, 15 | [ChainId.BSC]: { 16 | env: process.env.NPM_BSC_STORE, 17 | next: process.env.NEXT_PUBLIC_BSC_STORE, 18 | fallback: undefined 19 | }, 20 | [ChainId.BaseGoerli]: { 21 | env: process.env.NPM_BASE_GOERLI_STORE, 22 | next: process.env.NEXT_PUBLIC_BASE_GOERLI_STORE, 23 | fallback: undefined 24 | }, 25 | [ChainId.Mumbai]: { 26 | env: process.env.NPM_MUMBAI_STORE, 27 | next: process.env.NEXT_PUBLIC_MUMBAI_STORE, 28 | fallback: undefined 29 | }, 30 | [ChainId.Fuji]: { 31 | env: process.env.NPM_FUJI_STORE, 32 | next: process.env.NEXT_PUBLIC_FUJI_STORE, 33 | fallback: undefined 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/config/store/index.ts: -------------------------------------------------------------------------------- 1 | import { 2 | InvalidChainIdError 3 | } from '../../types/Exceptions/InvalidChainIdError.js' 4 | import { InvalidStoreError } from '../../types/Exceptions/InvalidStoreError.js' 5 | import { ChainId } from '../../types/index.js' 6 | import { getStorageValue } from '../internal.js' 7 | import { getDefinition } from './definition.js' 8 | 9 | const getStoreAddressFromEnvironment = (chainId: ChainId): string => { 10 | if (chainId === ChainId.Invalid) { 11 | throw new InvalidChainIdError('Invalid Chain Id') 12 | } 13 | 14 | const { env, next, fallback } = getDefinition()[chainId] 15 | 16 | if (env !== undefined && env !== '') { 17 | return env 18 | } 19 | 20 | if (next !== undefined && next !== '') { 21 | return next 22 | } 23 | 24 | if (fallback !== undefined && fallback !== '') { 25 | return fallback 26 | } 27 | 28 | const storeAddresses = getStorageValue('store') 29 | 30 | const value = storeAddresses?.[chainId] 31 | 32 | if (value !== undefined && value !== '') { 33 | return value 34 | } 35 | 36 | throw new InvalidStoreError('Store not found') 37 | } 38 | 39 | export { getStoreAddressFromEnvironment } 40 | -------------------------------------------------------------------------------- /src/core/claimsProcessor.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Provider } from '@ethersproject/providers' 3 | 4 | import { 5 | ClaimsProcessor, 6 | IERC20 7 | } from '../registry/index.js' 8 | import { 9 | type ChainId, 10 | type IApproveTransactionArgs, 11 | type IWrappedResult, 12 | Status 13 | } from '../types/index.js' 14 | import { erc20Utils } from '../utils/index.js' 15 | 16 | const getAllowance = async (chainId: ChainId, cTokenAddress: string, owner: string, signerOrProvider: Provider | Signer): Promise => { 17 | const cxToken = IERC20.getInstance(cTokenAddress, signerOrProvider) 18 | const processor = await ClaimsProcessor.getAddress(chainId, signerOrProvider) 19 | 20 | const result = await cxToken.allowance(owner, processor) 21 | 22 | return { 23 | status: Status.SUCCESS, 24 | result 25 | } 26 | } 27 | 28 | const approve = async (chainId: ChainId, cTokenAddress: string, args: IApproveTransactionArgs, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 29 | const cxToken = IERC20.getInstance(cTokenAddress, signerOrProvider) 30 | 31 | const processor = await ClaimsProcessor.getAddress(chainId, signerOrProvider) 32 | const amount = erc20Utils.getApprovalAmount(args) 33 | 34 | const result = await cxToken.approve(processor, amount, transactionOverrides) 35 | 36 | return { 37 | status: Status.SUCCESS, 38 | result 39 | } 40 | } 41 | 42 | const validate = async (chainId: ChainId, cTokenAddress: string, coverKey: string, productKey: string, incidentDate: number, amount: number, signerOrProvider: Provider | Signer): Promise => { 43 | const processor = await ClaimsProcessor.getInstance(chainId, signerOrProvider) 44 | 45 | const result = await processor.validate(cTokenAddress, coverKey, productKey, incidentDate, amount) 46 | 47 | return { 48 | status: Status.SUCCESS, 49 | result 50 | } 51 | } 52 | 53 | const claim = async (chainId: ChainId, cTokenAddress: string, coverKey: string, productKey: string, incidentDate: number, amount: number, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 54 | const processor = await ClaimsProcessor.getInstance(chainId, signerOrProvider) 55 | 56 | const result = await processor.claim(cTokenAddress, coverKey, productKey, incidentDate, amount, transactionOverrides) 57 | 58 | return { 59 | status: Status.SUCCESS, 60 | result 61 | } 62 | } 63 | 64 | export { approve, claim, getAllowance, validate } 65 | -------------------------------------------------------------------------------- /src/core/cover.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Provider } from '@ethersproject/providers' 3 | 4 | import { 5 | constants 6 | } from '../config/index.js' 7 | import { 8 | Cover, 9 | IERC20, 10 | NPMToken 11 | } from '../registry/index.js' 12 | import { 13 | type ChainId, 14 | exceptions, 15 | type IApproveTransactionArgs, 16 | type ICoverInfo, 17 | type ICoverInfoStorage, 18 | type IProductInfo, 19 | type IWrappedResult, 20 | Status 21 | } from '../types/index.js' 22 | import { InvalidProductKeyError } from '../types/Exceptions/index.js' 23 | import { 24 | erc20Utils, 25 | ipfs, 26 | keyUtil, 27 | signer, 28 | store 29 | } from '../utils/index.js' 30 | 31 | const { GenericError, InvalidAccountError, InvalidSignerError, InvalidCoverKeyError } = exceptions 32 | 33 | const whitelistCoverCreator = async (chainId: ChainId, whitelisted: string, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 34 | const { ZERO_ADDRESS } = constants 35 | 36 | if (whitelisted === ZERO_ADDRESS) { 37 | throw new InvalidAccountError('Invalid account to whitelist') 38 | } 39 | 40 | const coverContract = await Cover.getInstance(chainId, signerOrProvider) 41 | 42 | const tx = await coverContract.updateCoverCreatorWhitelist([whitelisted], [true], transactionOverrides) 43 | 44 | return { 45 | status: Status.SUCCESS, 46 | result: { 47 | tx 48 | } 49 | } 50 | } 51 | 52 | const removeCoverCreatorFromWhitelist = async (chainId: ChainId, whitelisted: string, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 53 | const { ZERO_ADDRESS } = constants 54 | 55 | if (whitelisted === ZERO_ADDRESS) { 56 | throw new InvalidAccountError('Invalid account to whitelist') 57 | } 58 | 59 | const coverContract = await Cover.getInstance(chainId, signerOrProvider) 60 | 61 | const tx = await coverContract.updateCoverCreatorWhitelist([whitelisted], [false], transactionOverrides) 62 | 63 | return { 64 | status: Status.SUCCESS, 65 | result: { 66 | tx 67 | } 68 | } 69 | } 70 | 71 | const approveReassurance = async (chainId: ChainId, tokenAddress: string, args: IApproveTransactionArgs, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 72 | const reassuranceToken = IERC20.getInstance(tokenAddress, signerOrProvider) 73 | 74 | const contract = await Cover.getAddress(chainId, signerOrProvider) 75 | const amount = erc20Utils.getApprovalAmount(args) 76 | 77 | const result = await reassuranceToken.approve(contract, amount, transactionOverrides) 78 | 79 | return { 80 | status: Status.SUCCESS, 81 | result 82 | } 83 | } 84 | 85 | const approveStakeAndFees = async (chainId: ChainId, args: IApproveTransactionArgs, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 86 | const npm = await NPMToken.getInstance(chainId, signerOrProvider) 87 | const amount = erc20Utils.getApprovalAmount(args) 88 | const contract = await Cover.getAddress(chainId, signerOrProvider) 89 | const result = await npm.approve(contract, amount, transactionOverrides) 90 | 91 | return { 92 | status: Status.SUCCESS, 93 | result 94 | } 95 | } 96 | 97 | const getCoverInfo = async (chainId: ChainId, coverKey: string, provider: Provider): Promise => { 98 | const candidates = [{ 99 | key: [keyUtil.PROTOCOL.NS.COVER_INFO, coverKey], 100 | signature: ['bytes32', 'bytes32'], 101 | returns: 'string', 102 | property: 'info' 103 | }] 104 | const { info } = await store.readStorage(chainId, candidates, provider) 105 | 106 | if (info === '') { 107 | throw new InvalidCoverKeyError(`Invalid cover key ${coverKey}`) 108 | } 109 | 110 | return (await ipfs.read(info)) as ICoverInfoStorage 111 | } 112 | 113 | const getProductInfo = async (chainId: ChainId, coverKey: string, productKey: string, provider: Provider): Promise => { 114 | const candidates = [{ 115 | key: [keyUtil.PROTOCOL.NS.COVER_PRODUCT, coverKey, productKey], 116 | signature: ['bytes32', 'bytes32'], 117 | returns: 'bytes32', 118 | property: 'info' 119 | }] 120 | const { info } = await store.readStorage(chainId, candidates, provider) 121 | 122 | if (info === '') { 123 | throw new InvalidCoverKeyError('Invalid cover key or product key') 124 | } 125 | 126 | return (await ipfs.read(info)) as ICoverInfoStorage 127 | } 128 | 129 | const createCover = async (chainId: ChainId, info: ICoverInfo, ipfsHash: string, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 130 | const { key } = info 131 | 132 | if (!key) { // eslint-disable-line 133 | throw new InvalidCoverKeyError('Invalid or empty cover key') 134 | } 135 | 136 | if (!info.stakeWithFees) { // eslint-disable-line 137 | throw new GenericError('Invalid or empty cover fee') 138 | } 139 | 140 | if (!info.vault.name) { // eslint-disable-line 141 | throw new GenericError('Invalid vault name') 142 | } 143 | 144 | if (!info.vault.symbol) { // eslint-disable-line 145 | throw new GenericError('Invalid vault symbol') 146 | } 147 | 148 | if (typeof info.supportsProducts === 'undefined') { // eslint-disable-line 149 | throw new GenericError('Invalid value provided for supportsProducts') 150 | } 151 | 152 | if (typeof info.requiresWhitelist === 'undefined') { // eslint-disable-line 153 | throw new GenericError('Invalid value provided for requiresWhitelist') 154 | } 155 | 156 | const account = await signer.getAddress(signerOrProvider) 157 | 158 | if (account == null) { 159 | throw new InvalidSignerError('The provider is not a valid signer') 160 | } 161 | 162 | const coverContract = await Cover.getInstance(chainId, signerOrProvider) 163 | 164 | const addCoverArgs = { 165 | coverKey: key, 166 | info: ipfsHash, 167 | tokenName: info.vault.name, 168 | tokenSymbol: info.vault.symbol, 169 | supportsProducts: info.supportsProducts, 170 | requiresWhitelist: info.requiresWhitelist, 171 | stakeWithFee: info.stakeWithFees.toString(), 172 | initialReassuranceAmount: info.reassurance.toString(), 173 | minStakeToReport: info.minReportingStake.toString(), 174 | reportingPeriod: info.reportingPeriod.toString(), 175 | cooldownPeriod: info.cooldownPeriod.toString(), 176 | claimPeriod: info.claimPeriod.toString(), 177 | floor: info.pricingFloor.toString(), 178 | ceiling: info.pricingCeiling.toString(), 179 | reassuranceRate: info.reassuranceRate.toString(), 180 | leverageFactor: info.leverage.toString() 181 | } 182 | 183 | const tx = await coverContract.addCover( 184 | addCoverArgs, 185 | transactionOverrides 186 | ) 187 | 188 | return { 189 | status: Status.SUCCESS, 190 | result: { 191 | storage: { 192 | hash: ipfsHash, 193 | permalink: `https://ipfs.io/ipfs/${ipfsHash}` 194 | }, 195 | tx 196 | } 197 | } 198 | } 199 | 200 | const createProduct = async (chainId: ChainId, info: IProductInfo, ipfsHash: string, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 201 | const { ZERO_BYTES32 } = constants 202 | const { coverKey, productKey } = info 203 | 204 | if (!coverKey || coverKey === ZERO_BYTES32) { // eslint-disable-line 205 | throw new InvalidCoverKeyError('Invalid or empty cover key') 206 | } 207 | 208 | if (!productKey || productKey === ZERO_BYTES32) { // eslint-disable-line 209 | throw new InvalidProductKeyError('Invalid or empty product key') 210 | } 211 | 212 | const account = await signer.getAddress(signerOrProvider) 213 | 214 | if (account == null) { 215 | throw new InvalidSignerError('The provider is not a valid signer') 216 | } 217 | 218 | const coverContract = await Cover.getInstance(chainId, signerOrProvider) 219 | 220 | const status = 1 221 | const addProductArgs = { 222 | coverKey, 223 | productKey, 224 | info: ipfsHash, 225 | requiresWhitelist: info.requiresWhitelist, 226 | productStatus: status, 227 | efficiency: info.capitalEfficiency 228 | } 229 | 230 | const tx = await coverContract.addProduct( 231 | addProductArgs, 232 | transactionOverrides 233 | ) 234 | 235 | return { 236 | status: Status.SUCCESS, 237 | result: { 238 | storage: { 239 | hash: ipfsHash, 240 | permalink: `https://ipfs.io/ipfs/${ipfsHash}` 241 | }, 242 | tx 243 | } 244 | } 245 | } 246 | 247 | const updateCover = async (chainId: ChainId, info: ICoverInfo, ipfsHash: string, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 248 | const { key } = info 249 | 250 | if (!key) { // eslint-disable-line 251 | throw new InvalidCoverKeyError('Invalid or empty cover key') 252 | } 253 | 254 | if (!info.stakeWithFees) { // eslint-disable-line 255 | throw new GenericError('Invalid or empty cover fee') 256 | } 257 | 258 | const account = await signer.getAddress(signerOrProvider) 259 | 260 | if (account == null) { 261 | throw new InvalidSignerError('The provider is not a valid signer') 262 | } 263 | 264 | const coverContract = await Cover.getInstance(chainId, signerOrProvider) 265 | 266 | const tx = await coverContract.updateCover(key, ipfsHash, transactionOverrides) 267 | 268 | return { 269 | status: Status.SUCCESS, 270 | result: { 271 | storage: { 272 | hash: ipfsHash, 273 | permalink: `https://ipfs.io/ipfs/${ipfsHash}` 274 | }, 275 | tx 276 | } 277 | } 278 | } 279 | 280 | const updateProduct = async (chainId: ChainId, info: IProductInfo, ipfsHash: string, productStatus: number, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 281 | const { coverKey, productKey } = info 282 | 283 | if (!coverKey) { // eslint-disable-line 284 | throw new InvalidCoverKeyError('Invalid or empty cover key') 285 | } 286 | 287 | if (!productKey) { // eslint-disable-line 288 | throw new InvalidProductKeyError('Invalid or empty product key') 289 | } 290 | 291 | const account = await signer.getAddress(signerOrProvider) 292 | 293 | if (account == null) { 294 | throw new InvalidSignerError('The provider is not a valid signer') 295 | } 296 | 297 | const coverContract = await Cover.getInstance(chainId, signerOrProvider) 298 | 299 | const updateProductArgs = { 300 | coverKey, 301 | productKey, 302 | info: ipfsHash, 303 | productStatus, 304 | efficiency: info.capitalEfficiency 305 | } 306 | 307 | const tx = await coverContract.updateProduct( 308 | updateProductArgs, 309 | transactionOverrides 310 | ) 311 | 312 | return { 313 | status: Status.SUCCESS, 314 | result: { 315 | storage: { 316 | hash: ipfsHash, 317 | permalink: `https://ipfs.io/ipfs/${ipfsHash}` 318 | }, 319 | tx 320 | } 321 | } 322 | } 323 | 324 | export { 325 | approveReassurance, 326 | approveStakeAndFees, 327 | createCover, 328 | createProduct, 329 | getCoverInfo, 330 | getProductInfo, 331 | removeCoverCreatorFromWhitelist, 332 | updateCover, 333 | updateProduct, 334 | whitelistCoverCreator 335 | } 336 | -------------------------------------------------------------------------------- /src/core/cxToken.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Provider } from '@ethersproject/providers' 3 | 4 | import * as abis from '../config/abis/index.js' 5 | import { PolicyContract } from '../registry/index.js' 6 | import { 7 | type ChainId, 8 | type IWrappedResult, 9 | type PolicyDuration, 10 | Status 11 | } from '../types/index.js' 12 | import * as contract from '../utils/contract.js' 13 | 14 | const getCToken = async (chainId: ChainId, coverKey: string, productKey: string, duration: PolicyDuration, signerOrProvider: Provider | Signer): Promise => { 15 | const policy = await PolicyContract.getInstance(chainId, signerOrProvider) 16 | const values = await policy.getCxToken(coverKey, productKey, duration) 17 | const { cxToken, expiryDate } = values 18 | 19 | const instance = contract.getContract(cxToken, abis.ICxToken, signerOrProvider) 20 | 21 | return { 22 | status: Status.SUCCESS, 23 | result: { 24 | cxToken: instance, 25 | expiryDate 26 | } 27 | } 28 | } 29 | 30 | const getCTokenByAddress = async (address: string, signerOrProvider: Provider | Signer): Promise => { 31 | const instance = contract.getContract(address, abis.ICxToken, signerOrProvider) 32 | const expiryDate = await instance.expiresOn() 33 | 34 | return { 35 | status: Status.SUCCESS, 36 | result: { 37 | cxToken: instance, 38 | expiryDate 39 | } 40 | } 41 | } 42 | 43 | const getCTokenByExpiryDate = async (chainId: ChainId, coverKey: string, productKey: string, expiryDate: number, signerOrProvider: Provider | Signer): Promise => { 44 | const policy = await PolicyContract.getInstance(chainId, signerOrProvider) 45 | const cxToken = await policy.getCxTokenByExpiryDate(coverKey, productKey, expiryDate) 46 | 47 | const result = contract.getContract(cxToken, abis.ICxToken, signerOrProvider) 48 | 49 | return { 50 | status: Status.SUCCESS, 51 | result 52 | } 53 | } 54 | 55 | export { getCToken, getCTokenByAddress, getCTokenByExpiryDate } 56 | -------------------------------------------------------------------------------- /src/core/governance.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Provider } from '@ethersproject/providers' 3 | 4 | import { 5 | Governance, 6 | NPMToken 7 | } from '../registry/index.js' 8 | import { 9 | type ChainId, 10 | CoverStatus, 11 | type IApproveTransactionArgs, 12 | type IReportingInfo, 13 | type IWrappedResult, 14 | Status 15 | } from '../types/index.js' 16 | import { 17 | InvalidReportError, 18 | InvalidSignerError 19 | } from '../types/Exceptions/index.js' 20 | import { type IDisputeInfo } from '../types/IReportingInfo.js' 21 | import { 22 | erc20Utils, 23 | signer 24 | } from '../utils/index.js' 25 | 26 | const approveStake = async (chainId: ChainId, args: IApproveTransactionArgs, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 27 | const npm = await NPMToken.getInstance(chainId, signerOrProvider) 28 | const amount = erc20Utils.getApprovalAmount(args) 29 | const governance = await Governance.getAddress(chainId, signerOrProvider) 30 | const result = await npm.approve(governance, amount, transactionOverrides) 31 | 32 | return { 33 | status: Status.SUCCESS, 34 | result 35 | } 36 | } 37 | 38 | const report = async (chainId: ChainId, coverKey: string, productKey: string, info: IReportingInfo, ipfsHash: string, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 39 | const { title, observed, proofOfIncident, stake } = info 40 | 41 | if (!title) { // eslint-disable-line 42 | throw new InvalidReportError('Enter the report title') 43 | } 44 | 45 | if (!observed) { // eslint-disable-line 46 | throw new InvalidReportError('Specify when the incident was observed') 47 | } 48 | 49 | if (!proofOfIncident) { // eslint-disable-line 50 | throw new InvalidReportError('Provide a proof of the incident') 51 | } 52 | 53 | if (!stake) { // eslint-disable-line 54 | throw new InvalidReportError('Specify your NPM stake to report this incident') 55 | } 56 | 57 | const account = await signer.getAddress(signerOrProvider) 58 | 59 | if (account == null) { 60 | throw new InvalidSignerError('The provider is not a valid signer') 61 | } 62 | 63 | const governanceContract = await Governance.getInstance(chainId, signerOrProvider) 64 | const incidentDate = await governanceContract.getActiveIncidentDate(coverKey, productKey) 65 | 66 | if (incidentDate.toString() !== '0') { 67 | throw new InvalidReportError('The incident has already been reported') 68 | } 69 | 70 | const tx = await governanceContract.report( 71 | coverKey, 72 | productKey, 73 | ipfsHash, 74 | stake, 75 | transactionOverrides 76 | ) 77 | 78 | return { 79 | status: Status.SUCCESS, 80 | result: { 81 | storage: { 82 | hash: ipfsHash, 83 | permalink: `https://ipfs.io/ipfs/${ipfsHash}` 84 | }, 85 | tx 86 | } 87 | } 88 | } 89 | 90 | const dispute = async (chainId: ChainId, coverKey: string, productKey: string, info: IDisputeInfo, ipfsHash: string, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 91 | const { title, proofOfDispute, stake } = info 92 | 93 | if (!title) { // eslint-disable-line 94 | throw new InvalidReportError('Enter the dispute title') 95 | } 96 | 97 | if (!proofOfDispute) { // eslint-disable-line 98 | throw new InvalidReportError('Provide a proof of the dispute') 99 | } 100 | 101 | if (!stake) { // eslint-disable-line 102 | throw new InvalidReportError('Cannot dispute incident without NPM stake') 103 | } 104 | 105 | const governanceContract = await Governance.getInstance(chainId, signerOrProvider) 106 | const incidentDate = await governanceContract.getActiveIncidentDate(coverKey, productKey) 107 | 108 | if (incidentDate.toString() === '0') { 109 | throw new InvalidReportError('Cannot dispute a non-existing incident') 110 | } 111 | 112 | const [, no] = await governanceContract.getStakes(coverKey, productKey, incidentDate) // eslint-disable-line 113 | 114 | if (no.toString() !== '0') { 115 | throw new InvalidReportError('Cannot dispute an already-disputed incident') 116 | } 117 | 118 | const account = await signer.getAddress(signerOrProvider) 119 | 120 | if (account == null) { 121 | throw new InvalidSignerError('The provider is not a valid signer') 122 | } 123 | 124 | const tx = await governanceContract.dispute( 125 | coverKey, 126 | productKey, 127 | incidentDate, 128 | ipfsHash, 129 | stake, 130 | transactionOverrides 131 | ) 132 | 133 | return { 134 | status: Status.SUCCESS, 135 | result: { 136 | storage: { 137 | hash: ipfsHash, 138 | permalink: `https://ipfs.io/ipfs/${ipfsHash}` 139 | }, 140 | tx 141 | } 142 | } 143 | } 144 | 145 | const attest = async (chainId: ChainId, coverKey: string, productKey: string, stake: string, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 146 | if (!stake) { // eslint-disable-line 147 | throw new InvalidReportError('Cannot attest an incident without NPM stake') 148 | } 149 | 150 | const governanceContract = await Governance.getInstance(chainId, signerOrProvider) 151 | const incidentDate = await governanceContract.getActiveIncidentDate(coverKey, productKey) 152 | 153 | if (incidentDate.toString() === '0') { 154 | throw new InvalidReportError('Cannot attest a non-existing incident') 155 | } 156 | 157 | const result = await governanceContract.attest( 158 | coverKey, 159 | productKey, 160 | incidentDate, 161 | stake, 162 | transactionOverrides 163 | ) 164 | 165 | return { 166 | status: Status.SUCCESS, 167 | result 168 | } 169 | } 170 | 171 | const refute = async (chainId: ChainId, coverKey: string, productKey: string, stake: string, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 172 | if (!stake) { // eslint-disable-line 173 | throw new InvalidReportError('Cannot refute an incident without NPM stake') 174 | } 175 | 176 | const governanceContract = await Governance.getInstance(chainId, signerOrProvider) 177 | const incidentDate = await governanceContract.getActiveIncidentDate(coverKey, productKey) 178 | 179 | if (incidentDate.toString() === '0') { 180 | throw new InvalidReportError('Cannot refute a non-existing incident') 181 | } 182 | 183 | const result = await governanceContract.refute( 184 | coverKey, 185 | productKey, 186 | incidentDate, 187 | stake, 188 | transactionOverrides 189 | ) 190 | 191 | return { 192 | status: Status.SUCCESS, 193 | result 194 | } 195 | } 196 | 197 | const getMinStake = async (chainId: ChainId, coverKey: string, signerOrProvider: Provider | Signer): Promise => { 198 | const governanceContract = await Governance.getInstance(chainId, signerOrProvider) 199 | 200 | const result = await governanceContract.getFirstReportingStake(coverKey) 201 | 202 | return { 203 | status: Status.SUCCESS, 204 | result 205 | } 206 | } 207 | 208 | const getIncidentDate = async (chainId: ChainId, coverKey: string, productKey: string, signerOrProvider: Provider | Signer): Promise => { 209 | const governanceContract = await Governance.getInstance(chainId, signerOrProvider) 210 | 211 | const result = await governanceContract.getActiveIncidentDate(coverKey, productKey) 212 | 213 | return { 214 | status: Status.SUCCESS, 215 | result 216 | } 217 | } 218 | 219 | const getReporter = async (chainId: ChainId, coverKey: string, productKey: string, incidentDate: number, signerOrProvider: Provider | Signer): Promise => { 220 | const governanceContract = await Governance.getInstance(chainId, signerOrProvider) 221 | 222 | const result = await governanceContract.getReporter(coverKey, productKey, incidentDate) 223 | 224 | return { 225 | status: Status.SUCCESS, 226 | result 227 | } 228 | } 229 | 230 | const getStatus = async (chainId: ChainId, coverKey: string, productKey: string, signerOrProvider: Provider | Signer): Promise => { 231 | const governanceContract = await Governance.getInstance(chainId, signerOrProvider) 232 | 233 | const result = parseInt(await governanceContract.getStatus(coverKey, productKey)) 234 | 235 | return { 236 | status: Status.SUCCESS, 237 | result: { 238 | key: CoverStatus[result], 239 | value: result 240 | } 241 | } 242 | } 243 | 244 | const getStakes = async (chainId: ChainId, coverKey: string, productKey: string, incidentDate: number, signerOrProvider: Provider | Signer): Promise => { 245 | const governanceContract = await Governance.getInstance(chainId, signerOrProvider) 246 | 247 | const result = await governanceContract.getStakes(coverKey, productKey, incidentDate) 248 | const [yes, no] = result 249 | 250 | return { 251 | status: Status.SUCCESS, 252 | result: { 253 | yes, 254 | no 255 | } 256 | } 257 | } 258 | 259 | const getStakesOf = async (chainId: ChainId, coverKey: string, productKey: string, incidentDate: number, account: string, signerOrProvider: Provider | Signer): Promise => { 260 | const governanceContract = await Governance.getInstance(chainId, signerOrProvider) 261 | 262 | const result = await governanceContract.getStakesOf(coverKey, productKey, incidentDate, account) 263 | const [yes, no] = result 264 | 265 | return { 266 | status: Status.SUCCESS, 267 | result: { 268 | yes, 269 | no 270 | } 271 | } 272 | } 273 | 274 | export { 275 | approveStake, 276 | attest, 277 | dispute, 278 | getIncidentDate, 279 | getMinStake, 280 | getReporter, 281 | getStakes, 282 | getStakesOf, 283 | getStatus, 284 | refute, 285 | report 286 | } 287 | -------------------------------------------------------------------------------- /src/core/index.ts: -------------------------------------------------------------------------------- 1 | import * as claimsProcessor from './claimsProcessor.js' 2 | import * as cover from './cover.js' 3 | import * as cxToken from './cxToken.js' 4 | import * as governance from './governance.js' 5 | import * as liquidity from './liquidity.js' 6 | import * as policy from './policy.js' 7 | import * as reassurance from './reassurance.js' 8 | import * as resolution from './resolution.js' 9 | 10 | export { 11 | claimsProcessor, 12 | cover, 13 | cxToken, 14 | governance, 15 | liquidity, 16 | policy, 17 | reassurance, 18 | resolution 19 | } 20 | -------------------------------------------------------------------------------- /src/core/liquidity.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Provider } from '@ethersproject/providers' 3 | 4 | import { 5 | NPMToken, 6 | Stablecoin, 7 | Vault 8 | } from '../registry/index.js' 9 | import { 10 | type ChainId, 11 | type IApproveTransactionArgs, 12 | type IWrappedResult, 13 | Status 14 | } from '../types/index.js' 15 | import { 16 | erc20Utils, 17 | signer 18 | } from '../utils/index.js' 19 | 20 | const getAllowance = async (chainId: ChainId, key: string, owner: string, signerOrProvider: Provider | Signer): Promise => { 21 | const stablecoin = await Stablecoin.getInstance(chainId, signerOrProvider) 22 | const vault = await Vault.getAddress(chainId, key, signerOrProvider) 23 | 24 | const result = await stablecoin.allowance(owner, vault) 25 | 26 | return { 27 | status: Status.SUCCESS, 28 | result 29 | } 30 | } 31 | 32 | const approveStake = async (chainId: ChainId, key: string, args: IApproveTransactionArgs, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 33 | const npm = await NPMToken.getInstance(chainId, signerOrProvider) 34 | const amount = erc20Utils.getApprovalAmount(args) 35 | const vault = await Vault.getAddress(chainId, key, signerOrProvider) 36 | const result = await npm.approve(vault, amount, transactionOverrides) 37 | 38 | return { 39 | status: Status.SUCCESS, 40 | result 41 | } 42 | } 43 | 44 | const approve = async (chainId: ChainId, key: string, args: IApproveTransactionArgs, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 45 | const stablecoin = await Stablecoin.getInstance(chainId, signerOrProvider) 46 | const vault = await Vault.getAddress(chainId, key, signerOrProvider) 47 | 48 | const amount = erc20Utils.getApprovalAmount(args) 49 | 50 | const result = await stablecoin.approve(vault, amount, transactionOverrides) 51 | 52 | return { 53 | status: Status.SUCCESS, 54 | result 55 | } 56 | } 57 | 58 | const add = async (chainId: ChainId, coverKey: string, amount: string, stake: string, signerOrProvider: Provider | Signer, referralCode: string, transactionOverrides: any = {}): Promise => { 59 | const vault = await Vault.getInstance(chainId, coverKey, signerOrProvider) 60 | const result = await vault.addLiquidity({ 61 | coverKey, 62 | amount, 63 | npmStakeToAdd: stake, 64 | referralCode 65 | }, transactionOverrides) 66 | 67 | return { 68 | status: Status.SUCCESS, 69 | result 70 | } 71 | } 72 | 73 | const getBalance = async (chainId: ChainId, key: string, signerOrProvider: Provider | Signer): Promise => { 74 | const vault = await Vault.getInstance(chainId, key, signerOrProvider) 75 | const result = await vault.getStablecoinBalanceOf() 76 | 77 | return { 78 | status: Status.SUCCESS, 79 | result 80 | } 81 | } 82 | 83 | const getBalanceOf = async (chainId: ChainId, key: string, signerOrProvider: Provider | Signer): Promise => { 84 | const vault = await Vault.getInstance(chainId, key, signerOrProvider) 85 | const sender = await signer.getAddress(signerOrProvider) 86 | const result = await vault.balanceOf(sender) 87 | 88 | return { 89 | status: Status.SUCCESS, 90 | result 91 | } 92 | } 93 | 94 | export { add, approve, approveStake, getAllowance, getBalance, getBalanceOf } 95 | -------------------------------------------------------------------------------- /src/core/policy.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Provider } from '@ethersproject/providers' 3 | 4 | import { 5 | PolicyContract, 6 | Stablecoin 7 | } from '../registry/index.js' 8 | import { 9 | type ChainId, 10 | type IApproveTransactionArgs, 11 | type IPolicyFeeArgs, 12 | type IWrappedResult, 13 | Status 14 | } from '../types/index.js' 15 | import { erc20Utils } from '../utils/index.js' 16 | 17 | const getCoverFee = async (chainId: ChainId, coverKey: string, productKey: string, args: IPolicyFeeArgs, signerOrProvider: Provider | Signer): Promise => { 18 | const policy = await PolicyContract.getInstance(chainId, signerOrProvider) 19 | 20 | const { duration, amount } = args 21 | const result = await policy.getCoverFeeInfo(coverKey, productKey, duration, amount) 22 | 23 | return { 24 | status: Status.SUCCESS, 25 | result 26 | } 27 | } 28 | 29 | const getAllowance = async (chainId: ChainId, owner: string, signerOrProvider: Provider | Signer): Promise => { 30 | const stablecoin = await Stablecoin.getInstance(chainId, signerOrProvider) 31 | const policy = await PolicyContract.getAddress(chainId, signerOrProvider) 32 | 33 | const result = await stablecoin.allowance(owner, policy) 34 | 35 | return { 36 | status: Status.SUCCESS, 37 | result 38 | } 39 | } 40 | 41 | const approve = async (chainId: ChainId, args: IApproveTransactionArgs, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 42 | const stablecoin = await Stablecoin.getInstance(chainId, signerOrProvider) 43 | const policy = await PolicyContract.getAddress(chainId, signerOrProvider) 44 | 45 | const amount = erc20Utils.getApprovalAmount(args) 46 | 47 | const result = await stablecoin.approve(policy, amount, transactionOverrides) 48 | 49 | return { 50 | status: Status.SUCCESS, 51 | result 52 | } 53 | } 54 | 55 | const purchaseCover = async (chainId: ChainId, coverKey: string, productKey: string, args: IPolicyFeeArgs, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 56 | const policy = await PolicyContract.getInstance(chainId, signerOrProvider) 57 | 58 | const { duration, amount, referralCode, onBehalfOf } = args 59 | 60 | const purchaseCoverArgs = { 61 | onBehalfOf, 62 | coverKey, 63 | productKey, 64 | coverDuration: duration, 65 | amountToCover: amount, 66 | referralCode 67 | } 68 | const result = await policy.purchaseCover(purchaseCoverArgs, transactionOverrides) 69 | 70 | return { 71 | status: Status.SUCCESS, 72 | result 73 | } 74 | } 75 | 76 | export { approve, getAllowance, getCoverFee, purchaseCover } 77 | -------------------------------------------------------------------------------- /src/core/reassurance.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Provider } from '@ethersproject/providers' 3 | 4 | import { 5 | Reassurance, 6 | Stablecoin 7 | } from '../registry/index.js' 8 | import { 9 | type ChainId, 10 | type IApproveTransactionArgs, 11 | type IWrappedResult, 12 | Status 13 | } from '../types/index.js' 14 | import { getApprovalAmount } from '../utils/erc20-utils.js' 15 | import { getAddress } from '../utils/signer.js' 16 | 17 | const getAllowance = async (chainId: ChainId, owner: string, signerOrProvider: Provider | Signer): Promise => { 18 | const contract = await Reassurance.getAddress(chainId, signerOrProvider) 19 | const reassuranceToken = await Stablecoin.getInstance(chainId, signerOrProvider) 20 | 21 | const result = await reassuranceToken.allowance(owner, contract) 22 | 23 | return { 24 | status: Status.SUCCESS, 25 | result 26 | } 27 | } 28 | 29 | const approve = async (chainId: ChainId, args: IApproveTransactionArgs, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 30 | const contract = await Reassurance.getAddress(chainId, signerOrProvider) 31 | const amount = getApprovalAmount(args) 32 | 33 | const reassuranceToken = await Stablecoin.getInstance(chainId, signerOrProvider) 34 | 35 | const result = await reassuranceToken.approve(contract, amount, transactionOverrides) 36 | 37 | return { 38 | status: Status.SUCCESS, 39 | result 40 | } 41 | } 42 | 43 | const add = async (chainId: ChainId, key: string, amount: number, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 44 | const signer = await getAddress(signerOrProvider) 45 | const contract = await Reassurance.getInstance(chainId, signerOrProvider) 46 | const result = await contract.addReassurance(key, signer, amount, transactionOverrides) 47 | 48 | return { 49 | status: Status.SUCCESS, 50 | result 51 | } 52 | } 53 | 54 | const get = async (chainId: ChainId, key: string, signerOrProvider: Provider | Signer): Promise => { 55 | const contract = await Reassurance.getInstance(chainId, signerOrProvider) 56 | const result = await contract.getReassurance(key) 57 | 58 | return { 59 | status: Status.SUCCESS, 60 | result 61 | } 62 | } 63 | 64 | export { add, approve, get, getAllowance } 65 | -------------------------------------------------------------------------------- /src/core/resolution.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Provider } from '@ethersproject/providers' 3 | 4 | import { 5 | Governance, 6 | Resolution 7 | } from '../registry/index.js' 8 | import { 9 | type ChainId, 10 | type IWrappedResult, 11 | Status 12 | } from '../types/index.js' 13 | 14 | const finalize = async (chainId: ChainId, coverKey: string, productKey: string, incidentDate: number, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 15 | const resolutionContract = await Resolution.getInstance(chainId, signerOrProvider) 16 | 17 | const result = await resolutionContract.finalize(coverKey, productKey, incidentDate, transactionOverrides) 18 | 19 | return { 20 | status: Status.SUCCESS, 21 | result 22 | } 23 | } 24 | 25 | const resolve = async (chainId: ChainId, coverKey: string, productKey: string, incidentDate: number, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 26 | const resolutionContract = await Resolution.getInstance(chainId, signerOrProvider) 27 | 28 | const result = await resolutionContract.resolve(coverKey, productKey, incidentDate, transactionOverrides) 29 | 30 | return { 31 | status: Status.SUCCESS, 32 | result 33 | } 34 | } 35 | 36 | const emergencyResolve = async (chainId: ChainId, coverKey: string, productKey: string, incidentDate: number, decision: boolean, signerOrProvider: Provider | Signer, transactionOverrides: any = {}): Promise => { 37 | const resolutionContract = await Resolution.getInstance(chainId, signerOrProvider) 38 | 39 | const result = await resolutionContract.emergencyResolve(coverKey, productKey, incidentDate, decision, transactionOverrides) 40 | 41 | return { 42 | status: Status.SUCCESS, 43 | result 44 | } 45 | } 46 | 47 | const getResolutionDate = async (chainId: ChainId, coverKey: string, productKey: string, signerOrProvider: Provider | Signer): Promise => { 48 | const governanceContract = await Governance.getInstance(chainId, signerOrProvider) 49 | 50 | const result = await governanceContract.getResolutionTimestamp(coverKey, productKey) 51 | 52 | return { 53 | status: Status.SUCCESS, 54 | result 55 | } 56 | } 57 | 58 | export { emergencyResolve, finalize, getResolutionDate, resolve } 59 | -------------------------------------------------------------------------------- /src/entities/Token.ts: -------------------------------------------------------------------------------- 1 | import { 2 | type ChainId, 3 | type IToken 4 | } from '../types/index.js' 5 | 6 | class Token implements IToken { 7 | chainId: ChainId 8 | at: string 9 | name: string 10 | symbol: string 11 | 12 | constructor (chainId: ChainId, at: string, name: string, symbol: string) { 13 | this.chainId = chainId 14 | this.at = at 15 | this.name = name 16 | this.symbol = symbol 17 | } 18 | } 19 | 20 | export { Token } 21 | -------------------------------------------------------------------------------- /src/entities/index.ts: -------------------------------------------------------------------------------- 1 | import * as Token from './Token.js' 2 | 3 | export { Token } 4 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import * as config from './config/index.js' 2 | import { initialize } from './config/internal.js' 3 | import * as core from './core/index.js' 4 | import * as entities from './entities/index.js' 5 | import * as net from './net/index.js' 6 | import * as multicall from './packages/ethers-multicall/src/index.js' 7 | import * as registry from './registry/index.js' 8 | import * as types from './types/index.js' 9 | import * as utils from './utils/index.js' 10 | 11 | const { ChainId } = types 12 | const { reassurance, cover, policy, cxToken, liquidity, governance, resolution, claimsProcessor } = core 13 | 14 | const sdk = { 15 | ChainId, 16 | reassurance, 17 | cover, 18 | policy, 19 | cxToken, 20 | liquidity, 21 | registry, 22 | governance, 23 | initialize, 24 | resolution, 25 | claimsProcessor, 26 | types, 27 | entities, 28 | config, 29 | utils, 30 | net, 31 | multicall 32 | } 33 | 34 | export { 35 | ChainId, 36 | claimsProcessor, 37 | config, 38 | cover, 39 | cxToken, 40 | entities, 41 | governance, 42 | initialize, 43 | liquidity, 44 | multicall, 45 | net, 46 | policy, 47 | reassurance, 48 | registry, 49 | resolution, 50 | types, 51 | utils 52 | } 53 | 54 | export default sdk 55 | -------------------------------------------------------------------------------- /src/net/index.ts: -------------------------------------------------------------------------------- 1 | import IPFSClient from './ipfs-client.js' 2 | 3 | export { IPFSClient } 4 | -------------------------------------------------------------------------------- /src/net/ipfs-client.ts: -------------------------------------------------------------------------------- 1 | import { v4 as uuid } from 'uuid' 2 | 3 | class IPFSClient { 4 | urls: string[] 5 | 6 | constructor (urls: string[]) { 7 | this.urls = urls 8 | } 9 | 10 | createBoundary (stringPayload: string): string { 11 | let boundary = 'Delimiter.' 12 | 13 | while (true) { 14 | boundary += uuid() 15 | 16 | if (!stringPayload.includes(boundary)) { 17 | return boundary 18 | } 19 | } 20 | } 21 | 22 | async addString (value: string): Promise { 23 | const boundary: string = this.createBoundary(value) 24 | const payload: string = `--${boundary}\r\nContent-Disposition: form-data; name="path"\r\nContent-Type: application/octet-stream\r\n\r\n${value}\r\n--${boundary}--` 25 | let result 26 | 27 | for (const url of this.urls) { 28 | try { 29 | const options = { 30 | boundary, 31 | payload, 32 | method: 'POST', 33 | url: `${url}/api/v0/add`, 34 | headers: { 35 | Accept: 'application/json', 36 | 'Content-Type': `multipart/form-data; boundary=${boundary}` 37 | } 38 | } 39 | 40 | result = await this.call(options) 41 | } catch (error) { 42 | console.error(error) 43 | } 44 | } 45 | 46 | if (result !== undefined) { 47 | const { Hash } = JSON.parse(result) 48 | return Hash 49 | } 50 | 51 | return undefined 52 | } 53 | 54 | async getString (hash: string): Promise { 55 | return await Promise.any( 56 | this.urls.map(async (url) => { 57 | return await this.call({ 58 | hash, 59 | method: 'POST', 60 | url: `${url}/api/v0/cat?arg=${hash}`, 61 | headers: { 62 | Accept: 'application/json' 63 | } 64 | }) 65 | }) 66 | ) 67 | } 68 | 69 | async call (options: any): Promise { 70 | const { payload, method, url, headers } = options 71 | 72 | const response = await fetch(url, { 73 | body: payload, 74 | method, 75 | headers 76 | }) 77 | 78 | const result = await response.json() 79 | 80 | return JSON.stringify(result) 81 | } 82 | } 83 | 84 | export default IPFSClient 85 | -------------------------------------------------------------------------------- /src/packages/ethers-multicall/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Cavan Flynn 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /src/packages/ethers-multicall/README.md: -------------------------------------------------------------------------------- 1 | # ethers-multicall 2 | 3 | Make multiple Ethereum network requests in a single HTTP query. [ethcall](https://github.com/Destiner/ethcall) for ethers v5. 4 | 5 | ## API 6 | 7 | * `Contract(address, abi)`: Create contract instance; calling `contract.callFuncName` will yield a `call` object 8 | * `all(calls)`: Execute all calls in a single request 9 | * `calls`: List of helper call methods 10 | * `getEthBalance(address)`: Returns account ether balance 11 | 12 | ## Example 13 | 14 | ```ts 15 | import { Contract, Provider } from 'ethers-multicall'; 16 | import { ethers } from 'ethers'; 17 | 18 | import erc20Abi from './abi/erc20.json'; 19 | 20 | const infuraKey = 'INSERT_YOUR_KEY_HERE'; 21 | const provider = new ethers.providers.InfuraProvider('mainnet', infuraKey); 22 | 23 | const daiAddress = '0x6b175474e89094c44da98b954eedeac495271d0f'; 24 | 25 | async function call() { 26 | const ethcallProvider = new Provider(provider); 27 | 28 | await ethcallProvider.init(); // Only required when `chainId` is not provided in the `Provider` constructor 29 | 30 | const daiContract = new Contract(daiAddress, erc20Abi); 31 | 32 | const uniswapDaiPool = '0x2a1530c4c41db0b0b2bb646cb5eb1a67b7158667'; 33 | 34 | const ethBalanceCall = ethcallProvider.getEthBalance(uniswapDaiPool); 35 | const daiBalanceCall = daiContract.balanceOf(uniswapDaiPool); 36 | 37 | const [ethBalance, daiBalance] = await ethcallProvider.all([ethBalanceCall, daiBalanceCall]); 38 | 39 | console.log('ETH Balance:', ethBalance.toString()); 40 | console.log('DAI Balance:', daiBalance.toString()); 41 | } 42 | 43 | call(); 44 | ``` -------------------------------------------------------------------------------- /src/packages/ethers-multicall/src/abi.ts: -------------------------------------------------------------------------------- 1 | import { AbiCoder, ParamType } from '@ethersproject/abi' 2 | import { BytesLike } from '@ethersproject/bytes' 3 | import { keccak256 } from '@ethersproject/keccak256' 4 | import { toUtf8Bytes } from '@ethersproject/strings' 5 | 6 | export class Abi { 7 | public static encode (name: string, inputs: ParamType[], params: any[]): string { 8 | const functionSignature = getFunctionSignature(name, inputs) 9 | const functionHash = keccak256(toUtf8Bytes(functionSignature)) 10 | const functionData = functionHash.substring(2, 10) 11 | const abiCoder = new AbiCoder() 12 | const argumentString = abiCoder.encode(inputs, params) 13 | const argumentData = argumentString.substring(2) 14 | const inputData = `0x${functionData}${argumentData}` 15 | return inputData 16 | } 17 | 18 | public static decode (outputs: ParamType[], data: BytesLike) { 19 | const abiCoder = new AbiCoder() 20 | const params = abiCoder.decode(outputs, data) 21 | return params 22 | } 23 | } 24 | 25 | function getFunctionSignature (name: string, inputs: ParamType[]): string { 26 | const types = [] 27 | for (const input of inputs) { 28 | if (input.type === 'tuple') { 29 | const tupleString = getFunctionSignature('', input.components) 30 | types.push(tupleString) 31 | continue 32 | } 33 | if (input.type === 'tuple[]') { 34 | const tupleString = getFunctionSignature('', input.components) 35 | const arrayString = `${tupleString}[]` 36 | types.push(arrayString) 37 | continue 38 | } 39 | types.push(input.type) 40 | } 41 | const typeString = types.join(',') 42 | const functionSignature = `${name}(${typeString})` 43 | return functionSignature 44 | } 45 | -------------------------------------------------------------------------------- /src/packages/ethers-multicall/src/abi/multicall.ts: -------------------------------------------------------------------------------- 1 | export const multicallAbi = [ 2 | { 3 | constant: true, 4 | inputs: [ 5 | { 6 | components: [ 7 | { 8 | internalType: 'address', 9 | name: 'target', 10 | type: 'address', 11 | }, 12 | { 13 | internalType: 'bytes', 14 | name: 'callData', 15 | type: 'bytes', 16 | }, 17 | ], 18 | internalType: 'struct Multicall.Call[]', 19 | name: 'calls', 20 | type: 'tuple[]', 21 | }, 22 | ], 23 | name: 'aggregate', 24 | outputs: [ 25 | { 26 | internalType: 'uint256', 27 | name: 'blockNumber', 28 | type: 'uint256', 29 | }, 30 | { 31 | internalType: 'bytes[]', 32 | name: 'returnData', 33 | type: 'bytes[]', 34 | }, 35 | ], 36 | payable: false, 37 | stateMutability: 'view', 38 | type: 'function', 39 | }, 40 | { 41 | constant: true, 42 | inputs: [ 43 | { 44 | internalType: 'uint256', 45 | name: 'blockNumber', 46 | type: 'uint256', 47 | }, 48 | ], 49 | name: 'getBlockHash', 50 | outputs: [ 51 | { 52 | internalType: 'bytes32', 53 | name: 'blockHash', 54 | type: 'bytes32', 55 | }, 56 | ], 57 | payable: false, 58 | stateMutability: 'view', 59 | type: 'function', 60 | }, 61 | { 62 | constant: true, 63 | inputs: [], 64 | name: 'getCurrentBlockCoinbase', 65 | outputs: [ 66 | { 67 | internalType: 'address', 68 | name: 'coinbase', 69 | type: 'address', 70 | }, 71 | ], 72 | payable: false, 73 | stateMutability: 'view', 74 | type: 'function', 75 | }, 76 | { 77 | constant: true, 78 | inputs: [], 79 | name: 'getCurrentBlockDifficulty', 80 | outputs: [ 81 | { 82 | internalType: 'uint256', 83 | name: 'difficulty', 84 | type: 'uint256', 85 | }, 86 | ], 87 | payable: false, 88 | stateMutability: 'view', 89 | type: 'function', 90 | }, 91 | { 92 | constant: true, 93 | inputs: [], 94 | name: 'getCurrentBlockGasLimit', 95 | outputs: [ 96 | { 97 | internalType: 'uint256', 98 | name: 'gaslimit', 99 | type: 'uint256', 100 | }, 101 | ], 102 | payable: false, 103 | stateMutability: 'view', 104 | type: 'function', 105 | }, 106 | { 107 | constant: true, 108 | inputs: [], 109 | name: 'getCurrentBlockTimestamp', 110 | outputs: [ 111 | { 112 | internalType: 'uint256', 113 | name: 'timestamp', 114 | type: 'uint256', 115 | }, 116 | ], 117 | payable: false, 118 | stateMutability: 'view', 119 | type: 'function', 120 | }, 121 | { 122 | constant: true, 123 | inputs: [ 124 | { 125 | internalType: 'address', 126 | name: 'addr', 127 | type: 'address', 128 | }, 129 | ], 130 | name: 'getEthBalance', 131 | outputs: [ 132 | { 133 | internalType: 'uint256', 134 | name: 'balance', 135 | type: 'uint256', 136 | }, 137 | ], 138 | payable: false, 139 | stateMutability: 'view', 140 | type: 'function', 141 | }, 142 | { 143 | constant: true, 144 | inputs: [], 145 | name: 'getLastBlockHash', 146 | outputs: [ 147 | { 148 | internalType: 'bytes32', 149 | name: 'blockHash', 150 | type: 'bytes32', 151 | }, 152 | ], 153 | payable: false, 154 | stateMutability: 'view', 155 | type: 'function', 156 | }, 157 | ]; 158 | -------------------------------------------------------------------------------- /src/packages/ethers-multicall/src/call.ts: -------------------------------------------------------------------------------- 1 | import { Contract } from '@ethersproject/contracts' 2 | import { Provider } from '@ethersproject/providers' 3 | 4 | import { Abi } from './abi.js' 5 | import { multicallAbi } from './abi/multicall.js' 6 | import { ContractCall } from './types.js' 7 | 8 | export async function all ( 9 | calls: ContractCall[], 10 | multicallAddress: string, 11 | provider: Provider 12 | ): Promise { 13 | const multicall = new Contract(multicallAddress, multicallAbi, provider) 14 | const callRequests = calls.map(call => { 15 | const callData = Abi.encode(call.name, call.inputs, call.params) 16 | return { 17 | target: call.contract.address, 18 | callData 19 | } 20 | }) 21 | const response = await multicall.aggregate(callRequests) 22 | const callCount = calls.length 23 | const callResult = [] as unknown as T 24 | for (let i = 0; i < callCount; i++) { 25 | const outputs = calls[i].outputs 26 | const returnData = response.returnData[i] 27 | const params = Abi.decode(outputs, returnData) 28 | const result = outputs.length === 1 ? params[0] : params 29 | callResult.push(result) 30 | } 31 | return callResult 32 | } 33 | -------------------------------------------------------------------------------- /src/packages/ethers-multicall/src/calls.ts: -------------------------------------------------------------------------------- 1 | import { multicallAbi } from './abi/multicall.js'; 2 | import { Contract } from './contract.js'; 3 | 4 | export function getEthBalance(address: string, multicallAddress: string) { 5 | const multicall = new Contract(multicallAddress, multicallAbi); 6 | return multicall.getEthBalance(address); 7 | } 8 | -------------------------------------------------------------------------------- /src/packages/ethers-multicall/src/contract.ts: -------------------------------------------------------------------------------- 1 | import { Fragment, FunctionFragment, JsonFragment } from '@ethersproject/abi' 2 | 3 | export class Contract { 4 | private readonly _address: string 5 | private readonly _abi: Fragment[] 6 | private readonly _functions: FunctionFragment[] 7 | 8 | get address () { 9 | return this._address 10 | } 11 | 12 | get abi () { 13 | return this._abi 14 | } 15 | 16 | get functions () { 17 | return this._functions 18 | } 19 | 20 | constructor(address: string, abi: JsonFragment[] | string[] | Fragment[]) { 21 | this._address = address 22 | 23 | this._abi = toFragment(abi) 24 | 25 | this._functions = this._abi.filter(x => x.type === 'function').map(x => FunctionFragment.from(x)) 26 | const callFunctions = this._functions.filter(x => x.stateMutability === 'pure' || x.stateMutability === 'view') 27 | 28 | for (const callFunction of callFunctions) { 29 | const { name } = callFunction 30 | const getCall = makeCallFunction(this, name) 31 | if (!this[name]) { 32 | defineReadOnly(this, name, getCall) 33 | } 34 | } 35 | } 36 | 37 | [method: string]: any; 38 | } 39 | 40 | function toFragment (abi: JsonFragment[] | string[] | Fragment[]): Fragment[] { 41 | return abi.map((item: JsonFragment | string | Fragment) => Fragment.from(item)) 42 | } 43 | 44 | function makeCallFunction (contract: Contract, name: string) { 45 | return (...params: any[]) => { 46 | const { address } = contract 47 | const callFunction = contract.functions.find(f => f.name === name) 48 | 49 | if (!callFunction) { 50 | throw new Error("Function not found"); 51 | } 52 | 53 | const { inputs } = callFunction 54 | const { outputs } = callFunction 55 | return { 56 | contract: { 57 | address 58 | }, 59 | name, 60 | inputs, 61 | outputs, 62 | params 63 | } 64 | } 65 | } 66 | 67 | function defineReadOnly (object: object, name: string, value: unknown) { 68 | Object.defineProperty(object, name, { 69 | enumerable: true, 70 | value, 71 | writable: false 72 | }) 73 | } 74 | -------------------------------------------------------------------------------- /src/packages/ethers-multicall/src/index.ts: -------------------------------------------------------------------------------- 1 | import { Contract } from './contract.js'; 2 | import { Provider, setMulticallAddress } from './provider.js'; 3 | import { ContractCall } from './types.js'; 4 | 5 | export { Contract, Provider, ContractCall, setMulticallAddress }; 6 | export default { Contract, Provider, setMulticallAddress }; 7 | -------------------------------------------------------------------------------- /src/packages/ethers-multicall/src/provider.ts: -------------------------------------------------------------------------------- 1 | // @ts-nocheck 2 | import { Provider as EthersProvider } from '@ethersproject/abstract-provider'; 3 | import { all } from './call.js'; 4 | import { getEthBalance } from './calls.js'; 5 | import { ContractCall } from './types.js'; 6 | 7 | export class Provider { 8 | private _provider: EthersProvider; 9 | private _multicallAddress: string; 10 | 11 | constructor(provider: EthersProvider, chainId?: number) { 12 | this._provider = provider; 13 | this._multicallAddress = getAddressForChainId(chainId); 14 | } 15 | 16 | public async init() { 17 | // Only required if `chainId` was not provided in constructor 18 | this._multicallAddress = await getAddress(this._provider); 19 | } 20 | 21 | public getEthBalance(address: string) { 22 | if (!this._provider) { 23 | throw new Error('Provider should be initialized before use.'); 24 | } 25 | return getEthBalance(address, this._multicallAddress); 26 | } 27 | 28 | public async all(calls: ContractCall[]) { 29 | if (!this._provider) { 30 | throw new Error('Provider should be initialized before use.'); 31 | } 32 | return all(calls, this._multicallAddress, this._provider); 33 | } 34 | } 35 | 36 | const multicallAddresses = { 37 | 1: '0xeefba1e63905ef1d7acba5a8513c70307c1ce441', 38 | 3: '0xF24b01476a55d635118ca848fbc7Dab69d403be3', 39 | 4: '0x42ad527de7d4e9d9d011ac45b31d8551f8fe9821', 40 | 5: '0x77dca2c955b15e9de4dbbcf1246b4b85b651e50e', 41 | 42: '0x2cc8688c5f75e365aaeeb4ea8d6a480405a48d2a', 42 | 56: '0x1Ee38d535d541c55C9dae27B12edf090C608E6Fb', 43 | 66: '0x94fEadE0D3D832E4A05d459eBeA9350c6cDd3bCa', 44 | 97: '0x3A09ad1B8535F25b48e6Fa0CFd07dB6B017b31B2', 45 | 100: '0xb5b692a88bdfc81ca69dcb1d924f59f0413a602a', 46 | 128: '0x2C55D51804CF5b436BA5AF37bD7b8E5DB70EBf29', 47 | 137: '0x11ce4B23bD875D7F5C6a31084f55fDe1e9A87507', 48 | 250: '0x0118EF741097D0d3cc88e46233Da1e407d9ac139', 49 | 1337: '0x77dca2c955b15e9de4dbbcf1246b4b85b651e50e', 50 | 42161: '0x813715eF627B01f4931d8C6F8D2459F26E19137E', 51 | 43114: '0x7f3aC7C283d7E6662D886F494f7bc6F1993cDacf', 52 | 43113: '0xb209C02537de9A1Bf0c88B101B43540FDb8b70cF', 53 | 80001: '0x08411ADd0b5AA8ee47563b146743C13b3556c9Cc', 54 | 84531: '0xcA11bde05977b3631167028862bE2a173976CA11', 55 | }; 56 | 57 | export function setMulticallAddress(chainId: number, address: string) { 58 | multicallAddresses[chainId] = address; 59 | } 60 | 61 | function getAddressForChainId(chainId: number) { 62 | return multicallAddresses[chainId]; 63 | } 64 | 65 | async function getAddress(provider: EthersProvider) { 66 | const { chainId } = await provider.getNetwork(); 67 | return getAddressForChainId(chainId); 68 | } 69 | -------------------------------------------------------------------------------- /src/packages/ethers-multicall/src/types.ts: -------------------------------------------------------------------------------- 1 | import { ParamType } from '@ethersproject/abi'; 2 | 3 | export interface ContractCall { 4 | contract: { 5 | address: string; 6 | }; 7 | name: string; 8 | inputs: ParamType[]; 9 | outputs: ParamType[]; 10 | params: any[]; 11 | } 12 | -------------------------------------------------------------------------------- /src/registry/BondPool.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Contract } from '@ethersproject/contracts' 3 | import { type Provider } from '@ethersproject/providers' 4 | 5 | import * as abis from '../config/abis/index.js' 6 | import { type ChainId } from '../types/index.js' 7 | import * as contract from '../utils/contract.js' 8 | import * as keyUtil from '../utils/key-util.js' 9 | import { findAddress } from './MemberResolver.js' 10 | 11 | const getAddress = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 12 | // eslint-disable-next-line @typescript-eslint/return-await 13 | return findAddress(chainId, keyUtil.PROTOCOL.CNS.BOND_POOL, signerOrProvider) 14 | } 15 | 16 | const getInstance = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 17 | const address = await getAddress(chainId, signerOrProvider) 18 | return contract.getContract(address, abis.IBondPool, signerOrProvider) 19 | } 20 | 21 | export { getAddress, getInstance } 22 | -------------------------------------------------------------------------------- /src/registry/CachedStoreAddress.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Provider } from '@ethersproject/providers' 3 | 4 | import * as cache from '../cache/index.js' 5 | import { type ChainId } from '../types/index.js' 6 | import * as Store from './Store.js' 7 | 8 | const getOrFetch = async (chainId: ChainId, nsKey: string, signerOrProvider: Provider | Signer): Promise => { 9 | const cacheKey = cache.genKey(chainId, nsKey) 10 | const cached = cache.get(cacheKey) 11 | 12 | if (cached !== null) { 13 | return cached 14 | } 15 | 16 | const store = Store.getInstance(chainId, signerOrProvider) 17 | 18 | const address = await store.getAddress(nsKey) 19 | cache.set(cacheKey, address) 20 | 21 | return address 22 | } 23 | 24 | export { getOrFetch } 25 | -------------------------------------------------------------------------------- /src/registry/ClaimsProcessor.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Contract } from '@ethersproject/contracts' 3 | import { type Provider } from '@ethersproject/providers' 4 | 5 | import * as abis from '../config/abis/index.js' 6 | import { type ChainId } from '../types/index.js' 7 | import * as contract from '../utils/contract.js' 8 | import * as keyUtil from '../utils/key-util.js' 9 | import { findAddress } from './MemberResolver.js' 10 | 11 | const getAddress = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 12 | // eslint-disable-next-line @typescript-eslint/return-await 13 | return findAddress(chainId, keyUtil.PROTOCOL.CNS.CLAIM_PROCESSOR, signerOrProvider) 14 | } 15 | 16 | const getInstance = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 17 | const address = await getAddress(chainId, signerOrProvider) 18 | return contract.getContract(address, abis.IClaimsProcessor, signerOrProvider) 19 | } 20 | 21 | export { getAddress, getInstance } 22 | -------------------------------------------------------------------------------- /src/registry/Cover.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Contract } from '@ethersproject/contracts' 3 | import { type Provider } from '@ethersproject/providers' 4 | 5 | import * as abis from '../config/abis/index.js' 6 | import { type ChainId } from '../types/index.js' 7 | import * as contract from '../utils/contract.js' 8 | import * as keyUtil from '../utils/key-util.js' 9 | import { findAddress } from './MemberResolver.js' 10 | 11 | const getAddress = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 12 | // eslint-disable-next-line @typescript-eslint/return-await 13 | return findAddress(chainId, keyUtil.PROTOCOL.CNS.COVER, signerOrProvider) 14 | } 15 | 16 | const getInstance = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 17 | const address = await getAddress(chainId, signerOrProvider) 18 | return contract.getContract(address, abis.ICover, signerOrProvider) 19 | } 20 | 21 | export { getAddress, getInstance } 22 | -------------------------------------------------------------------------------- /src/registry/Governance.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Contract } from '@ethersproject/contracts' 3 | import { type Provider } from '@ethersproject/providers' 4 | 5 | import * as abis from '../config/abis/index.js' 6 | import { type ChainId } from '../types/index.js' 7 | import * as contract from '../utils/contract.js' 8 | import * as keyUtil from '../utils/key-util.js' 9 | import { findAddress } from './MemberResolver.js' 10 | 11 | const getAddress = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 12 | // eslint-disable-next-line @typescript-eslint/return-await 13 | return findAddress(chainId, keyUtil.PROTOCOL.CNS.GOVERNANCE, signerOrProvider) 14 | } 15 | 16 | const getInstance = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 17 | const address = await getAddress(chainId, signerOrProvider) 18 | return contract.getContract(address, abis.IGovernance, signerOrProvider) 19 | } 20 | 21 | export { getAddress, getInstance } 22 | -------------------------------------------------------------------------------- /src/registry/IERC20.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Contract } from '@ethersproject/contracts' 3 | import { type Provider } from '@ethersproject/providers' 4 | 5 | import * as abis from '../config/abis/index.js' 6 | import * as contract from '../utils/contract.js' 7 | 8 | const getInstance = (tokenAddress: string, signerOrProvider: Provider | Signer): Contract => { 9 | return contract.getContract(tokenAddress, abis.IERC20Detailed, signerOrProvider) 10 | } 11 | 12 | export { getInstance } 13 | -------------------------------------------------------------------------------- /src/registry/IUniswapV2FactoryLike.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Contract } from '@ethersproject/contracts' 3 | import { type Provider } from '@ethersproject/providers' 4 | 5 | import * as abis from '../config/abis/index.js' 6 | import { type ChainId } from '../types/index.js' 7 | import * as contract from '../utils/contract.js' 8 | import * as keyUtil from '../utils/key-util.js' 9 | import { getOrFetch } from './CachedStoreAddress.js' 10 | 11 | const getAddress = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 12 | // eslint-disable-next-line @typescript-eslint/return-await 13 | return getOrFetch(chainId, keyUtil.PROTOCOL.CNS.UNISWAP_V2_FACTORY, signerOrProvider) 14 | } 15 | 16 | const getInstance = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 17 | const address = await getAddress(chainId, signerOrProvider) 18 | return contract.getContract(address, abis.IUniswapV2FactoryLike, signerOrProvider) 19 | } 20 | 21 | export { getAddress, getInstance } 22 | -------------------------------------------------------------------------------- /src/registry/IUniswapV2PairLike.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Contract } from '@ethersproject/contracts' 3 | import { type Provider } from '@ethersproject/providers' 4 | 5 | import * as abis from '../config/abis/index.js' 6 | import * as contract from '../utils/contract.js' 7 | 8 | const getInstance = async (fromAddress: string, signerOrProvider: Provider | Signer): Promise => { 9 | return contract.getContract(fromAddress, abis.IUniswapV2PairLike, signerOrProvider) 10 | } 11 | 12 | export { getInstance } 13 | -------------------------------------------------------------------------------- /src/registry/IUniswapV2RouterLike.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Contract } from '@ethersproject/contracts' 3 | import { type Provider } from '@ethersproject/providers' 4 | 5 | import * as abis from '../config/abis/index.js' 6 | import { type ChainId } from '../types/index.js' 7 | import * as contract from '../utils/contract.js' 8 | import * as keyUtil from '../utils/key-util.js' 9 | import { getOrFetch } from './CachedStoreAddress.js' 10 | 11 | const getAddress = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 12 | // eslint-disable-next-line @typescript-eslint/return-await 13 | return getOrFetch(chainId, keyUtil.PROTOCOL.CNS.UNISWAP_V2_ROUTER, signerOrProvider) 14 | } 15 | 16 | const getInstance = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 17 | const address = await getAddress(chainId, signerOrProvider) 18 | return contract.getContract(address, abis.IUniswapV2RouterLike, signerOrProvider) 19 | } 20 | 21 | export { getAddress, getInstance } 22 | -------------------------------------------------------------------------------- /src/registry/MemberResolver.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Provider } from '@ethersproject/providers' 3 | 4 | import { type ChainId } from '../types/index.js' 5 | import * as keyUtil from '../utils/key-util.js' 6 | import { getOrFetch } from './CachedStoreAddress.js' 7 | 8 | const findAddress = async (chainId: ChainId, cnsBytes32: string, signerOrProvider: Provider | Signer): Promise => { 9 | const key = keyUtil.encodeKeys(['bytes32', 'bytes32'], [keyUtil.PROTOCOL.NS.CONTRACTS, cnsBytes32]) 10 | 11 | // eslint-disable-next-line @typescript-eslint/return-await 12 | return getOrFetch(chainId, key, signerOrProvider) 13 | } 14 | 15 | export { findAddress } 16 | -------------------------------------------------------------------------------- /src/registry/NPMToken.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Contract } from '@ethersproject/contracts' 3 | import { type Provider } from '@ethersproject/providers' 4 | 5 | import * as abis from '../config/abis/index.js' 6 | import { type ChainId } from '../types/index.js' 7 | import * as contract from '../utils/contract.js' 8 | import * as keyUtil from '../utils/key-util.js' 9 | import { getOrFetch } from './CachedStoreAddress.js' 10 | 11 | const getAddress = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 12 | // eslint-disable-next-line @typescript-eslint/return-await 13 | return getOrFetch(chainId, keyUtil.PROTOCOL.CNS.NPM, signerOrProvider) 14 | } 15 | 16 | const getInstance = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 17 | const address = await getAddress(chainId, signerOrProvider) 18 | return contract.getContract(address, abis.IERC20Detailed, signerOrProvider) 19 | } 20 | 21 | export { getAddress, getInstance } 22 | -------------------------------------------------------------------------------- /src/registry/PolicyContract.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Contract } from '@ethersproject/contracts' 3 | import { type Provider } from '@ethersproject/providers' 4 | 5 | import * as abis from '../config/abis/index.js' 6 | import { type ChainId } from '../types/index.js' 7 | import * as contract from '../utils/contract.js' 8 | import * as keyUtil from '../utils/key-util.js' 9 | import { findAddress } from './MemberResolver.js' 10 | 11 | const getAddress = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 12 | // eslint-disable-next-line @typescript-eslint/return-await 13 | return findAddress(chainId, keyUtil.PROTOCOL.CNS.COVER_POLICY, signerOrProvider) 14 | } 15 | 16 | const getInstance = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 17 | const address = await getAddress(chainId, signerOrProvider) 18 | return contract.getContract(address, abis.IPolicy, signerOrProvider) 19 | } 20 | 21 | export { getAddress, getInstance } 22 | -------------------------------------------------------------------------------- /src/registry/Protocol.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Contract } from '@ethersproject/contracts' 3 | import { type Provider } from '@ethersproject/providers' 4 | 5 | import * as abis from '../config/abis/index.js' 6 | import { type ChainId } from '../types/index.js' 7 | import * as contract from '../utils/contract.js' 8 | import * as keyUtil from '../utils/key-util.js' 9 | import { getOrFetch } from './CachedStoreAddress.js' 10 | 11 | const getAddress = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 12 | // eslint-disable-next-line @typescript-eslint/return-await 13 | return getOrFetch(chainId, keyUtil.PROTOCOL.CNS.CORE, signerOrProvider) 14 | } 15 | 16 | const getInstance = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 17 | const address = await getAddress(chainId, signerOrProvider) 18 | return contract.getContract(address, abis.IProtocol, signerOrProvider) 19 | } 20 | 21 | export { getAddress, getInstance } 22 | -------------------------------------------------------------------------------- /src/registry/Reassurance.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Contract } from '@ethersproject/contracts' 3 | import { type Provider } from '@ethersproject/providers' 4 | 5 | import * as abis from '../config/abis/index.js' 6 | import { type ChainId } from '../types/index.js' 7 | import * as contract from '../utils/contract.js' 8 | import * as keyUtil from '../utils/key-util.js' 9 | import { findAddress } from './MemberResolver.js' 10 | 11 | const getAddress = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 12 | // eslint-disable-next-line @typescript-eslint/return-await 13 | return findAddress(chainId, keyUtil.PROTOCOL.CNS.COVER_REASSURANCE, signerOrProvider) 14 | } 15 | 16 | const getInstance = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 17 | const address = await getAddress(chainId, signerOrProvider) 18 | return contract.getContract(address, abis.ICoverReassurance, signerOrProvider) 19 | } 20 | 21 | export { getAddress, getInstance } 22 | -------------------------------------------------------------------------------- /src/registry/Resolution.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Contract } from '@ethersproject/contracts' 3 | import { type Provider } from '@ethersproject/providers' 4 | 5 | import * as abis from '../config/abis/index.js' 6 | import { type ChainId } from '../types/index.js' 7 | import * as contract from '../utils/contract.js' 8 | import * as keyUtil from '../utils/key-util.js' 9 | import { findAddress } from './MemberResolver.js' 10 | 11 | const getAddress = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 12 | // eslint-disable-next-line @typescript-eslint/return-await 13 | return findAddress(chainId, keyUtil.PROTOCOL.CNS.GOVERNANCE_RESOLUTION, signerOrProvider) 14 | } 15 | 16 | const getInstance = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 17 | const address = await getAddress(chainId, signerOrProvider) 18 | return contract.getContract(address, abis.IResolution, signerOrProvider) 19 | } 20 | 21 | export { getAddress, getInstance } 22 | -------------------------------------------------------------------------------- /src/registry/Stablecoin.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Contract } from '@ethersproject/contracts' 3 | import { type Provider } from '@ethersproject/providers' 4 | 5 | import * as abis from '../config/abis/index.js' 6 | import { type ChainId } from '../types/index.js' 7 | import * as contract from '../utils/contract.js' 8 | import * as keyUtil from '../utils/key-util.js' 9 | import { getOrFetch } from './CachedStoreAddress.js' 10 | 11 | const getAddress = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 12 | // eslint-disable-next-line @typescript-eslint/return-await 13 | return getOrFetch(chainId, keyUtil.PROTOCOL.CNS.COVER_STABLECOIN, signerOrProvider) 14 | } 15 | 16 | const getInstance = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 17 | const address = await getAddress(chainId, signerOrProvider) 18 | return contract.getContract(address, abis.IERC20Detailed, signerOrProvider) 19 | } 20 | 21 | export { getAddress, getInstance } 22 | -------------------------------------------------------------------------------- /src/registry/Staking.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Contract } from '@ethersproject/contracts' 3 | import { type Provider } from '@ethersproject/providers' 4 | 5 | import * as abis from '../config/abis/index.js' 6 | import { type ChainId } from '../types/index.js' 7 | import * as contract from '../utils/contract.js' 8 | import * as keyUtil from '../utils/key-util.js' 9 | import { findAddress } from './MemberResolver.js' 10 | 11 | const getAddress = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 12 | // eslint-disable-next-line @typescript-eslint/return-await 13 | return findAddress(chainId, keyUtil.PROTOCOL.CNS.COVER_STAKE, signerOrProvider) 14 | } 15 | 16 | const getInstance = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 17 | const address = await getAddress(chainId, signerOrProvider) 18 | return contract.getContract(address, abis.ICoverStake, signerOrProvider) 19 | } 20 | 21 | export { getAddress, getInstance } 22 | -------------------------------------------------------------------------------- /src/registry/StakingPools.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Contract } from '@ethersproject/contracts' 3 | import { type Provider } from '@ethersproject/providers' 4 | 5 | import * as abis from '../config/abis/index.js' 6 | import { type ChainId } from '../types/index.js' 7 | import * as contract from '../utils/contract.js' 8 | import * as keyUtil from '../utils/key-util.js' 9 | import { findAddress } from './MemberResolver.js' 10 | 11 | const getAddress = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 12 | // eslint-disable-next-line @typescript-eslint/return-await 13 | return findAddress(chainId, keyUtil.PROTOCOL.CNS.STAKING_POOL, signerOrProvider) 14 | } 15 | 16 | const getInstance = async (chainId: ChainId, signerOrProvider: Provider | Signer): Promise => { 17 | const address = await getAddress(chainId, signerOrProvider) 18 | return contract.getContract(address, abis.IStakingPools, signerOrProvider) 19 | } 20 | 21 | export { getAddress, getInstance } 22 | -------------------------------------------------------------------------------- /src/registry/Store.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Contract } from '@ethersproject/contracts' 3 | import { type Provider } from '@ethersproject/providers' 4 | 5 | import { 6 | abis, 7 | networks 8 | } from '../config/index.js' 9 | import { type ChainId } from '../types/index.js' 10 | import * as contract from '../utils/contract.js' 11 | 12 | const getInstance = (chainId: ChainId, signerOrProvider: Provider | Signer): Contract => { 13 | const { store } = networks.getChainConfig(chainId) 14 | return contract.getContract(store, abis.IStore, signerOrProvider) 15 | } 16 | 17 | export { getInstance } 18 | -------------------------------------------------------------------------------- /src/registry/Vault.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Contract } from '@ethersproject/contracts' 3 | import { type Provider } from '@ethersproject/providers' 4 | 5 | import * as abis from '../config/abis/index.js' 6 | import { type ChainId } from '../types/index.js' 7 | import * as contract from '../utils/contract.js' 8 | import * as keyUtil from '../utils/key-util.js' 9 | import { getOrFetch } from './CachedStoreAddress.js' 10 | 11 | const getAddress = async (chainId: ChainId, coverKey: string, signerOrProvider: Provider | Signer): Promise => { 12 | const key = keyUtil.encodeKeys(['bytes32', 'bytes32', 'bytes32'], [keyUtil.PROTOCOL.NS.CONTRACTS, keyUtil.PROTOCOL.CNS.COVER_VAULT, coverKey]) 13 | 14 | // eslint-disable-next-line @typescript-eslint/return-await 15 | return getOrFetch(chainId, key, signerOrProvider) 16 | } 17 | 18 | const getInstance = async (chainId: ChainId, coverKey: string, signerOrProvider: Provider | Signer): Promise => { 19 | const address = await getAddress(chainId, coverKey, signerOrProvider) 20 | return contract.getContract(address, abis.IVault, signerOrProvider) 21 | } 22 | 23 | const getInstanceByAddress = async (address: string, signerOrProvider: Provider | Signer): Promise => { 24 | return contract.getContract(address, abis.IVault, signerOrProvider) 25 | } 26 | 27 | export { getAddress, getInstance, getInstanceByAddress } 28 | -------------------------------------------------------------------------------- /src/registry/index.ts: -------------------------------------------------------------------------------- 1 | import * as BondPool from './BondPool.js' 2 | import * as ClaimsProcessor from './ClaimsProcessor.js' 3 | import * as Cover from './Cover.js' 4 | import * as Governance from './Governance.js' 5 | import * as IERC20 from './IERC20.js' 6 | import * as IUniswapV2FactoryLike from './IUniswapV2FactoryLike.js' 7 | import * as IUniswapV2PairLike from './IUniswapV2PairLike.js' 8 | import * as IUniswapV2RouterLike from './IUniswapV2RouterLike.js' 9 | import * as NPMToken from './NPMToken.js' 10 | import * as PolicyContract from './PolicyContract.js' 11 | import * as Protocol from './Protocol.js' 12 | import * as Reassurance from './Reassurance.js' 13 | import * as Resolution from './Resolution.js' 14 | import * as Stablecoin from './Stablecoin.js' 15 | import * as Staking from './Staking.js' 16 | import * as StakingPools from './StakingPools.js' 17 | import * as Store from './Store.js' 18 | import * as Vault from './Vault.js' 19 | 20 | export { 21 | BondPool, 22 | ClaimsProcessor, 23 | Cover, 24 | Governance, 25 | IERC20, 26 | IUniswapV2FactoryLike, 27 | IUniswapV2PairLike, 28 | IUniswapV2RouterLike, 29 | NPMToken, 30 | PolicyContract, 31 | Protocol, 32 | Reassurance, 33 | Resolution, 34 | Stablecoin, 35 | Staking, 36 | StakingPools, 37 | Store, 38 | Vault 39 | } 40 | -------------------------------------------------------------------------------- /src/types/ChainId.ts: -------------------------------------------------------------------------------- 1 | enum ChainId { 2 | Invalid = 0, 3 | Ethereum = 1, 4 | BSC = 56, 5 | BaseGoerli = 84531, 6 | Mumbai = 80001, 7 | Fuji = 43113, 8 | Arbitrum = 42161, // Arbitrum One 9 | } 10 | 11 | export { ChainId } 12 | -------------------------------------------------------------------------------- /src/types/CoverStatus.ts: -------------------------------------------------------------------------------- 1 | enum CoverStatus { 2 | Normal = 0, 3 | Stopped = 1, 4 | IncidentHappened = 2, 5 | FalseReporting = 3, 6 | Claimable = 4 7 | } 8 | 9 | export { CoverStatus } 10 | -------------------------------------------------------------------------------- /src/types/Exceptions/BaseError.ts: -------------------------------------------------------------------------------- 1 | class BaseError extends Error { 2 | constructor (message: string) { 3 | super(message) 4 | Object.setPrototypeOf(this, new.target.prototype) 5 | } 6 | } 7 | 8 | export { BaseError } 9 | -------------------------------------------------------------------------------- /src/types/Exceptions/DuplicateCoverError.ts: -------------------------------------------------------------------------------- 1 | import { BaseError } from './BaseError.js' 2 | 3 | class DuplicateCoverError extends BaseError {} 4 | 5 | export { DuplicateCoverError } 6 | -------------------------------------------------------------------------------- /src/types/Exceptions/GenericError.ts: -------------------------------------------------------------------------------- 1 | import { BaseError } from './BaseError.js' 2 | 3 | class GenericError extends BaseError {} 4 | 5 | export { GenericError } 6 | -------------------------------------------------------------------------------- /src/types/Exceptions/InvalidAccountError.ts: -------------------------------------------------------------------------------- 1 | import { BaseError } from './BaseError.js' 2 | 3 | class InvalidAccountError extends BaseError {} 4 | 5 | export { InvalidAccountError } 6 | -------------------------------------------------------------------------------- /src/types/Exceptions/InvalidChainIdError.ts: -------------------------------------------------------------------------------- 1 | import { BaseError } from './BaseError.js' 2 | 3 | class InvalidChainIdError extends BaseError {} 4 | 5 | export { InvalidChainIdError } 6 | -------------------------------------------------------------------------------- /src/types/Exceptions/InvalidCoverKeyError.ts: -------------------------------------------------------------------------------- 1 | import { BaseError } from './BaseError.js' 2 | 3 | class InvalidCoverKeyError extends BaseError {} 4 | 5 | export { InvalidCoverKeyError } 6 | -------------------------------------------------------------------------------- /src/types/Exceptions/InvalidProductKeyError.ts: -------------------------------------------------------------------------------- 1 | import { BaseError } from './BaseError.js' 2 | 3 | class InvalidProductKeyError extends BaseError {} 4 | 5 | export { InvalidProductKeyError } 6 | -------------------------------------------------------------------------------- /src/types/Exceptions/InvalidReportError.ts: -------------------------------------------------------------------------------- 1 | import { BaseError } from './BaseError.js' 2 | 3 | class InvalidReportError extends BaseError {} 4 | 5 | export { InvalidReportError } 6 | -------------------------------------------------------------------------------- /src/types/Exceptions/InvalidSignerError.ts: -------------------------------------------------------------------------------- 1 | import { BaseError } from './BaseError.js' 2 | 3 | class InvalidSignerError extends BaseError {} 4 | 5 | export { InvalidSignerError } 6 | -------------------------------------------------------------------------------- /src/types/Exceptions/InvalidStoreError.ts: -------------------------------------------------------------------------------- 1 | import { BaseError } from './BaseError.js' 2 | 3 | class InvalidStoreError extends BaseError {} 4 | 5 | export { InvalidStoreError } 6 | -------------------------------------------------------------------------------- /src/types/Exceptions/UnsupportedBlockchainError.ts: -------------------------------------------------------------------------------- 1 | import { BaseError } from './BaseError.js' 2 | 3 | class UnsupportedBlockchainError extends BaseError {} 4 | 5 | export { UnsupportedBlockchainError } 6 | -------------------------------------------------------------------------------- /src/types/Exceptions/index.ts: -------------------------------------------------------------------------------- 1 | import { BaseError } from './BaseError.js' 2 | import { DuplicateCoverError } from './DuplicateCoverError.js' 3 | import { GenericError } from './GenericError.js' 4 | import { InvalidSignerError } from './InvalidSignerError.js' 5 | import { UnsupportedBlockchainError } from './UnsupportedBlockchainError.js' 6 | import { InvalidCoverKeyError } from './InvalidCoverKeyError.js' 7 | import { InvalidProductKeyError } from './InvalidProductKeyError.js' 8 | import { InvalidReportError } from './InvalidReportError.js' 9 | import { InvalidAccountError } from './InvalidAccountError.js' 10 | 11 | export { 12 | BaseError, 13 | DuplicateCoverError, 14 | GenericError, 15 | InvalidAccountError, 16 | InvalidCoverKeyError, 17 | InvalidProductKeyError, 18 | InvalidReportError, 19 | InvalidSignerError, 20 | UnsupportedBlockchainError 21 | } 22 | -------------------------------------------------------------------------------- /src/types/IApproveTransactionArgs.ts: -------------------------------------------------------------------------------- 1 | interface IApproveTransactionArgs { 2 | amount?: string 3 | } 4 | 5 | export type { IApproveTransactionArgs } 6 | -------------------------------------------------------------------------------- /src/types/ICacheProvider.ts: -------------------------------------------------------------------------------- 1 | interface ICacheProvider { 2 | get: (key: string) => string | null 3 | set: (key: string, value: string) => void 4 | remove: (key: string) => void 5 | } 6 | 7 | export type { ICacheProvider } 8 | -------------------------------------------------------------------------------- /src/types/ICoverInfo.ts: -------------------------------------------------------------------------------- 1 | import { type ChainId } from './ChainId.js' 2 | 3 | interface ICoverInfo { 4 | key: string 5 | coverName: string 6 | projectName?: string 7 | vault: { 8 | name: string 9 | symbol: string 10 | } 11 | requiresWhitelist: boolean 12 | supportsProducts: boolean 13 | leverage: string 14 | tags: string[] 15 | about: string 16 | blockchains?: Array<{ 17 | chainId?: number 18 | name: string 19 | }> 20 | rules: string 21 | exclusions: string 22 | links?: { 23 | website: string 24 | documentation?: string 25 | telegram?: string 26 | twitter?: string 27 | github?: string 28 | facebook?: string 29 | blog?: string 30 | discord?: string 31 | linkedin?: string 32 | slack?: string 33 | } 34 | pricingFloor: string 35 | pricingCeiling: string 36 | reportingPeriod: number 37 | cooldownPeriod: number 38 | claimPeriod: number 39 | minReportingStake: string 40 | resolutionSources: string[] 41 | stakeWithFees: string 42 | reassurance: string 43 | reassuranceRate: string 44 | stakingPool?: { 45 | name: string 46 | settings: { 47 | [key in ChainId]?: { 48 | rewardToken: { symbol: string } 49 | uniRewardTokenDollarPair: { token: string } 50 | stakingTarget: string 51 | maxStake: string 52 | rewardPerBlock: string 53 | lockupPeriodInBlocks: string 54 | rewardTokenDeposit: string 55 | } 56 | } 57 | } 58 | } 59 | 60 | export type { ICoverInfo } 61 | -------------------------------------------------------------------------------- /src/types/ICoverInfoStorage.ts: -------------------------------------------------------------------------------- 1 | import { type ICoverInfo } from './ICoverInfo.js' 2 | 3 | interface ICoverInfoStorage extends ICoverInfo { 4 | createdBy: string 5 | permalink: string 6 | } 7 | 8 | export type { ICoverInfoStorage } 9 | -------------------------------------------------------------------------------- /src/types/INetwork.ts: -------------------------------------------------------------------------------- 1 | import { type ChainId } from './ChainId.js' 2 | import { type IToken } from './IToken.js' 3 | 4 | interface INetwork { 5 | chainId: ChainId 6 | chain: string 7 | approximateBlockTime: number 8 | store: string 9 | uniswap: { 10 | factory: string | null 11 | router: string | null 12 | masterChef: string | null 13 | } 14 | tokens: { 15 | WETH: IToken 16 | } 17 | hostname: string 18 | } 19 | 20 | export type { INetwork } 21 | -------------------------------------------------------------------------------- /src/types/IPolicyFeeArgs.ts: -------------------------------------------------------------------------------- 1 | import { type PolicyDuration } from './PolicyDuration.js' 2 | 3 | interface IPolicyFeeArgs { 4 | duration: PolicyDuration 5 | amount: string 6 | referralCode: string 7 | onBehalfOf: string 8 | } 9 | 10 | export type { IPolicyFeeArgs } 11 | -------------------------------------------------------------------------------- /src/types/IProductInfo.ts: -------------------------------------------------------------------------------- 1 | interface IProductInfo { 2 | coverKey: string 3 | productKey: string 4 | productName: string 5 | requiresWhitelist: boolean 6 | capitalEfficiency: string 7 | tags: string[] 8 | about: string 9 | rules: string 10 | exclusions: string 11 | links: { 12 | website: string 13 | documentation?: string 14 | telegram?: string 15 | twitter?: string 16 | github?: string 17 | facebook?: string 18 | blog?: string 19 | discord?: string 20 | linkedin?: string 21 | slack?: string 22 | } 23 | resolutionSources: string[] 24 | } 25 | 26 | export type { IProductInfo } 27 | -------------------------------------------------------------------------------- /src/types/IProductInfoStorage.ts: -------------------------------------------------------------------------------- 1 | import { type IProductInfo } from './IProductInfo.js' 2 | 3 | interface IProductInfoStorage extends IProductInfo { 4 | createdBy: string 5 | permalink: string 6 | } 7 | 8 | export type { IProductInfoStorage } 9 | -------------------------------------------------------------------------------- /src/types/IReportingInfo.ts: -------------------------------------------------------------------------------- 1 | interface IReportingInfo { 2 | title: string 3 | observed: Date 4 | proofOfIncident: string 5 | description: string 6 | stake: string 7 | } 8 | 9 | interface IDisputeInfo { 10 | title: string 11 | proofOfDispute: string 12 | description: string 13 | stake: string 14 | } 15 | 16 | export type { IDisputeInfo, IReportingInfo } 17 | -------------------------------------------------------------------------------- /src/types/IReportingInfoStorage.ts: -------------------------------------------------------------------------------- 1 | import { 2 | type IDisputeInfo, 3 | type IReportingInfo 4 | } from './IReportingInfo.js' 5 | 6 | interface IReportingInfoStorage extends IReportingInfo { 7 | createdBy: string 8 | permalink: string 9 | } 10 | 11 | interface IDisputeInfoStorage extends IDisputeInfo { 12 | createdBy: string 13 | permalink: string 14 | } 15 | 16 | export type { IDisputeInfoStorage, IReportingInfoStorage } 17 | -------------------------------------------------------------------------------- /src/types/IStoreCandidate.ts: -------------------------------------------------------------------------------- 1 | interface IStoreCandidate { 2 | key?: string[] 3 | signature?: string[] 4 | returns: string 5 | property: string 6 | compute?: ((result: any) => any) 7 | args?: string[] 8 | fn?: string 9 | } 10 | 11 | export type { IStoreCandidate } 12 | -------------------------------------------------------------------------------- /src/types/IToken.ts: -------------------------------------------------------------------------------- 1 | import { type ChainId } from './ChainId.js' 2 | 3 | interface IToken { 4 | chainId: ChainId 5 | at: string 6 | name: string 7 | symbol: string 8 | } 9 | 10 | export type { IToken } 11 | -------------------------------------------------------------------------------- /src/types/IWrappedResult.ts: -------------------------------------------------------------------------------- 1 | import { type Status } from './Status.js' 2 | 3 | interface IWrappedResult { 4 | status: Status 5 | result: any 6 | error?: Error 7 | } 8 | 9 | export type { IWrappedResult } 10 | -------------------------------------------------------------------------------- /src/types/PolicyDuration.ts: -------------------------------------------------------------------------------- 1 | type PolicyDuration = 1 | 2 | 3 2 | 3 | export type { PolicyDuration } 4 | -------------------------------------------------------------------------------- /src/types/SDKInternalStorage.ts: -------------------------------------------------------------------------------- 1 | import { type ChainId } from './ChainId.js' 2 | 3 | interface SDKInternalStorage { 4 | initialized: boolean 5 | store?: { 6 | [key in ChainId]?: string 7 | } 8 | } 9 | 10 | export type { SDKInternalStorage } 11 | -------------------------------------------------------------------------------- /src/types/Status.ts: -------------------------------------------------------------------------------- 1 | enum Status { 2 | SUCCESS = 'Success', 3 | FAILURE = 'Failure', 4 | EXCEPTION = 'Exception' 5 | } 6 | 7 | export { Status } 8 | -------------------------------------------------------------------------------- /src/types/index.ts: -------------------------------------------------------------------------------- 1 | import { ChainId } from './ChainId.js' 2 | import { CoverStatus } from './CoverStatus.js' 3 | import * as exceptions from './Exceptions/index.js' 4 | import { type IApproveTransactionArgs } from './IApproveTransactionArgs.js' 5 | import { type ICoverInfo } from './ICoverInfo.js' 6 | import { type ICoverInfoStorage } from './ICoverInfoStorage.js' 7 | import { type INetwork } from './INetwork.js' 8 | import { type IPolicyFeeArgs } from './IPolicyFeeArgs.js' 9 | import { type IProductInfo } from './IProductInfo.js' 10 | import { type IProductInfoStorage } from './IProductInfoStorage.js' 11 | import { type IReportingInfo } from './IReportingInfo.js' 12 | import { type IReportingInfoStorage } from './IReportingInfoStorage.js' 13 | import { type IStoreCandidate } from './IStoreCandidate.js' 14 | import { type IToken } from './IToken.js' 15 | import { type IWrappedResult } from './IWrappedResult.js' 16 | import { type PolicyDuration } from './PolicyDuration.js' 17 | import { type SDKInternalStorage } from './SDKInternalStorage.js' 18 | import { Status } from './Status.js' 19 | 20 | export { 21 | ChainId, 22 | CoverStatus, 23 | exceptions, 24 | type IApproveTransactionArgs, 25 | type ICoverInfo, 26 | type ICoverInfoStorage, 27 | type INetwork, 28 | type IPolicyFeeArgs, 29 | type IProductInfo, 30 | type IProductInfoStorage, 31 | type IReportingInfo, 32 | type IReportingInfoStorage, 33 | type IStoreCandidate, 34 | type IToken, 35 | type IWrappedResult, 36 | type PolicyDuration, 37 | type SDKInternalStorage, 38 | Status 39 | } 40 | -------------------------------------------------------------------------------- /src/utils/contract.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { Contract } from '@ethersproject/contracts' 3 | import { type Provider } from '@ethersproject/providers' 4 | 5 | const getContract = (address: string, abi: any[], signerOrProvider: Provider | Signer): Contract => { 6 | return new Contract(address, abi, signerOrProvider) 7 | } 8 | 9 | export { getContract } 10 | -------------------------------------------------------------------------------- /src/utils/date.ts: -------------------------------------------------------------------------------- 1 | const getMonthEndDate = (x: Date): Date => new Date(Date.UTC(x.getFullYear(), x.getMonth() + 1, 0, 23, 59, 59)) 2 | 3 | const getExpiryDate = (coverDuration: number, policyDate: Date = new Date()): number => { 4 | // Get the day of the month 5 | const day = policyDate.getUTCDate() 6 | 7 | let monthToAdd = coverDuration - 1 8 | 9 | // Jump to the next month 10 | day >= 25 && monthToAdd++ 11 | 12 | // Obtain next timestamp 13 | const next = monthToAdd === 0 ? policyDate : new Date(policyDate.setMonth(policyDate.getMonth() + monthToAdd)) 14 | 15 | // Get the month end date of the supplied date 16 | const ts = getMonthEndDate(next).getTime() 17 | 18 | // Convert the month end date to unix timestamp 19 | return Math.floor(ts / 1000) 20 | } 21 | 22 | export { getExpiryDate } 23 | -------------------------------------------------------------------------------- /src/utils/erc20-utils.ts: -------------------------------------------------------------------------------- 1 | import { MaxUint256 } from '@ethersproject/constants' 2 | 3 | const getApprovalAmount = (x: any): string => (x !== null && x !== undefined && parseFloat(x.amount) > 0) ? x.amount : MaxUint256 4 | 5 | export { getApprovalAmount } 6 | -------------------------------------------------------------------------------- /src/utils/index.ts: -------------------------------------------------------------------------------- 1 | import * as contract from './contract.js' 2 | import * as date from './date.js' 3 | import * as erc20Utils from './erc20-utils.js' 4 | import * as ipfs from './ipfs.js' 5 | import * as keyUtil from './key-util.js' 6 | import * as numbers from './numbers.js' 7 | import * as pricing from './pricing/index.js' 8 | import * as signer from './signer.js' 9 | import * as store from './store.js' 10 | import * as uniswapV2 from './uniswap-v2/index.js' 11 | 12 | export { 13 | contract, 14 | date, 15 | erc20Utils, 16 | ipfs, 17 | keyUtil, 18 | numbers, 19 | pricing, 20 | signer, 21 | store, 22 | uniswapV2 23 | } 24 | -------------------------------------------------------------------------------- /src/utils/ipfs.ts: -------------------------------------------------------------------------------- 1 | import { IPFSClient } from '../net/index.js' 2 | 3 | const fallbackNodes = ['https://api.thegraph.com/ipfs'] 4 | 5 | const write = async (contents: Record, nodeUrls?: string[]): Promise => { 6 | const formatted = JSON.stringify(contents, null, 2) 7 | 8 | const nodes = typeof nodeUrls !== 'undefined' ? nodeUrls : fallbackNodes 9 | const client = new IPFSClient(nodes) 10 | 11 | const hash = await client.addString(formatted) 12 | 13 | if (hash === undefined) { 14 | return undefined 15 | } 16 | 17 | return hash 18 | } 19 | 20 | const read = async (key: string, nodeUrls?: string[]): Promise | undefined> => { 21 | const nodes = typeof nodeUrls !== 'undefined' ? nodeUrls : fallbackNodes 22 | const client = new IPFSClient(nodes) 23 | 24 | const raw = await client.getString(key) 25 | 26 | if (raw !== undefined) { 27 | return JSON.parse(raw) 28 | } 29 | 30 | return raw // which is undefined 31 | } 32 | 33 | export { read, write } 34 | -------------------------------------------------------------------------------- /src/utils/key-util.ts: -------------------------------------------------------------------------------- 1 | import { keccak256 as solidityKeccak256 } from '@ethersproject/solidity' 2 | import { formatBytes32String } from '@ethersproject/strings' 3 | 4 | const encodeKey = (x: string): string => solidityKeccak256(['bytes32'], [x]) 5 | const encodeKeys = (x: string[], y: string[]): string => solidityKeccak256(x, y) 6 | const toBytes32 = (x: string): string => formatBytes32String(x) 7 | const getCoverContractKey = (namespace: string, coverKey: string): string => encodeKeys(['bytes32', 'bytes32'], [namespace, coverKey]) 8 | const qualifyBytes32 = (k: string): string => encodeKeys(['bytes32', 'bytes32'], [PROTOCOL.NS.CONTRACTS, k]) 9 | const qualify = (k: string): string => encodeKeys(['bytes32', 'address'], [PROTOCOL.NS.CONTRACTS, k]) 10 | const qualifyMember = (k: string): string => encodeKeys(['bytes32', 'address'], [PROTOCOL.NS.MEMBERS, k]) 11 | 12 | const ACCESS_CONTROL = { 13 | ADMIN: toBytes32(''), 14 | COVER_MANAGER: toBytes32('role:cover:manager'), 15 | LIQUIDITY_MANAGER: toBytes32('role:liquidity:manager'), 16 | GOVERNANCE_AGENT: toBytes32('role:governance:agent'), 17 | GOVERNANCE_ADMIN: toBytes32('role:governance:admin'), 18 | UPGRADE_AGENT: toBytes32('role:upgrade:agent'), 19 | RECOVERY_AGENT: toBytes32('role:recovery:agent'), 20 | PAUSE_AGENT: toBytes32('role:pause:agent'), 21 | UNPAUSE_AGENT: toBytes32('role:unpause:agent') 22 | } 23 | 24 | const BOND = { 25 | TO_CLAIM: toBytes32('ns:pool:bond:to:claim'), 26 | CONTRIBUTION: toBytes32('ns:pool:bond:contribution'), 27 | LP_TOKEN: toBytes32('ns:pool:bond:lq:pair:token'), 28 | DISCOUNT_RATE: toBytes32('ns:pool:bond:discount'), 29 | MAX_UNIT: toBytes32('ns:pool:bond:max:unit'), 30 | VESTING_TERM: toBytes32('ns:pool:bond:vesting:term'), 31 | UNLOCK_DATE: toBytes32('ns:pool:bond:unlock:date'), 32 | TOTAL_NPM_ALLOCATED: toBytes32('ns:pool:bond:total:npm:alloc'), 33 | TOTAL_NPM_DISTRIBUTED: toBytes32('ns:pool:bond:total:npm:distrib') 34 | } 35 | 36 | const PROTOCOL = { 37 | CNS: { 38 | CORE: toBytes32('cns:core'), 39 | NPM: toBytes32('cns:core:npm:instance'), 40 | COVER: toBytes32('cns:cover'), 41 | UNISWAP_V2_ROUTER: toBytes32('cns:core:uni:v2:router'), 42 | UNISWAP_V2_FACTORY: toBytes32('cns:core:uni:v2:factory'), 43 | PRICE_DISCOVERY: toBytes32('cns:core:price:discovery'), 44 | TREASURY: toBytes32('cns:core:treasury'), 45 | NPM_PRICE_ORACLE: toBytes32('cns:core:npm:price:oracle'), 46 | COVER_REASSURANCE: toBytes32('cns:cover:reassurance'), 47 | POOL_BOND: toBytes32('cns:pool:bond'), 48 | COVER_POLICY: toBytes32('cns:cover:policy'), 49 | COVER_POLICY_MANAGER: toBytes32('cns:cover:policy:manager'), 50 | COVER_POLICY_ADMIN: toBytes32('cns:cover:policy:admin'), 51 | COVER_STAKE: toBytes32('cns:cover:stake'), 52 | COVER_VAULT: toBytes32('cns:cover:vault'), 53 | COVER_VAULT_DELEGATE: toBytes32('cns:cover:vault:delegate'), 54 | COVER_STABLECOIN: toBytes32('cns:cover:sc'), 55 | COVER_CXTOKEN_FACTORY: toBytes32('cns:cover:cxtoken:factory'), 56 | COVER_VAULT_FACTORY: toBytes32('cns:cover:vault:factory'), 57 | BOND_POOL: toBytes32('cns:pools:bond'), 58 | STAKING_POOL: toBytes32('cns:pools:staking'), 59 | LIQUIDITY_ENGINE: toBytes32('cns:liquidity:engine'), 60 | STRATEGY_AAVE: toBytes32('cns:strategy:aave'), 61 | STRATEGY_COMPOUND: toBytes32('cns:strategy:compound'), 62 | GOVERNANCE: toBytes32('cns:gov'), 63 | GOVERNANCE_RESOLUTION: toBytes32('cns:gov:resolution'), 64 | CLAIM_PROCESSOR: toBytes32('cns:claim:processor'), 65 | BURNER: toBytes32('cns:core:burner') 66 | }, 67 | NS: { 68 | MEMBERS: toBytes32('ns:members'), 69 | CONTRACTS: toBytes32('ns:contracts'), 70 | COVER: toBytes32('ns:cover'), 71 | COVER_PRODUCT: toBytes32('ns:cover:product'), 72 | COVER_PRODUCT_EFFICIENCY: toBytes32('ns:cover:product:efficiency'), 73 | COVER_CREATION_DATE: toBytes32('ns:cover:creation:date'), 74 | COVER_CREATION_FEE: toBytes32('ns:cover:creation:fee'), 75 | COVER_CREATION_MIN_STAKE: toBytes32('ns:cover:creation:min:stake'), 76 | COVER_REASSURANCE: toBytes32('ns:cover:reassurance'), 77 | COVER_REASSURANCE_PAYOUT: toBytes32('ns:cover:reassurance:payout'), 78 | COVER_REASSURANCE_WEIGHT: toBytes32('ns:cover:reassurance:weight'), 79 | COVER_REASSURANCE_RATE: toBytes32('ns:cover:reassurance:rate'), 80 | COVER_LEVERAGE_FACTOR: toBytes32('ns:cover:leverage:factor'), 81 | COVER_CREATION_FEE_EARNING: toBytes32('ns:cover:creation:fee:earning'), 82 | COVER_INFO: toBytes32('ns:cover:info'), 83 | COVER_OWNER: toBytes32('ns:cover:owner'), 84 | COVER_SUPPORTS_PRODUCTS: toBytes32('ns:cover:supports:products'), 85 | VAULT_STRATEGY_OUT: toBytes32('ns:vault:strategy:out'), 86 | VAULT_LENDING_INCOMES: toBytes32('ns:vault:lending:incomes'), 87 | VAULT_LENDING_LOSSES: toBytes32('ns:vault:lending:losses'), 88 | VAULT_DEPOSIT_HEIGHTS: toBytes32('ns:vault:deposit:heights'), 89 | COVER_LIQUIDITY_LENDING_PERIOD: toBytes32('ns:cover:liquidity:len:p'), 90 | COVER_LIQUIDITY_MAX_LENDING_RATIO: toBytes32('ns:cover:liquidity:max:lr'), 91 | COVER_LIQUIDITY_WITHDRAWAL_WINDOW: toBytes32('ns:cover:liquidity:ww'), 92 | COVER_LIQUIDITY_MIN_STAKE: toBytes32('ns:cover:liquidity:min:stake'), 93 | COVER_LIQUIDITY_STAKE: toBytes32('ns:cover:liquidity:stake'), 94 | COVER_LIQUIDITY_COMMITTED: toBytes32('ns:cover:liquidity:committed'), 95 | COVER_STABLECOIN_NAME: toBytes32('ns:cover:stablecoin:name'), 96 | COVER_REQUIRES_WHITELIST: toBytes32('ns:cover:requires:whitelist'), 97 | COVER_HAS_FLASH_LOAN: toBytes32('ns:cover:has:fl'), 98 | COVER_LIQUIDITY_FLASH_LOAN_FEE: toBytes32('ns:cover:liquidity:fl:fee'), 99 | COVER_LIQUIDITY_FLASH_LOAN_FEE_PROTOCOL: toBytes32('ns:proto:cover:liquidity:fl:fee'), 100 | COVERAGE_LAG: toBytes32('ns:coverage:lag'), 101 | COVER_POLICY_RATE_FLOOR: toBytes32('ns:cover:policy:rate:floor'), 102 | COVER_POLICY_RATE_CEILING: toBytes32('ns:cover:policy:rate:ceiling'), 103 | POLICY_DISABLED: toBytes32('ns:policy:disabled'), 104 | POLICY_LAST_PURCHASE_ID: toBytes32('ns:policy:last:purchase:id'), 105 | COVER_STAKE: toBytes32('ns:cover:stake'), 106 | COVER_STAKE_OWNED: toBytes32('ns:cover:stake:owned'), 107 | COVER_STATUS: toBytes32('ns:cover:status'), 108 | COVER_CXTOKEN: toBytes32('ns:cover:cxtoken'), 109 | VAULT_TOKEN_NAME: toBytes32('ns:vault:token:name'), 110 | VAULT_TOKEN_SYMBOL: toBytes32('ns:vault:token:symbol'), 111 | COVER_CREATOR_WHITELIST: toBytes32('ns:cover:creator:whitelist'), 112 | COVER_USER_WHITELIST: toBytes32('ns:cover:user:whitelist'), 113 | COVER_CLAIM_BLACKLIST: toBytes32('ns:cover:claim:blacklist'), 114 | GOVERNANCE_RESOLUTION_TS: toBytes32('ns:gov:resolution:ts'), 115 | GOVERNANCE_UNSTAKEN: toBytes32('ns:gov:unstaken'), 116 | GOVERNANCE_UNSTAKE_TS: toBytes32('ns:gov:unstake:ts'), 117 | GOVERNANCE_UNSTAKE_REWARD: toBytes32('ns:gov:unstake:reward'), 118 | GOVERNANCE_UNSTAKE_BURNED: toBytes32('ns:gov:unstake:burned'), 119 | GOVERNANCE_UNSTAKE_REPORTER_FEE: toBytes32('ns:gov:unstake:rep:fee'), 120 | GOVERNANCE_REPORTING_MIN_FIRST_STAKE: toBytes32('ns:gov:rep:min:first:stake'), 121 | GOVERNANCE_REPORTING_INCIDENT_DATE: toBytes32('ns:gov:rep:incident:date'), 122 | GOVERNANCE_REPORTING_PERIOD: toBytes32('ns:gov:rep:period'), 123 | GOVERNANCE_REPORTING_WITNESS_YES: toBytes32('ns:gov:rep:witness:yes'), 124 | GOVERNANCE_REPORTING_HAS_A_DISPUTE: toBytes32('ns:gov:rep:has:dispute'), 125 | GOVERNANCE_REPORTING_FINALIZATION: toBytes32('ns:gov:rep:has:finalized'), 126 | GOVERNANCE_REPORTING_WITNESS_NO: toBytes32('ns:gov:rep:witness:no'), 127 | GOVERNANCE_REPORTING_STAKE_OWNED_YES: toBytes32('ns:gov:rep:stake:owned:yes'), 128 | GOVERNANCE_REPORTING_STAKE_OWNED_NO: toBytes32('ns:gov:rep:stake:owned:no'), 129 | GOVERNANCE_REPORTING_BURN_RATE: toBytes32('ns:gov:rep:burn:rate'), 130 | GOVERNANCE_REPORTER_COMMISSION: toBytes32('ns:gov:reporter:commission'), 131 | CLAIM_PERIOD: toBytes32('ns:claim:period'), 132 | CLAIM_PAYOUTS: toBytes32('ns:claim:payouts'), 133 | CLAIM_BEGIN_TS: toBytes32('ns:claim:begin:ts'), 134 | CLAIM_EXPIRY_TS: toBytes32('ns:claim:expiry:ts'), 135 | RESOLUTION_DEADLINE: toBytes32('ns:resolution:deadline'), 136 | RESOLUTION_COOL_DOWN_PERIOD: toBytes32('ns:resolution:cdp'), 137 | COVER_PLATFORM_FEE: toBytes32('ns:cover:platform:fee'), 138 | CLAIM_REPORTER_COMMISSION: toBytes32('ns:claim:reporter:commission'), 139 | LAST_LIQUIDITY_STATE_UPDATE: toBytes32('ns:last:snl:update'), 140 | LIQUIDITY_STATE_UPDATE_INTERVAL: toBytes32('ns:snl:update:interval'), 141 | LENDING_STRATEGY_ACTIVE: toBytes32('ns:lending:strategy:active'), 142 | LENDING_STRATEGY_DISABLED: toBytes32('ns:lending:strategy:disabled'), 143 | LENDING_STRATEGY_WITHDRAWAL_START: toBytes32('ns:lending:strategy:w:start'), 144 | ACCRUAL_INVOCATION: toBytes32('ns:accrual:invocation'), 145 | LENDING_STRATEGY_WITHDRAWAL_END: toBytes32('ns:lending:strategy:w:end') 146 | }, 147 | CNAME: { 148 | PROTOCOL: toBytes32('Neptune Mutual Protocol'), 149 | TREASURY: toBytes32('Treasury'), 150 | POLICY: toBytes32('Policy'), 151 | POLICY_ADMIN: toBytes32('Policy Admin'), 152 | BOND_POOL: toBytes32('BondPool'), 153 | STAKING_POOL: toBytes32('Staking Pool'), 154 | CLAIMS_PROCESSOR: toBytes32('Claims Processor'), 155 | COVER: toBytes32('Cover'), 156 | GOVERNANCE: toBytes32('Governance'), 157 | RESOLUTION: toBytes32('Resolution'), 158 | VAULT_FACTORY: toBytes32('Vault Factory'), 159 | CXTOKEN_FACTORY: toBytes32('cxToken Factory'), 160 | COVER_STAKE: toBytes32('Cover Stake'), 161 | COVER_REASSURANCE: toBytes32('Cover Reassurance'), 162 | LIQUIDITY_VAULT: toBytes32('Vault'), 163 | VAULT_DELEGATE: toBytes32('Vault Delegate'), 164 | LIQUIDITY_ENGINE: toBytes32('Liquidity Engine') 165 | } 166 | } 167 | 168 | const STAKING = { 169 | NAME: toBytes32('ns:pool:staking:name'), 170 | LOCKED: toBytes32('ns:pool:staking:locked'), 171 | LOCKUP_PERIOD_IN_BLOCKS: toBytes32('ns:pool:staking:lockup:period'), 172 | STAKING_TARGET: toBytes32('ns:pool:staking:target'), 173 | CUMULATIVE_STAKING_AMOUNT: toBytes32('ns:pool:staking:cum:amount'), 174 | STAKING_TOKEN: toBytes32('ns:pool:staking:token'), 175 | STAKING_TOKEN_UNI_STABLECOIN_PAIR: toBytes32('ns:pool:staking:token:uni:pair'), 176 | REWARD_TOKEN: toBytes32('ns:pool:reward:token'), 177 | REWARD_TOKEN_UNI_STABLECOIN_PAIR: toBytes32('ns:pool:reward:token:uni:pair'), 178 | STAKING_TOKEN_BALANCE: toBytes32('ns:pool:staking:token:balance'), 179 | REWARD_TOKEN_DEPOSITS: toBytes32('ns:pool:reward:token:deposits'), 180 | REWARD_TOKEN_DISTRIBUTION: toBytes32('ns:pool:reward:token:distrib'), 181 | MAX_STAKE: toBytes32('ns:pool:max:stake'), 182 | REWARD_PER_BLOCK: toBytes32('ns:pool:reward:per:block'), 183 | REWARD_PLATFORM_FEE: toBytes32('ns:pool:reward:platform:fee'), 184 | REWARD_TOKEN_BALANCE: toBytes32('ns:pool:reward:token:balance'), 185 | DEPOSIT_HEIGHTS: toBytes32('ns:pool:deposit:heights'), 186 | REWARD_HEIGHTS: toBytes32('ns:pool:reward:heights'), 187 | TOTAL_REWARD_GIVEN: toBytes32('ns:pool:reward:total:given') 188 | } 189 | 190 | export { 191 | ACCESS_CONTROL, 192 | BOND, 193 | encodeKey, 194 | encodeKeys, 195 | getCoverContractKey, 196 | PROTOCOL, 197 | qualify, 198 | qualifyBytes32, 199 | qualifyMember, 200 | STAKING, 201 | toBytes32 202 | } 203 | -------------------------------------------------------------------------------- /src/utils/local-storage.ts: -------------------------------------------------------------------------------- 1 | const localStorageAvailable = (): boolean => { 2 | try { 3 | const x = '__storage_test__' 4 | localStorage.setItem(x, x) 5 | localStorage.removeItem(x) 6 | return true 7 | } catch { 8 | // swallow all errors 9 | return false 10 | } 11 | } 12 | 13 | export { localStorageAvailable } 14 | -------------------------------------------------------------------------------- /src/utils/numbers.ts: -------------------------------------------------------------------------------- 1 | export const stringify = (x: number | string): string => x.toLocaleString('fullwide', { useGrouping: false }) 2 | -------------------------------------------------------------------------------- /src/utils/pricing/index.ts: -------------------------------------------------------------------------------- 1 | import * as lp from './lp.js' 2 | import * as pod from './pod.js' 3 | import * as token from './token.js' 4 | 5 | export { lp, pod, token } 6 | -------------------------------------------------------------------------------- /src/utils/pricing/lp.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Provider } from '@ethersproject/providers' 3 | 4 | import * as Stablecoin from '../../registry/Stablecoin.js' 5 | import { type ChainId } from '../../types/index.js' 6 | import { stringify } from '../numbers.js' 7 | import { 8 | getPairFromAddress, 9 | getPairInfo 10 | } from '../uniswap-v2/pair.js' 11 | 12 | const getPrice = async (chainId: ChainId, pairAddress: string, amount: number, signerOrProvider: Provider | Signer): Promise => { 13 | const pair = await getPairFromAddress(pairAddress, signerOrProvider) 14 | const [reserve0, reserve1, supply] = await getPairInfo(pair) 15 | const stablecoin = await Stablecoin.getAddress(chainId, signerOrProvider) 16 | const token0 = await pair.token0() 17 | 18 | const reserve = token0.toLowerCase() === stablecoin.toLowerCase() ? reserve0 : reserve1 19 | return reserve.mul('2').mul(stringify(amount)).div(supply) 20 | } 21 | 22 | export { 23 | getPairFromAddress, 24 | getPairInfo as getLastKnownPairInfoInternal, 25 | getPrice 26 | } 27 | -------------------------------------------------------------------------------- /src/utils/pricing/pod.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Provider } from '@ethersproject/providers' 3 | 4 | import * as Vault from '../../registry/Vault.js' 5 | import { stringify } from '../numbers.js' 6 | 7 | const getPrice = async (pod: string, amount: number, signerOrProvider: Provider | Signer): Promise => { 8 | const vault = await Vault.getInstanceByAddress(pod, signerOrProvider) 9 | 10 | return vault.calculateLiquidity(stringify(amount)) 11 | } 12 | 13 | export { getPrice } 14 | -------------------------------------------------------------------------------- /src/utils/pricing/token.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Provider } from '@ethersproject/providers' 3 | 4 | import * as IUniswapV2RouterLike from '../../registry/IUniswapV2RouterLike.js' 5 | import * as Stablecoin from '../../registry/Stablecoin.js' 6 | import { type ChainId } from '../../types/index.js' 7 | import { stringify } from '../numbers.js' 8 | import { getPairFromFactory } from '../uniswap-v2/pair.js' 9 | 10 | const getPrice = async (chainId: ChainId, token: string, amount: number, signerOrProvider: Provider | Signer): Promise => { 11 | const stablecoin = await Stablecoin.getAddress(chainId, signerOrProvider) 12 | 13 | if (token.toLowerCase() === stablecoin.toLowerCase()) { 14 | return stringify(amount) 15 | } 16 | 17 | const router = await IUniswapV2RouterLike.getInstance(chainId, signerOrProvider) 18 | const [stablecoinNeeded, _tokenNeeded] = await router.getAmountsIn(stringify(amount), [stablecoin, token]) // eslint-disable-line 19 | 20 | return stablecoinNeeded 21 | } 22 | 23 | const getPriceUsingPair = async (chainId: ChainId, token: string, amount: number, signerOrProvider: Provider | Signer): Promise => { 24 | const stablecoin = await Stablecoin.getAddress(chainId, signerOrProvider) 25 | const value = stringify(amount) 26 | 27 | if (token.toLowerCase() === stablecoin.toLowerCase()) { 28 | return value 29 | } 30 | 31 | const pair = await getPairFromFactory(chainId, token, stablecoin, signerOrProvider) 32 | const { reserve0, reserve1 } = await pair.getReserves() 33 | 34 | const token1 = await pair.token1() 35 | 36 | return token1.toLowerCase() === stablecoin.toLowerCase() ? reserve1.mul(value).div(reserve0) : reserve0.mul(value).div(reserve1) 37 | } 38 | 39 | export { getPrice, getPriceUsingPair } 40 | -------------------------------------------------------------------------------- /src/utils/signer.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Provider } from '@ethersproject/providers' 3 | 4 | const getAddress = async (signerOrProvider: Provider | Signer): Promise => { 5 | if (signerOrProvider === undefined) { 6 | return null 7 | } 8 | 9 | const signer = (signerOrProvider as Signer) 10 | 11 | // eslint-disable-next-line @typescript-eslint/return-await 12 | return signer.getAddress() 13 | } 14 | 15 | export { getAddress } 16 | -------------------------------------------------------------------------------- /src/utils/store.ts: -------------------------------------------------------------------------------- 1 | import { type Provider as EthersProvider } from '@ethersproject/providers' 2 | import { keccak256 as solidityKeccak256 } from '@ethersproject/solidity' 3 | 4 | import { 5 | abis, 6 | store 7 | } from '../config/index.js' 8 | import { ZERO_BYTES32 } from '../config/constants.js' 9 | import { 10 | Contract, 11 | Provider 12 | } from '../packages/ethers-multicall/src/index.js' 13 | import { 14 | type ChainId, 15 | type IStoreCandidate 16 | } from '../types/index.js' 17 | 18 | const getKey = (signature: string[] | undefined, ...items: string[]): string => { 19 | let types = signature 20 | 21 | if (items.length === 1) { 22 | return items[0] 23 | } 24 | 25 | if (types === undefined) { 26 | types = items.map(() => 'bytes32') 27 | } 28 | 29 | return solidityKeccak256(types, items) 30 | } 31 | 32 | const getFunc = (type: string): string => { 33 | switch (type) { 34 | case 'bool': 35 | return 'getBool' 36 | case 'string': 37 | return 'getString' 38 | case 'bytes32': 39 | return 'getBytes32' 40 | case 'address': 41 | return 'getAddress' 42 | case 'uint256': 43 | case 'uint': 44 | return 'getUint' 45 | default: 46 | throw new Error('Unsupported data type') 47 | } 48 | } 49 | 50 | const readStorage = async (chainId: ChainId, candidates: IStoreCandidate[], provider: EthersProvider): Promise => { 51 | const result: any = {} 52 | 53 | const ethcallProvider = new Provider(provider) 54 | await ethcallProvider.init() 55 | 56 | const storeContract = new Contract(store.getStoreAddressFromEnvironment(chainId), abis.IStore) 57 | const calls = [] 58 | 59 | for (const candidate of candidates) { 60 | const { returns, key, signature, fn, args } = candidate 61 | let k = ZERO_BYTES32 62 | let func = getFunc(returns) 63 | 64 | if (key !== undefined) { 65 | k = getKey(signature, ...key) 66 | } 67 | 68 | if (fn !== undefined) { 69 | func = fn 70 | } 71 | 72 | if (args !== undefined) { 73 | calls.push(storeContract[func](...args)) 74 | } else { 75 | calls.push(storeContract[func](k)) 76 | } 77 | } 78 | 79 | const members = await ethcallProvider.all(calls) 80 | 81 | for (const i of members.keys()) { 82 | const { property, compute } = candidates[i] 83 | let value = members[i] 84 | 85 | if (compute !== undefined) { 86 | value = await compute({ value, result }) 87 | } 88 | 89 | result[property] = value 90 | } 91 | 92 | return result 93 | } 94 | 95 | export { readStorage } 96 | -------------------------------------------------------------------------------- /src/utils/uniswap-v2/index.ts: -------------------------------------------------------------------------------- 1 | import * as pair from './pair.js' 2 | 3 | export { pair } 4 | -------------------------------------------------------------------------------- /src/utils/uniswap-v2/pair.ts: -------------------------------------------------------------------------------- 1 | import { type Signer } from '@ethersproject/abstract-signer' 2 | import { type Contract } from '@ethersproject/contracts' 3 | import { type Provider } from '@ethersproject/providers' 4 | 5 | import { 6 | IUniswapV2FactoryLike, 7 | IUniswapV2PairLike 8 | } from '../../registry/index.js' 9 | import { type ChainId } from '../../types/ChainId.js' 10 | 11 | const getPairFromAddress = async (pairAddress: string, signerOrProvider: Provider | Signer): Promise => { 12 | // eslint-disable-next-line 13 | return IUniswapV2PairLike.getInstance(pairAddress, signerOrProvider) 14 | } 15 | 16 | const getPairFromFactory = async (chainId: ChainId, token0: string, token1: string, signerOrProvider: Provider | Signer): Promise => { 17 | const factory = await IUniswapV2FactoryLike.getInstance(chainId, signerOrProvider) 18 | const pairAddress = await factory.getPair(token0, token1) 19 | 20 | // eslint-disable-next-line 21 | return getPairFromAddress(pairAddress, signerOrProvider) 22 | } 23 | 24 | const getPairInfo = async (pair: Contract): Promise => { 25 | const { reserve0, reserve1 } = await pair.getReserves() 26 | const supply = await pair.totalSupply() 27 | 28 | return [reserve0, reserve1, supply] 29 | } 30 | 31 | export { getPairFromAddress, getPairFromFactory, getPairInfo } 32 | -------------------------------------------------------------------------------- /tsconfig-base.json: -------------------------------------------------------------------------------- 1 | { 2 | // see https://www.typescriptlang.org/tsconfig to better understand tsconfigs 3 | "include": [ 4 | "src", 5 | "types" 6 | ], 7 | "compilerOptions": { 8 | "target": "esnext", 9 | "module": "NodeNext", 10 | "lib": [ 11 | "es2021", 12 | "dom", 13 | ], 14 | "importHelpers": true, 15 | "declaration": true, 16 | "sourceMap": true, 17 | "rootDir": "./src", 18 | "outDir": "dist", 19 | "strict": true, 20 | "noImplicitReturns": true, 21 | "noFallthroughCasesInSwitch": true, 22 | "noUnusedLocals": true, 23 | "noUnusedParameters": true, 24 | "moduleResolution": "node", 25 | "resolveJsonModule": true, 26 | "esModuleInterop": true, 27 | "skipLibCheck": true, 28 | "forceConsistentCasingInFileNames": true, 29 | } 30 | } -------------------------------------------------------------------------------- /tsconfig-cjs.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig-base.json", 3 | "compilerOptions": { 4 | "importHelpers": true, 5 | "module": "CommonJS", 6 | "outDir": "dist/cjs", 7 | "target": "es2015" 8 | } 9 | } -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig-base.json", 3 | "compilerOptions": { 4 | "module": "esnext", 5 | "outDir": "dist/mjs", 6 | "target": "esnext" 7 | } 8 | } --------------------------------------------------------------------------------