1
0
mirror of https://github.com/oceanprotocol/react.git synced 2025-02-14 21:10:38 +01:00

Merge branch 'main' into fix/publishFixes

This commit is contained in:
mihaisc 2020-09-16 15:05:33 +03:00
commit 397e455924
No known key found for this signature in database
GPG Key ID: BE522BB8C3A5E2E4
13 changed files with 1866 additions and 741 deletions

View File

@ -11,9 +11,14 @@
"plugin:prettier/recommended", "plugin:prettier/recommended",
"prettier/react", "prettier/react",
"prettier/standard", "prettier/standard",
"prettier/@typescript-eslint" "prettier/@typescript-eslint",
"plugin:react-hooks/recommended"
], ],
"plugins": ["@typescript-eslint", "prettier"], "plugins": ["@typescript-eslint", "prettier"],
"rules": {
"no-use-before-define": "off",
"@typescript-eslint/no-use-before-define": "error"
},
"env": { "es6": true, "node": true }, "env": { "es6": true, "node": true },
"settings": { "settings": {
"react": { "react": {

View File

@ -4,6 +4,16 @@ All notable changes to this project will be documented in this file. Dates are d
Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog).
#### [v0.0.44](https://github.com/oceanprotocol/react/compare/v0.0.43...v0.0.44)
> 16 September 2020
- Bump eslint from 7.8.1 to 7.9.0 [`#113`](https://github.com/oceanprotocol/react/pull/113)
- Bump @typescript-eslint/eslint-plugin from 4.0.1 to 4.1.0 [`#114`](https://github.com/oceanprotocol/react/pull/114)
- package updates, linting fixes [`e22212b`](https://github.com/oceanprotocol/react/commit/e22212bd016c930283f6bb6966693b2ca23a8b63)
- bump @oceanprotocol/lib [`dc48874`](https://github.com/oceanprotocol/react/commit/dc48874290a19adb1bb9dc620d7f1f6849a9a488)
- prepare strict type checking, bunch of typing fixes [`75b1adb`](https://github.com/oceanprotocol/react/commit/75b1adb699dd6f25bf59b4311c077c6aba5ee61e)
#### [v0.0.43](https://github.com/oceanprotocol/react/compare/v0.0.42...v0.0.43) #### [v0.0.43](https://github.com/oceanprotocol/react/compare/v0.0.42...v0.0.43)
> 10 September 2020 > 10 September 2020

2360
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{ {
"name": "@oceanprotocol/react", "name": "@oceanprotocol/react",
"version": "0.0.43", "version": "0.0.44",
"description": "React hooks & components on top of @oceanprotocol/lib", "description": "React hooks & components on top of @oceanprotocol/lib",
"main": "dist/index.js", "main": "dist/index.js",
"umd:main": "dist/index.umd.js", "umd:main": "dist/index.umd.js",
@ -25,26 +25,28 @@
"dist/" "dist/"
], ],
"dependencies": { "dependencies": {
"@oceanprotocol/lib": "^0.2.4", "@oceanprotocol/lib": "^0.2.5",
"axios": "^0.20.0", "axios": "^0.20.0",
"decimal.js": "^10.2.0", "decimal.js": "^10.2.0",
"web3": "^1.2.11", "web3": "^1.3.0",
"web3modal": "^1.9.0" "web3modal": "^1.9.0"
}, },
"devDependencies": { "devDependencies": {
"@release-it/bumper": "^2.0.0", "@release-it/bumper": "^2.0.0",
"@types/node-fetch": "^2.5.7",
"@types/react": "^16.9.49", "@types/react": "^16.9.49",
"@typescript-eslint/eslint-plugin": "^4.0.1", "@typescript-eslint/eslint-plugin": "^4.1.1",
"@typescript-eslint/parser": "^4.0.1", "@typescript-eslint/parser": "^4.1.1",
"auto-changelog": "^2.2.0", "auto-changelog": "^2.2.0",
"eslint": "^7.8.1", "eslint": "^7.9.0",
"eslint-config-oceanprotocol": "^1.5.0", "eslint-config-oceanprotocol": "^1.5.0",
"eslint-config-prettier": "^6.11.0", "eslint-config-prettier": "^6.11.0",
"eslint-plugin-prettier": "^3.1.4", "eslint-plugin-prettier": "^3.1.4",
"eslint-plugin-react": "^7.20.5", "eslint-plugin-react": "^7.20.6",
"eslint-plugin-react-hooks": "^4.1.2",
"microbundle": "^0.12.3", "microbundle": "^0.12.3",
"prettier": "^2.1.1", "prettier": "^2.1.2",
"release-it": "^14.0.2", "release-it": "^14.0.3",
"serialize-javascript": "^5.0.1", "serialize-javascript": "^5.0.1",
"typescript": "^4.0.2" "typescript": "^4.0.2"
}, },

View File

@ -1,4 +1,3 @@
import Web3 from 'web3'
import { HttpProvider } from 'web3-core' import { HttpProvider } from 'web3-core'
interface EthereumProvider extends HttpProvider { interface EthereumProvider extends HttpProvider {

View File

@ -37,7 +37,7 @@ function useConsume(): UseConsume {
} }
async function consume( async function consume(
did: string, did: DID | string,
dataTokenAddress: string, dataTokenAddress: string,
serviceType: ServiceType = 'access' serviceType: ServiceType = 'access'
): Promise<void> { ): Promise<void> {
@ -50,7 +50,11 @@ function useConsume(): UseConsume {
await checkAndBuyDT(ocean, dataTokenAddress, account, config) await checkAndBuyDT(ocean, dataTokenAddress, account, config)
setStep(1) setStep(1)
const order = await ocean.assets.order(did, serviceType, accountId) const order = await ocean.assets.order(
did as string,
serviceType,
accountId
)
Logger.log('order created', order) Logger.log('order created', order)
setStep(2) setStep(2)
const res = JSON.parse(order) const res = JSON.parse(order)
@ -65,7 +69,7 @@ function useConsume(): UseConsume {
Logger.log('token transfered', tokenTransfer) Logger.log('token transfered', tokenTransfer)
setStep(3) setStep(3)
await ocean.assets.download( await ocean.assets.download(
did, did as string,
(tokenTransfer as any).transactionHash, (tokenTransfer as any).transactionHash,
dataTokenAddress, dataTokenAddress,
account, account,

View File

@ -25,20 +25,20 @@ function useMetadata(asset?: DID | string | DDO): UseMetadata {
const [isLoaded, setIsLoaded] = useState(false) const [isLoaded, setIsLoaded] = useState(false)
const [price, setPrice] = useState<BestPrice | undefined>() const [price, setPrice] = useState<BestPrice | undefined>()
async function getDDO(did: DID | string): Promise<DDO> { async function getDDO(did: DID | string): Promise<DDO | null> {
if (status === ProviderStatus.CONNECTED) { if (status !== ProviderStatus.CONNECTED) return null
const ddo = await ocean.metadatastore.retrieveDDO(did) const ddo = await ocean.metadatastore.retrieveDDO(did)
return ddo return ddo
} }
}
async function getPrice(dataTokenAddress?: string): Promise<BestPrice> { async function getPrice(dataTokenAddress?: string): Promise<BestPrice> {
if (!dataTokenAddress) dataTokenAddress = internalDdo.dataToken if (!dataTokenAddress) dataTokenAddress = internalDdo.dataToken
return await getBestDataTokenPrice(ocean, dataTokenAddress, accountId) return await getBestDataTokenPrice(ocean, dataTokenAddress, accountId)
} }
async function getMetadata(): Promise<Metadata> { async function getMetadata(): Promise<Metadata | null> {
if (!internalDdo) return if (!internalDdo) return null
const metadata = internalDdo.findServiceByType('metadata') const metadata = internalDdo.findServiceByType('metadata')
return metadata.attributes return metadata.attributes
} }

View File

@ -1,5 +1,5 @@
export interface PriceOptions { export interface PriceOptions {
price?: number price: number
tokensToMint: number tokensToMint: number
type: 'fixed' | 'dynamic' | string type: 'fixed' | 'dynamic' | string
weightOnDataToken: string weightOnDataToken: string

View File

@ -17,7 +17,7 @@ interface UsePublish {
priceOptions: PriceOptions, priceOptions: PriceOptions,
serviceConfigs: ServiceType, serviceConfigs: ServiceType,
dataTokenOptions?: DataTokenOptions dataTokenOptions?: DataTokenOptions
) => Promise<DDO> ) => Promise<DDO | undefined | null>
mint: (tokenAddress: string, tokensToMint: string) => void mint: (tokenAddress: string, tokensToMint: string) => void
publishStep?: number publishStep?: number
publishStepText?: string publishStepText?: string
@ -32,9 +32,52 @@ function usePublish(): UsePublish {
const [publishStepText, setPublishStepText] = useState<string | undefined>() const [publishStepText, setPublishStepText] = useState<string | undefined>()
const [publishError, setPublishError] = useState<string | undefined>() const [publishError, setPublishError] = useState<string | undefined>()
function setStep(index: number) { function setStep(index?: number) {
setPublishStep(index) setPublishStep(index)
setPublishStepText(publishFeedback[index]) index && setPublishStepText(publishFeedback[index])
}
async function mint(tokenAddress: string, tokensToMint: string) {
Logger.log('mint function', tokenAddress, accountId)
await ocean.datatokens.mint(tokenAddress, accountId, tokensToMint)
}
async function createPricing(
priceOptions: PriceOptions,
dataTokenAddress: string,
mintedTokens: string
): Promise<void | null> {
switch (priceOptions.type) {
case 'dynamic': {
const pool = await ocean.pool.createDTPool(
accountId,
dataTokenAddress,
priceOptions.tokensToMint.toString(),
priceOptions.weightOnDataToken,
priceOptions.liquidityProviderFee
)
break
}
case 'fixed': {
if (!config.fixedRateExchangeAddress) {
Logger.error(`'fixedRateExchangeAddress' not set in ccnfig.`)
return null
}
const fixedPriceExchange = await ocean.fixedRateExchange.create(
dataTokenAddress,
priceOptions.price.toString(),
accountId
)
await ocean.datatokens.approve(
dataTokenAddress,
config.fixedRateExchangeAddress,
mintedTokens,
accountId
)
break
}
}
} }
/** /**
@ -50,10 +93,12 @@ function usePublish(): UsePublish {
priceOptions: PriceOptions, priceOptions: PriceOptions,
serviceType: ServiceType, serviceType: ServiceType,
dataTokenOptions?: DataTokenOptions dataTokenOptions?: DataTokenOptions
): Promise<DDO> { ): Promise<DDO | undefined | null> {
if (status !== ProviderStatus.CONNECTED || !ocean || !account) return if (status !== ProviderStatus.CONNECTED || !ocean || !account) return null
setIsLoading(true) setIsLoading(true)
setPublishError(undefined) setPublishError(undefined)
try { try {
const tokensToMint = priceOptions.tokensToMint.toString() const tokensToMint = priceOptions.tokensToMint.toString()
@ -109,7 +154,7 @@ function usePublish(): UsePublish {
const origComputePrivacy = { const origComputePrivacy = {
allowRawAlgorithm: true, allowRawAlgorithm: true,
allowNetworkAccess: false, allowNetworkAccess: false,
trustedAlgorithms: [] trustedAlgorithms: [] as any
} }
const computeService = ocean.compute.createComputeService( const computeService = ocean.compute.createComputeService(
account, account,
@ -146,50 +191,12 @@ function usePublish(): UsePublish {
} catch (error) { } catch (error) {
setPublishError(error.message) setPublishError(error.message)
Logger.error(error) Logger.error(error)
setStep(undefined) setStep()
} finally { } finally {
setIsLoading(false) setIsLoading(false)
} }
} }
async function createPricing(
priceOptions: PriceOptions,
dataTokenAddress: string,
mintedTokens: string
) {
switch (priceOptions.type) {
case 'dynamic': {
const pool = await ocean.pool.createDTPool(
accountId,
dataTokenAddress,
priceOptions.tokensToMint.toString(),
priceOptions.weightOnDataToken,
priceOptions.liquidityProviderFee
)
break
}
case 'fixed': {
const fixedPriceExchange = await ocean.fixedRateExchange.create(
dataTokenAddress,
priceOptions.price.toString(),
accountId
)
await ocean.datatokens.approve(
dataTokenAddress,
config.fixedRateExchangeAddress,
mintedTokens,
accountId
)
break
}
}
}
async function mint(tokenAddress: string, tokensToMint: string) {
Logger.log('mint function', tokenAddress, accountId)
await ocean.datatokens.mint(tokenAddress, accountId, tokensToMint)
}
return { return {
publish, publish,
mint, mint,

View File

@ -33,7 +33,7 @@ interface OceanProviderValue {
refreshBalance: () => Promise<void> refreshBalance: () => Promise<void>
} }
const OceanContext = createContext(null) const OceanContext = createContext({} as OceanProviderValue)
function OceanProvider({ function OceanProvider({
initialConfig, initialConfig,
@ -47,7 +47,7 @@ function OceanProvider({
const [web3, setWeb3] = useState<Web3 | undefined>() const [web3, setWeb3] = useState<Web3 | undefined>()
const [web3Provider, setWeb3Provider] = useState<any | undefined>() const [web3Provider, setWeb3Provider] = useState<any | undefined>()
const [ocean, setOcean] = useState<Ocean | undefined>() const [ocean, setOcean] = useState<Ocean | undefined>()
const [web3Modal, setWeb3Modal] = useState<Web3Modal>(null) const [web3Modal, setWeb3Modal] = useState<Web3Modal>()
const [chainId, setChainId] = useState<number | undefined>() const [chainId, setChainId] = useState<number | undefined>()
const [account, setAccount] = useState<Account | undefined>() const [account, setAccount] = useState<Account | undefined>()
const [accountId, setAccountId] = useState<string | undefined>() const [accountId, setAccountId] = useState<string | undefined>()
@ -75,24 +75,13 @@ function OceanProvider({
Logger.log('Web3Modal instance created.', web3ModalInstance) Logger.log('Web3Modal instance created.', web3ModalInstance)
} }
// On mount setup Web3Modal instance
useEffect(() => {
init()
}, [])
// Connect automatically to cached provider if present
useEffect(() => {
if (!web3Modal) return
web3Modal.cachedProvider && connect()
}, [web3Modal])
async function connect(newConfig?: Config) { async function connect(newConfig?: Config) {
try { try {
Logger.log('Connecting ...', newConfig) Logger.log('Connecting ...', newConfig)
newConfig && setConfig(newConfig) newConfig && setConfig(newConfig)
const provider = await web3Modal.connect() const provider = await web3Modal?.connect()
setWeb3Provider(provider) setWeb3Provider(provider)
const web3 = new Web3(provider) const web3 = new Web3(provider)
@ -125,13 +114,25 @@ function OceanProvider({
Logger.error(error) Logger.error(error)
} }
} }
// On mount setup Web3Modal instance
useEffect(() => {
init()
}, [])
// Connect automatically to cached provider if present
useEffect(() => {
if (!web3Modal) return
web3Modal.cachedProvider && connect()
}, [web3Modal])
async function refreshBalance() { async function refreshBalance() {
const balance = await getBalance(account) const balance = account && (await getBalance(account))
setBalance(balance) setBalance(balance)
} }
async function logout() { async function logout() {
// TODO: #67 check how is the proper way to logout // TODO: #67 check how is the proper way to logout
web3Modal.clearCachedProvider() web3Modal?.clearCachedProvider()
} }
const handleAccountsChanged = async (accounts: string[]) => { const handleAccountsChanged = async (accounts: string[]) => {

View File

@ -8,8 +8,8 @@ export async function getCheapestPool(
ocean: Ocean, ocean: Ocean,
accountId: string, accountId: string,
dataTokenAddress: string dataTokenAddress: string
): Promise<Pool> { ): Promise<Pool | null> {
if (!ocean || !accountId || !dataTokenAddress) return if (!ocean || !accountId || !dataTokenAddress) return null
const tokenPools = await ocean.pool.searchPoolforDT( const tokenPools = await ocean.pool.searchPoolforDT(
accountId, accountId,
@ -47,47 +47,16 @@ export async function getCheapestPool(
} }
} }
export async function getBestDataTokenPrice(
ocean: Ocean,
dataTokenAddress: string,
accountId: string
): Promise<BestPrice | undefined> {
const cheapestPool = await getCheapestPool(ocean, accountId, dataTokenAddress)
const cheapestExchange = await getCheapestExchange(ocean, dataTokenAddress)
Decimal.set({ precision: 5 })
const cheapestPoolPrice = new Decimal(
cheapestPool.price !== '' ? cheapestPool.price : 999999999999
)
const cheapestExchangePrice = new Decimal(
cheapestExchange.price !== '' ? cheapestExchange.price : 999999999999
)
if (cheapestPoolPrice < cheapestExchangePrice) {
return {
type: 'pool',
address: cheapestPool.address,
value: cheapestPool.price
} as BestPrice
} else {
return {
type: 'exchange',
address: cheapestExchange.address,
value: cheapestExchange.price
} as BestPrice
}
}
export async function getCheapestExchange( export async function getCheapestExchange(
ocean: Ocean, ocean: Ocean,
dataTokenAddress: string dataTokenAddress: string
) { ): Promise<{ address?: string; price: string } | null> {
if (!ocean || !dataTokenAddress) return if (!ocean || !dataTokenAddress) return
try { try {
const tokenExchanges = await ocean.fixedRateExchange.searchforDT( const tokenExchanges = await ocean.fixedRateExchange.searchforDT(
dataTokenAddress, dataTokenAddress,
'1' '1'
) )
if (tokenExchanges === undefined || tokenExchanges.length === 0) { if (tokenExchanges === undefined || tokenExchanges.length === 0) {
return { return {
address: '', address: '',
@ -121,6 +90,41 @@ export async function getCheapestExchange(
} }
} }
export async function getBestDataTokenPrice(
ocean: Ocean,
dataTokenAddress: string,
accountId: string
): Promise<BestPrice | undefined> {
const cheapestPool = await getCheapestPool(ocean, accountId, dataTokenAddress)
const cheapestExchange = await getCheapestExchange(ocean, dataTokenAddress)
Decimal.set({ precision: 5 })
const cheapestPoolPrice = new Decimal(
cheapestPool && cheapestPool.price !== ''
? cheapestPool.price
: 999999999999
)
const cheapestExchangePrice = new Decimal(
cheapestExchange && cheapestExchange?.price !== ''
? cheapestExchange.price
: 999999999999
)
if (cheapestPoolPrice < cheapestExchangePrice) {
return {
type: 'pool',
address: cheapestPool?.address,
value: cheapestPool?.price
} as BestPrice
} else {
return {
type: 'exchange',
address: cheapestExchange?.address,
value: cheapestExchange?.price
} as BestPrice
}
}
export async function checkAndBuyDT( export async function checkAndBuyDT(
ocean: Ocean, ocean: Ocean,
dataTokenAddress: string, dataTokenAddress: string,
@ -139,7 +143,7 @@ export async function checkAndBuyDT(
account.getId() account.getId()
) )
switch (bestPrice.type) { switch (bestPrice?.type) {
case 'pool': { case 'pool': {
const price = new Decimal(bestPrice.value).times(1.05).toString() const price = new Decimal(bestPrice.value).times(1.05).toString()
const maxPrice = new Decimal(bestPrice.value).times(2).toString() const maxPrice = new Decimal(bestPrice.value).times(2).toString()
@ -155,6 +159,16 @@ export async function checkAndBuyDT(
return buyResponse return buyResponse
} }
case 'exchange': { case 'exchange': {
if (!config.oceanTokenAddress) {
Logger.error(`'oceanTokenAddress' not set in config`)
return null
}
if (!config.fixedRateExchangeAddress) {
Logger.error(`'fixedRateExchangeAddress' not set in config`)
return null
}
Logger.log('Buying token from exchange', bestPrice, account.getId()) Logger.log('Buying token from exchange', bestPrice, account.getId())
await ocean.datatokens.approve( await ocean.datatokens.approve(
config.oceanTokenAddress, config.oceanTokenAddress,

View File

@ -14,7 +14,9 @@ export function readFileContent(file: File): Promise<string> {
}) })
} }
export function isDDO(toBeDetermined): toBeDetermined is DDO { export function isDDO(
toBeDetermined: DID | string | DDO
): toBeDetermined is DDO {
if ((toBeDetermined as DDO).id) { if ((toBeDetermined as DDO).id) {
return true return true
} }

View File

@ -10,9 +10,12 @@
"esModuleInterop": true, "esModuleInterop": true,
"sourceMap": true, "sourceMap": true,
"declaration": true, "declaration": true,
"strictNullChecks": false, "importHelpers": true,
"importHelpers": true
/* Strict Type-Checking */
// TODO: remove and adapt for `strictNullChecks`
"strict": true,
"strictNullChecks": false
}, },
"include": ["./src/@types", "./src/index.ts"], "include": ["./src/@types", "./src/index.ts"]
"exclude": ["node_modules", "dist", "example"]
} }