prepare strict type checking, bunch of typing fixes

This commit is contained in:
Matthias Kretschmann 2020-09-15 21:28:27 +02:00
parent 73a4662bd2
commit 75b1adb699
Signed by: m
GPG Key ID: 606EEEF3C479A91F
10 changed files with 94 additions and 40 deletions

23
package-lock.json generated
View File

@ -1740,6 +1740,29 @@
"resolved": "https://registry.npmjs.org/@types/node/-/node-12.12.54.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-12.12.54.tgz",
"integrity": "sha512-ge4xZ3vSBornVYlDnk7yZ0gK6ChHf/CHB7Gl1I0Jhah8DDnEQqBzgohYG4FX4p81TNirSETOiSyn+y1r9/IR6w==" "integrity": "sha512-ge4xZ3vSBornVYlDnk7yZ0gK6ChHf/CHB7Gl1I0Jhah8DDnEQqBzgohYG4FX4p81TNirSETOiSyn+y1r9/IR6w=="
}, },
"@types/node-fetch": {
"version": "2.5.7",
"resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.5.7.tgz",
"integrity": "sha512-o2WVNf5UhWRkxlf6eq+jMZDu7kjgpgJfl4xVNlvryc95O/6F2ld8ztKX+qu+Rjyet93WAWm5LjeX9H5FGkODvw==",
"dev": true,
"requires": {
"@types/node": "*",
"form-data": "^3.0.0"
},
"dependencies": {
"form-data": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.0.tgz",
"integrity": "sha512-CKMFDglpbMi6PyN+brwB9Q/GOw0eAnsrEZDgcsH5Krhz5Od/haKHAX0NmQfha2zPPz0JpWzA7GJHGSnvCRLWsg==",
"dev": true,
"requires": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"mime-types": "^2.1.12"
}
}
}
},
"@types/parse-json": { "@types/parse-json": {
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.0.tgz", "resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.0.tgz",

View File

@ -33,6 +33,7 @@
}, },
"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.0.1",
"@typescript-eslint/parser": "^4.0.1", "@typescript-eslint/parser": "^4.0.1",

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,11 +25,11 @@ 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)
return ddo const ddo = await ocean.metadatastore.retrieveDDO(did)
} return ddo
} }
async function getPrice(dataTokenAddress?: string): Promise<BestPrice> { async function getPrice(dataTokenAddress?: string): Promise<BestPrice> {
@ -37,8 +37,8 @@ function useMetadata(asset?: DID | string | DDO): UseMetadata {
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,9 @@ 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])
} }
/** /**
@ -50,10 +50,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 +111,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,7 +148,7 @@ 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)
} }
@ -156,7 +158,7 @@ function usePublish(): UsePublish {
priceOptions: PriceOptions, priceOptions: PriceOptions,
dataTokenAddress: string, dataTokenAddress: string,
mintedTokens: string mintedTokens: string
) { ): Promise<void | null> {
switch (priceOptions.type) { switch (priceOptions.type) {
case 'dynamic': { case 'dynamic': {
const pool = await ocean.pool.createDTPool( const pool = await ocean.pool.createDTPool(
@ -169,6 +171,11 @@ function usePublish(): UsePublish {
break break
} }
case 'fixed': { case 'fixed': {
if (!config.fixedRateExchangeAddress) {
Logger.error(`'fixedRateExchangeAddress' not set in ccnfig.`)
return null
}
const fixedPriceExchange = await ocean.fixedRateExchange.create( const fixedPriceExchange = await ocean.fixedRateExchange.create(
dataTokenAddress, dataTokenAddress,
priceOptions.price.toString(), priceOptions.price.toString(),

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>()
@ -92,7 +92,7 @@ function OceanProvider({
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)
@ -126,12 +126,12 @@ function OceanProvider({
} }
} }
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,
@ -57,31 +57,35 @@ export async function getBestDataTokenPrice(
Decimal.set({ precision: 5 }) Decimal.set({ precision: 5 })
const cheapestPoolPrice = new Decimal( const cheapestPoolPrice = new Decimal(
cheapestPool.price !== '' ? cheapestPool.price : 999999999999 cheapestPool && cheapestPool.price !== ''
? cheapestPool.price
: 999999999999
) )
const cheapestExchangePrice = new Decimal( const cheapestExchangePrice = new Decimal(
cheapestExchange.price !== '' ? cheapestExchange.price : 999999999999 cheapestExchange && cheapestExchange?.price !== ''
? cheapestExchange.price
: 999999999999
) )
if (cheapestPoolPrice < cheapestExchangePrice) { if (cheapestPoolPrice < cheapestExchangePrice) {
return { return {
type: 'pool', type: 'pool',
address: cheapestPool.address, address: cheapestPool?.address,
value: cheapestPool.price value: cheapestPool?.price
} as BestPrice } as BestPrice
} else { } else {
return { return {
type: 'exchange', type: 'exchange',
address: cheapestExchange.address, address: cheapestExchange?.address,
value: cheapestExchange.price value: cheapestExchange?.price
} as BestPrice } 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 null
const tokenExchanges = await ocean.fixedRateExchange.searchforDT( const tokenExchanges = await ocean.fixedRateExchange.searchforDT(
dataTokenAddress, dataTokenAddress,
@ -132,7 +136,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()
@ -148,6 +152,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"]
} }