diff --git a/package.json b/package.json index d5a12f68..18987c5b 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,7 @@ }, "dependencies": { "@babel/core": "^7.10.4", - "@kiltprotocol/sdk-js": "^0.19.1-2", + "@kiltprotocol/sdk-js": "^0.19.1-8", "@polkadot/ui-identicon": "^0.33.1", "@types/react-select": "^2.0.11", "@types/reselect": "^2.2.0", diff --git a/src/components/DevTools/DevTools.anticov.ts b/src/components/DevTools/DevTools.anticov.ts index 26f348ae..190f733a 100644 --- a/src/components/DevTools/DevTools.anticov.ts +++ b/src/components/DevTools/DevTools.anticov.ts @@ -1,4 +1,13 @@ -import * as sdk from '@kiltprotocol/sdk-js' +import Kilt, { + DelegationRootNode, + Identity, + BlockchainUtils, + DelegationNode, + MessageBody, + MessageBodyType, + Permission, + UUID, +} from '@kiltprotocol/sdk-js' import { IMetadata } from '@kiltprotocol/sdk-js/build/types/CTypeMetadata' import { ICTypeSchema } from '@kiltprotocol/sdk-js/build/types/CType' import BN from 'bn.js' @@ -18,21 +27,23 @@ import FeedbackService, { notifyFailure, } from '../../services/FeedbackService' -const ctype = sdk.CType.fromSchema(CTYPE.schema as ICTypeSchema) +const { IS_IN_BLOCK } = BlockchainUtils + +const ctype = Kilt.CType.fromSchema(CTYPE.schema as ICTypeSchema) const metadata: IMetadata = CTYPE_METADATA interface ISetup { - root: sdk.Identity - delegationRoot: sdk.DelegationRootNode + root: Identity + delegationRoot: DelegationRootNode } let cachedSetup: ISetup async function setup(): Promise { if (!cachedSetup) { - const root = await sdk.Identity.buildFromMnemonic(ROOT_SEED) + const root = await Identity.buildFromMnemonic(ROOT_SEED) - const delegationRoot = new sdk.DelegationRootNode( + const delegationRoot = new DelegationRootNode( DELEGATION_ROOT_ID, ctype.hash, root.address @@ -50,15 +61,15 @@ async function setup(): Promise { async function newDelegation(delegate: IMyIdentity): Promise { const { root, delegationRoot } = await setup() - const delegationNode = new sdk.DelegationNode( - sdk.UUID.generate(), + const delegationNode = new DelegationNode( + UUID.generate(), delegationRoot.id, delegate.identity.address, - [sdk.Permission.ATTEST] + [Permission.ATTEST] ) const signature = delegate.identity.signStr(delegationNode.generateHash()) const tx = await delegationNode.store(root, signature) - await sdk.Blockchain.submitSignedTx(tx) + await BlockchainUtils.submitSignedTx(tx, { resolveOn: IS_IN_BLOCK }) notifySuccess(`Delegation successfully created for ${delegate.metaData.name}`) await DelegationsService.importDelegation( delegationNode.id, @@ -66,8 +77,8 @@ async function newDelegation(delegate: IMyIdentity): Promise { false ) notifySuccess(`Delegation imported. Switch to Delegation Tab to see it.`) - const messageBody: sdk.MessageBody = { - type: sdk.MessageBodyType.INFORM_CREATE_DELEGATION, + const messageBody: MessageBody = { + type: MessageBodyType.INFORM_CREATE_DELEGATION, content: { delegationId: delegationNode.id, isPCR: false }, } await MessageRepository.sendToAddresses( @@ -80,26 +91,29 @@ async function verifyOrAddCtypeAndRoot(): Promise { const { root, delegationRoot } = await setup() if (!(await ctype.verifyStored())) { const tx = await ctype.store(root) - await sdk.Blockchain.submitSignedTx(tx) + await BlockchainUtils.submitSignedTx(tx, { resolveOn: IS_IN_BLOCK }) CTypeRepository.register({ cType: ctype, metaData: { metadata, ctypeHash: ctype.hash }, }) notifySuccess(`CTYPE ${metadata.title.default} successfully created.`) } - // delegationRoot.verify() is unreliable when using the currently released mashnet-node & sdk - // workaround is checking the ctype hash of the query result; it is 0x000... if it doesn't exist on chain - const queriedRoot = await sdk.DelegationRootNode.query(delegationRoot.id) + // delegationRoot.verify() is unreliable when using the currently released mashnet-node & // workaround is checking the ctype hash of the query result; it is 0x000... if it doesn't exist on chain + const queriedRoot = await DelegationRootNode.query(delegationRoot.id) if (queriedRoot?.cTypeHash !== ctype.hash) { const tx = await delegationRoot.store(root) - await sdk.Blockchain.submitSignedTx(tx) - const messageBody: sdk.MessageBody = { - type: sdk.MessageBodyType.INFORM_CREATE_DELEGATION, + await BlockchainUtils.submitSignedTx(tx, { resolveOn: IS_IN_BLOCK }) + const messageBody: MessageBody = { + type: MessageBodyType.INFORM_CREATE_DELEGATION, content: { delegationId: delegationRoot.id, isPCR: false }, } notifySuccess(`AntiCov Delegation Root successfully created.`) // sending root owner message for importing the root - const message = new sdk.Message(messageBody, root, root.getPublicIdentity()) + const message = new Kilt.Message( + messageBody, + root, + root.getPublicIdentity() + ) await MessageRepository.dispatchMessage(message) notifySuccess(`Sent Delegation Root to AntiCov root authority.`) } diff --git a/src/components/DevTools/DevTools.ctypes.tsx b/src/components/DevTools/DevTools.ctypes.tsx index 4d890239..f9d0c0a2 100644 --- a/src/components/DevTools/DevTools.ctypes.tsx +++ b/src/components/DevTools/DevTools.ctypes.tsx @@ -1,6 +1,10 @@ -import * as sdk from '@kiltprotocol/sdk-js' - -import { ERROR_CTYPE_ALREADY_EXISTS } from '@kiltprotocol/sdk-js' +import Kilt, { + CType, + ICType, + ICTypeMetadata, + ERROR_CTYPE_ALREADY_EXISTS, + BlockchainUtils, +} from '@kiltprotocol/sdk-js' import CTypeRepository from '../../services/CtypeRepository' import errorService from '../../services/ErrorService' import { notifySuccess, notifyError } from '../../services/FeedbackService' @@ -11,9 +15,9 @@ import cTypesPool from './data/cTypes.json' type UpdateCallback = (bsCTypeKey: keyof BsCTypesPool) => void -interface IBsCTypesPoolElement extends sdk.ICType { +interface IBsCTypesPoolElement extends ICType { owner: string - metadata: sdk.ICTypeMetadata['metadata'] + metadata: ICTypeMetadata['metadata'] } export type BsCTypesPool = { @@ -27,12 +31,11 @@ class BsCType { // replace owner key with his address const ownerIdentity = (await BsIdentity.getByKey(bsCTypeData.owner)) .identity - const cType = sdk.CType.fromSchema( - bsCTypeData.schema, - ownerIdentity.address - ) + const cType = CType.fromSchema(bsCTypeData.schema, ownerIdentity.address) const tx = cType.store(ownerIdentity) - await sdk.Blockchain.submitSignedTx(await tx) + await BlockchainUtils.submitSignedTx(await tx, { + resolveOn: BlockchainUtils.IS_IN_BLOCK, + }) return tx .catch(error => { if (error === ERROR_CTYPE_ALREADY_EXISTS) { @@ -78,7 +81,7 @@ class BsCType { } public static async getByHash( - hash: sdk.ICType['hash'] + hash: ICType['hash'] ): Promise { const cType = await CTypeRepository.findByHash(hash) if (cType) { diff --git a/src/components/DevTools/DevTools.delegations.tsx b/src/components/DevTools/DevTools.delegations.tsx index 955fca46..32ab9c17 100644 --- a/src/components/DevTools/DevTools.delegations.tsx +++ b/src/components/DevTools/DevTools.delegations.tsx @@ -1,4 +1,14 @@ -import * as sdk from '@kiltprotocol/sdk-js' +import { + BlockchainUtils, + DelegationNode, + DelegationRootNode, + IInformCreateDelegation, + IRequestAcceptDelegation, + ISubmitAcceptDelegation, + MessageBodyType, + Permission, + UUID, +} from '@kiltprotocol/sdk-js' import ContactRepository from '../../services/ContactRepository' import DelegationsService from '../../services/DelegationsService' @@ -16,21 +26,21 @@ import pcrPool from './data/pcr.json' type UpdateCallback = (bsDelegationKey: keyof BsDelegationsPool) => void -type Permission = 'ATTEST' | 'DELEGATE' +type Permissions = 'ATTEST' | 'DELEGATE' type RootData = { ownerIdentity: IMyIdentity - rootDelegation: sdk.DelegationRootNode + rootDelegation: DelegationRootNode } type ParentData = { ownerIdentity: IMyIdentity - delegation: sdk.DelegationNode | sdk.DelegationRootNode + delegation: DelegationNode | DelegationRootNode metaData?: IMyDelegation['metaData'] } type DelegationDataForMessages = { - delegation: sdk.DelegationNode + delegation: DelegationNode isPCR: boolean ownerIdentity: IMyIdentity signature: string @@ -42,7 +52,7 @@ type BsDelegationsPoolElement = { children?: BsDelegationsPool cTypeKey?: keyof BsCTypesPool - permissions?: Permission[] + permissions?: Permissions[] } export type BsDelegationsPool = { @@ -76,16 +86,16 @@ class BsDelegation { } // creation - let newPermissions: sdk.Permission[] + let newPermissions: Permission[] if (isPCR) { - newPermissions = [sdk.Permission.ATTEST] + newPermissions = [Permission.ATTEST] } else { newPermissions = (permissions || []).map( - permission => sdk.Permission[permission] + permission => Permission[permission] ) } - const delegation = new sdk.DelegationNode( - sdk.UUID.generate(), + const delegation = new DelegationNode( + UUID.generate(), rootData.rootDelegation.id, ownerIdentity.identity.address, newPermissions, @@ -95,7 +105,9 @@ class BsDelegation { const signature = ownerIdentity.identity.signStr(delegation.generateHash()) const metaData = { alias } const tx = await DelegationsService.storeOnChain(delegation, signature) - await sdk.Blockchain.submitSignedTx(tx) + await BlockchainUtils.submitSignedTx(tx, { + resolveOn: BlockchainUtils.IS_IN_BLOCK, + }) DelegationsService.store({ cTypeHash: rootData.rootDelegation.cTypeHash, ...delegation, @@ -180,8 +192,8 @@ class BsDelegation { } // await creation - const rootDelegation = new sdk.DelegationRootNode( - sdk.UUID.generate(), + const rootDelegation = new DelegationRootNode( + UUID.generate(), cType.cType.hash, ownerIdentity.identity.address ) @@ -210,7 +222,7 @@ class BsDelegation { isPCR: boolean, withMessages: boolean, updateCallback?: UpdateCallback - ): Promise { + ): Promise { const pool = isPCR ? BsDelegation.pcrPool : BsDelegation.delegationsPool const bsDelegationKeys = Object.keys(pool) const requests = bsDelegationKeys.reduce( @@ -314,7 +326,7 @@ class BsDelegation { signature, } = delegationDataForMessages - const delegationData: sdk.IRequestAcceptDelegation['content']['delegationData'] = { + const delegationData: IRequestAcceptDelegation['content']['delegationData'] = { account: parentData.ownerIdentity.identity.address, id: delegation.id, isPCR, @@ -323,7 +335,7 @@ class BsDelegation { } // send invitation from inviter(parentIdentity) to invitee (ownerIdentity) - const requestAcceptDelegation: sdk.IRequestAcceptDelegation = { + const requestAcceptDelegation: IRequestAcceptDelegation = { content: { delegationData, metaData: parentData.metaData, @@ -333,7 +345,7 @@ class BsDelegation { ), }, }, - type: sdk.MessageBodyType.REQUEST_ACCEPT_DELEGATION, + type: MessageBodyType.REQUEST_ACCEPT_DELEGATION, } await MessageRepository.singleSend( requestAcceptDelegation, @@ -342,7 +354,7 @@ class BsDelegation { ) // send invitation acceptance back - const submitAcceptDelegation: sdk.ISubmitAcceptDelegation = { + const submitAcceptDelegation: ISubmitAcceptDelegation = { content: { delegationData, signatures: { @@ -350,7 +362,7 @@ class BsDelegation { inviter: requestAcceptDelegation.content.signatures.inviter, }, }, - type: sdk.MessageBodyType.SUBMIT_ACCEPT_DELEGATION, + type: MessageBodyType.SUBMIT_ACCEPT_DELEGATION, } await MessageRepository.singleSend( submitAcceptDelegation, @@ -359,12 +371,12 @@ class BsDelegation { ) // inform about delegation creation - const informCreateDelegation: sdk.IInformCreateDelegation = { + const informCreateDelegation: IInformCreateDelegation = { content: { delegationId: delegation.id, isPCR, }, - type: sdk.MessageBodyType.INFORM_CREATE_DELEGATION, + type: MessageBodyType.INFORM_CREATE_DELEGATION, } await MessageRepository.singleSend( informCreateDelegation, diff --git a/src/containers/CtypeCreate/CtypeCreate.tsx b/src/containers/CtypeCreate/CtypeCreate.tsx index b4c9ab53..e6921798 100644 --- a/src/containers/CtypeCreate/CtypeCreate.tsx +++ b/src/containers/CtypeCreate/CtypeCreate.tsx @@ -1,4 +1,4 @@ -import * as sdk from '@kiltprotocol/sdk-js' +import { BlockchainUtils, CType, ICTypeMetadata } from '@kiltprotocol/sdk-js' import React from 'react' import { connect, MapStateToProps } from 'react-redux' import { RouteComponentProps, withRouter } from 'react-router' @@ -73,8 +73,8 @@ class CTypeCreate extends React.Component { const { connected, isValid, cType: stateCtype } = this.state stateCtype.owner = selectedIdentity?.identity.address if (selectedIdentity && connected && isValid) { - let cType: sdk.CType - let metaData: sdk.ICTypeMetadata + let cType: CType + let metaData: ICTypeMetadata try { const inputICTypeWithMetadata = fromInputModel(stateCtype) ;({ cType, metaData } = inputICTypeWithMetadata) @@ -99,7 +99,9 @@ class CTypeCreate extends React.Component { } const tx = cType.store(selectedIdentity.identity) - await sdk.Blockchain.submitSignedTx(await tx) + await BlockchainUtils.submitSignedTx(await tx, { + resolveOn: BlockchainUtils.IS_IN_BLOCK, + }) tx.then(() => { blockUi.updateMessage( `CTYPE stored on blockchain,\nnow registering CTYPE` diff --git a/src/services/AttestationService.ts b/src/services/AttestationService.ts index d2c31954..b9a0bae0 100644 --- a/src/services/AttestationService.ts +++ b/src/services/AttestationService.ts @@ -1,10 +1,11 @@ -import Kilt, { - IRequestForAttestation, +import { + Attestation, AttestedClaim, + BlockchainUtils, IAttestation, IAttestedClaim, Identity, - Blockchain, + IRequestForAttestation, } from '@kiltprotocol/sdk-js' import { ClaimSelectionData } from '../components/SelectAttestedClaims/SelectAttestedClaims' @@ -15,6 +16,8 @@ import persistentStore from '../state/PersistentStore' import ErrorService from './ErrorService' import { notifySuccess, notifyError } from './FeedbackService' +const { IS_IN_BLOCK } = BlockchainUtils + class AttestationService { /** * Creates and stores an attestation for the given `claim` on the blockchain. @@ -32,12 +35,12 @@ class AttestationService { throw new Error('No identity selected') } - const attestation = Kilt.Attestation.fromRequestAndPublicIdentity( + const attestation = Attestation.fromRequestAndPublicIdentity( requestForAttestation, selectedIdentity.getPublicIdentity() ) - const attestedClaim = Kilt.AttestedClaim.fromRequestAndAttestation( + const attestedClaim = AttestedClaim.fromRequestAndAttestation( requestForAttestation, attestation ) @@ -47,7 +50,9 @@ class AttestationService { try { const tx = await attestation.store(selectedIdentity) - await Blockchain.submitSignedTx(tx) + await BlockchainUtils.submitSignedTx(tx, { + resolveOn: IS_IN_BLOCK, + }) } catch (error) { ErrorService.log({ error, @@ -63,7 +68,7 @@ class AttestationService { public static async revokeAttestation( iAttestation: IAttestation ): Promise { - const attestation = Kilt.Attestation.fromAttestation(iAttestation) + const attestation = Attestation.fromAttestation(iAttestation) const selectedIdentity = AttestationService.getIdentity() if (!selectedIdentity) { @@ -71,7 +76,7 @@ class AttestationService { } try { const tx = await attestation.revoke(selectedIdentity) - await Blockchain.submitSignedTx(tx) + await BlockchainUtils.submitSignedTx(tx, { resolveOn: IS_IN_BLOCK }) notifySuccess('Attestation successfully revoked') persistentStore.store.dispatch( Attestations.Store.revokeAttestation(attestation.claimHash) @@ -92,8 +97,10 @@ class AttestationService { ): Promise { const selectedIdentity = AttestationService.getIdentity() - const tx = Kilt.Attestation.revoke(claimHash, selectedIdentity) - await Blockchain.submitSignedTx(await tx) + const tx = Attestation.revoke(claimHash, selectedIdentity) + await BlockchainUtils.submitSignedTx(await tx, { + resolveOn: IS_IN_BLOCK, + }) return tx .then(() => { notifySuccess(`Attestation successfully revoked.`) @@ -101,7 +108,7 @@ class AttestationService { Attestations.Store.revokeAttestation(claimHash) ) }) - .catch(error => { + .catch((error: any) => { ErrorService.log({ error, message: `Could not revoke attestation.`, @@ -115,14 +122,14 @@ class AttestationService { public static async verifyAttestatedClaim( attestedClaim: IAttestedClaim ): Promise { - const initialisedAttestedClaim = Kilt.AttestedClaim.fromAttestedClaim( + const initialisedAttestedClaim = AttestedClaim.fromAttestedClaim( attestedClaim ) return initialisedAttestedClaim.verify() } public static verifyAttestation(attestation: IAttestation): Promise { - const initialisedAttestation = Kilt.Attestation.fromAttestation(attestation) + const initialisedAttestation = Attestation.fromAttestation(attestation) return initialisedAttestation.checkValidity() } @@ -164,7 +171,7 @@ class AttestationService { state.selectedAttestedClaims.forEach( (selectedAttestedClaim: IAttestedClaim) => { - const attClaim = Kilt.AttestedClaim.fromAttestedClaim( + const attClaim = AttestedClaim.fromAttestedClaim( selectedAttestedClaim ) diff --git a/src/services/BalanceUtilities.tsx b/src/services/BalanceUtilities.tsx index b54facae..4fc04115 100644 --- a/src/services/BalanceUtilities.tsx +++ b/src/services/BalanceUtilities.tsx @@ -1,4 +1,9 @@ -import * as sdk from '@kiltprotocol/sdk-js' +import { + Balance, + BalanceUtils, + BlockchainUtils, + PublicIdentity, +} from '@kiltprotocol/sdk-js' import BN from 'bn.js' import React from 'react' import { Store } from 'redux' @@ -12,10 +17,10 @@ import { IContact, IMyIdentity } from '../types/Contact' import { notify, notifySuccess, notifyFailure } from './FeedbackService' // any balance below this will we purged -const MIN_BALANCE = sdk.BalanceUtils.KILT_COIN.muln(1) +const MIN_BALANCE = BalanceUtils.KILT_COIN.muln(1) // initial endowment for automatically created accounts -const ENDOWMENT = sdk.BalanceUtils.KILT_COIN.muln(30) +const ENDOWMENT = BalanceUtils.KILT_COIN.muln(30) // TODO: do we need to do something upon deleting an identity? class BalanceUtilities { @@ -26,7 +31,7 @@ class BalanceUtilities { myIdentity.identity.address ) == null ) { - sdk.Balance.listenToBalanceChanges( + Balance.listenToBalanceChanges( myIdentity.identity.address, BalanceUtilities.listener ).then(() => { @@ -41,7 +46,7 @@ class BalanceUtilities { } public static async getMyBalance(identity: IMyIdentity): Promise { - const balance: BN = await sdk.Balance.getBalance(identity.identity.address) + const balance: BN = await Balance.getBalance(identity.identity.address) return balance } @@ -61,7 +66,7 @@ class BalanceUtilities { amount: BN, successCallback?: () => void ): void { - const transferAmount = sdk.BalanceUtils.asFemtoKilt(amount) + const transferAmount = BalanceUtils.asFemtoKilt(amount) notify(
Transfer of @@ -70,12 +75,12 @@ class BalanceUtilities { initiated.
) - sdk.Balance.makeTransfer( - myIdentity.identity, - receiverAddress, - transferAmount - ) - .then(tx => sdk.Blockchain.submitSignedTx(tx)) + Balance.makeTransfer(myIdentity.identity, receiverAddress, transferAmount) + .then(tx => + BlockchainUtils.submitSignedTx(tx, { + resolveOn: BlockchainUtils.IS_IN_BLOCK, + }) + ) .then(() => { notifySuccess(
@@ -111,7 +116,7 @@ class BalanceUtilities { } private static listener( - account: sdk.PublicIdentity['address'], + account: PublicIdentity['address'], balance: BN, change: BN ): void { diff --git a/src/services/ContactRepository.ts b/src/services/ContactRepository.ts index d8d297db..426ebb53 100644 --- a/src/services/ContactRepository.ts +++ b/src/services/ContactRepository.ts @@ -1,5 +1,4 @@ -import * as sdk from '@kiltprotocol/sdk-js' - +import { PublicIdentity } from '@kiltprotocol/sdk-js' import * as Contacts from '../state/ducks/Contacts' import * as Wallet from '../state/ducks/Wallet' import PersistentStore from '../state/PersistentStore' @@ -112,7 +111,7 @@ class ContactRepository { identifier: string, alias: string ): Promise { - const publicIdentity = await sdk.PublicIdentity.resolveFromDid( + const publicIdentity = await PublicIdentity.resolveFromDid( identifier.trim(), { resolve: (url: string) => { diff --git a/src/services/CtypeRepository.ts b/src/services/CtypeRepository.ts index 7a51cd19..877a968b 100644 --- a/src/services/CtypeRepository.ts +++ b/src/services/CtypeRepository.ts @@ -1,5 +1,4 @@ -import * as sdk from '@kiltprotocol/sdk-js' - +import { ICType } from '@kiltprotocol/sdk-js' import * as CTypes from '../state/ducks/CTypes' import PersistentStore from '../state/PersistentStore' import { ICTypeWithMetadata } from '../types/Ctype' @@ -11,7 +10,7 @@ import { BasePostParams } from './BaseRepository' class CTypeRepository { public static async findByHash( - hash: sdk.ICType['hash'] + hash: ICType['hash'] ): Promise { const storedCType = CTypes.getCType(PersistentStore.store.getState(), hash) diff --git a/src/services/DelegationsService.ts b/src/services/DelegationsService.ts index 6a1e8332..69769318 100644 --- a/src/services/DelegationsService.ts +++ b/src/services/DelegationsService.ts @@ -1,5 +1,14 @@ -import * as sdk from '@kiltprotocol/sdk-js' - +import { + BlockchainUtils, + DelegationBaseNode, + DelegationNode, + DelegationRootNode, + IDelegationBaseNode, + IDelegationNode, + IDelegationRootNode, + Identity, + SubmittableExtrinsic, +} from '@kiltprotocol/sdk-js' import { DelegationsTreeNode } from '../components/DelegationNode/DelegationNode' import { IMyDelegation } from '../state/ducks/Delegations' import * as Delegations from '../state/ducks/Delegations' @@ -8,13 +17,15 @@ import PersistentStore from '../state/PersistentStore' class DelegationsService { public static async storeRoot( - delegationRoot: sdk.DelegationRootNode, + delegationRoot: DelegationRootNode, alias: string, isPCR: boolean ): Promise { const tx = DelegationsService.storeRootOnChain(delegationRoot) - await sdk.Blockchain.submitSignedTx(await tx) + await BlockchainUtils.submitSignedTx(await tx, { + resolveOn: BlockchainUtils.IS_IN_BLOCK, + }) return tx.then(() => { const { account, cTypeHash, id } = delegationRoot @@ -33,10 +44,10 @@ class DelegationsService { } public static async storeOnChain( - delegation: sdk.DelegationNode, + delegation: DelegationNode, signature: string - ): Promise { - const selectedIdentity: sdk.Identity = Wallet.getSelectedIdentity( + ): Promise { + const selectedIdentity: Identity = Wallet.getSelectedIdentity( PersistentStore.store.getState() ).identity return delegation.store(selectedIdentity, signature) @@ -55,9 +66,9 @@ class DelegationsService { * @param delegationNodeId id of the intermediate node (non-root node) */ public static async lookupNodeById( - delegationNodeId: sdk.IDelegationBaseNode['id'] - ): Promise { - return sdk.DelegationNode.query(delegationNodeId) + delegationNodeId: IDelegationBaseNode['id'] + ): Promise { + return DelegationNode.query(delegationNodeId) } /** @@ -66,9 +77,9 @@ class DelegationsService { * @param rootNodeId id of the desired root node */ public static async lookupRootNodeById( - rootNodeId: sdk.IDelegationRootNode['id'] - ): Promise { - return sdk.DelegationRootNode.query(rootNodeId) + rootNodeId: IDelegationRootNode['id'] + ): Promise { + return DelegationRootNode.query(rootNodeId) } /** @@ -77,9 +88,9 @@ class DelegationsService { * @param delegationNodeId the id of the node to find the root node for */ public static async findRootNode( - delegationNodeId: sdk.IDelegationNode['id'] - ): Promise { - const node = await sdk.DelegationNode.query(delegationNodeId) + delegationNodeId: IDelegationNode['id'] + ): Promise { + const node = await DelegationNode.query(delegationNodeId) if (node) { return node.getRoot() } @@ -87,7 +98,7 @@ class DelegationsService { } public static async importDelegation( - delegationNodeId: sdk.IDelegationBaseNode['id'], + delegationNodeId: IDelegationBaseNode['id'], alias: string, isPCR?: boolean ): Promise { @@ -121,8 +132,8 @@ class DelegationsService { } public static async revoke( - node: sdk.DelegationBaseNode, - identity: sdk.Identity + node: DelegationBaseNode, + identity: Identity ): Promise { await node.revoke(identity) PersistentStore.store.dispatch( @@ -133,7 +144,7 @@ class DelegationsService { public static async resolveParent( currentNode: DelegationsTreeNode ): Promise { - const parentDelegation: sdk.IDelegationBaseNode | null = await currentNode.delegation.getParent() + const parentDelegation: IDelegationBaseNode | null = await currentNode.delegation.getParent() if (!parentDelegation) { return currentNode @@ -145,9 +156,9 @@ class DelegationsService { } private static async storeRootOnChain( - delegation: sdk.DelegationRootNode - ): Promise { - const selectedIdentity: sdk.Identity = Wallet.getSelectedIdentity( + delegation: DelegationRootNode + ): Promise { + const selectedIdentity: Identity = Wallet.getSelectedIdentity( PersistentStore.store.getState() ).identity return delegation.store(selectedIdentity) diff --git a/src/services/DidService.ts b/src/services/DidService.ts index cc3130dc..48ed92f7 100644 --- a/src/services/DidService.ts +++ b/src/services/DidService.ts @@ -1,4 +1,11 @@ -import * as sdk from '@kiltprotocol/sdk-js' +import { + BlockchainUtils, + Did, + IDid, + IPublicIdentity, + IURLResolver, + PublicIdentity, +} from '@kiltprotocol/sdk-js' import { IDidDocumentSigned } from '@kiltprotocol/sdk-js/build/did/Did' import * as Wallet from '../state/ducks/Wallet' import persistentStore from '../state/PersistentStore' @@ -6,21 +13,23 @@ import { IContact, IMyIdentity } from '../types/Contact' import ContactRepository from './ContactRepository' import MessageRepository from './MessageRepository' +const { IS_IN_BLOCK } = BlockchainUtils + class DidService { public static readonly URL = `${window._env_.REACT_APP_SERVICE_HOST}/contacts/did` public static async resolveDid( identifier: string - ): Promise { - return sdk.PublicIdentity.resolveFromDid(identifier, this.URL_RESOLVER) + ): Promise { + return PublicIdentity.resolveFromDid(identifier, this.URL_RESOLVER) } - public static async createDid(myIdentity: IMyIdentity): Promise { - const documentStore: sdk.IDid['documentStore'] = `${ContactRepository.URL}/${myIdentity.identity.address}` + public static async createDid(myIdentity: IMyIdentity): Promise { + const documentStore: IDid['documentStore'] = `${ContactRepository.URL}/${myIdentity.identity.address}` - const did = sdk.Did.fromIdentity(myIdentity.identity, documentStore) + const did = Did.fromIdentity(myIdentity.identity, documentStore) const didDocument = did.createDefaultDidDocument(`${MessageRepository.URL}`) - const signedDidDocument: IDidDocumentSigned = sdk.Did.signDidDocument( + const signedDidDocument: IDidDocumentSigned = Did.signDidDocument( didDocument, myIdentity.identity ) @@ -34,7 +43,9 @@ class DidService { } as IContact) const tx = await did.store(myIdentity.identity) - const status = await sdk.Blockchain.submitSignedTx(tx) + const status = await BlockchainUtils.submitSignedTx(tx, { + resolveOn: IS_IN_BLOCK, + }) if (status.isError) { throw new Error( `Error creating DID for identity ${myIdentity.metaData.name}` @@ -50,8 +61,10 @@ class DidService { } public static async deleteDid(myIdentity: IMyIdentity): Promise { - const tx = await sdk.Did.remove(myIdentity.identity) - const status = await sdk.Blockchain.submitSignedTx(tx) + const tx = await Did.remove(myIdentity.identity) + const status = await BlockchainUtils.submitSignedTx(tx, { + resolveOn: IS_IN_BLOCK, + }) if (status.isError) { throw new Error( `Error deleting DID for identity ${myIdentity.metaData.name}` @@ -83,7 +96,7 @@ class DidService { .then(response => response.json()) .then(result => (typeof result === 'object' ? result : undefined)) }, - } as sdk.IURLResolver + } as IURLResolver } export default DidService diff --git a/src/services/MessageRepository.tsx b/src/services/MessageRepository.tsx index 18840a27..b126ae60 100644 --- a/src/services/MessageRepository.tsx +++ b/src/services/MessageRepository.tsx @@ -1,5 +1,19 @@ -import { ISubmitAttestationForClaim } from '@kiltprotocol/sdk-js' -import * as sdk from '@kiltprotocol/sdk-js' +import { + Identity, + IEncryptedMessage, + IMessage, + IPublicIdentity, + IRejectTerms, + IRequestAttestationForClaim, + IRequestClaimsForCTypes, + IRequestTerms, + ISubmitAttestationForClaim, + ISubmitClaimsForCTypesClassic, + ISubmitTerms, + Message, + MessageBody, + MessageBodyType, +} from '@kiltprotocol/sdk-js' import cloneDeep from 'lodash/cloneDeep' import React from 'react' import { InteractionProps } from 'react-json-view' @@ -19,8 +33,8 @@ import FeedbackService, { notifySuccess, } from './FeedbackService' -export interface IMessageOutput extends sdk.IMessage { - encryptedMessage: sdk.IEncryptedMessage +export interface IMessageOutput extends IMessage { + encryptedMessage: IEncryptedMessage sender?: IContact } @@ -41,7 +55,7 @@ class MessageRepository { */ public static async send( receivers: IContact[], - messageBody: sdk.MessageBody + messageBody: MessageBody ): Promise { const sender: IMyIdentity = Wallet.getSelectedIdentity( PersistentStore.store.getState() @@ -65,7 +79,7 @@ class MessageRepository { */ public static async sendToAddresses( receiverAddresses: Array, - messageBody: sdk.MessageBody + messageBody: MessageBody ): Promise { const arrayOfPromises = receiverAddresses.map( (receiverAddress: IContact['publicIdentity']['address']) => { @@ -91,8 +105,8 @@ class MessageRepository { * @param messageBody */ public static sendToPublicIdentity( - receiver: sdk.IPublicIdentity, - messageBody: sdk.MessageBody + receiver: IPublicIdentity, + messageBody: MessageBody ): Promise { const receiverContact: IContact = { metaData: { @@ -106,13 +120,11 @@ class MessageRepository { public static async multiSendToAddresses( receiverAddresses: Array, - messageBodies: sdk.MessageBody[] + messageBodies: MessageBody[] ): Promise { - const arrayOfPromises = messageBodies.map( - (messageBody: sdk.MessageBody) => { - return MessageRepository.sendToAddresses(receiverAddresses, messageBody) - } - ) + const arrayOfPromises = messageBodies.map((messageBody: MessageBody) => { + return MessageRepository.sendToAddresses(receiverAddresses, messageBody) + }) return Promise.any(arrayOfPromises) .then(result => { @@ -134,33 +146,33 @@ class MessageRepository { public static async findByMessageId( messageId: string, - myIdentity: sdk.Identity - ): Promise { + myIdentity: Identity + ): Promise { return fetch( `${MessageRepository.URL}/inbox/${myIdentity.signPublicKeyAsHex}/${messageId}` ) .then(response => response.json()) .then(message => { return ContactRepository.findByAddress(message.senderAddress).then(() => - sdk.Message.decrypt(message, myIdentity) + Message.decrypt(message, myIdentity) ) }) } public static async findByMyIdentity( - myIdentity: sdk.Identity + myIdentity: Identity ): Promise { return fetch(`${MessageRepository.URL}/inbox/${myIdentity.address}`) .then(response => response.json()) - .then((encryptedMessages: sdk.IEncryptedMessage[]) => { + .then((encryptedMessages: IEncryptedMessage[]) => { return Promise.any( - encryptedMessages.map((encryptedMessage: sdk.IEncryptedMessage) => { + encryptedMessages.map((encryptedMessage: IEncryptedMessage) => { return ContactRepository.findByAddress( encryptedMessage.senderAddress ).then((contact: IContact) => { try { - const m = sdk.Message.decrypt(encryptedMessage, myIdentity) - sdk.Message.ensureOwnerIsSender(m) + const m = Message.decrypt(encryptedMessage, myIdentity) + Message.ensureOwnerIsSender(m) let sender = contact if (!sender) { sender = { @@ -194,7 +206,7 @@ class MessageRepository { }) } - public static async dispatchMessage(message: sdk.Message): Promise { + public static async dispatchMessage(message: Message): Promise { const response = await fetch(`${MessageRepository.URL}`, { ...BasePostParams, body: JSON.stringify(message.encrypt()), @@ -206,12 +218,12 @@ class MessageRepository { } public static async singleSend( - messageBody: sdk.MessageBody, + messageBody: MessageBody, sender: IMyIdentity, receiver: IContact ): Promise { try { - let message: sdk.Message = new sdk.Message( + let message: Message = new Message( messageBody, sender.identity, receiver.publicIdentity @@ -251,30 +263,30 @@ class MessageRepository { const { type } = body switch (type) { - case sdk.MessageBodyType.REQUEST_TERMS: - return [(message.body as sdk.IRequestTerms).content.cTypeHash] - case sdk.MessageBodyType.SUBMIT_TERMS: - return [(message.body as sdk.ISubmitTerms).content.claim.cTypeHash] - case sdk.MessageBodyType.REJECT_TERMS: - return [(message.body as sdk.IRejectTerms).content.claim.cTypeHash] + case MessageBodyType.REQUEST_TERMS: + return [(message.body as IRequestTerms).content.cTypeHash] + case MessageBodyType.SUBMIT_TERMS: + return [(message.body as ISubmitTerms).content.claim.cTypeHash] + case MessageBodyType.REJECT_TERMS: + return [(message.body as IRejectTerms).content.claim.cTypeHash] - case sdk.MessageBodyType.REQUEST_ATTESTATION_FOR_CLAIM: + case MessageBodyType.REQUEST_ATTESTATION_FOR_CLAIM: return [ - (message.body as sdk.IRequestAttestationForClaim).content + (message.body as IRequestAttestationForClaim).content .requestForAttestation.claim.cTypeHash, ] - case sdk.MessageBodyType.SUBMIT_ATTESTATION_FOR_CLAIM: + case MessageBodyType.SUBMIT_ATTESTATION_FOR_CLAIM: return [ (message.body as ISubmitAttestationForClaim).content.attestation .cTypeHash, ] - case sdk.MessageBodyType.REQUEST_CLAIMS_FOR_CTYPES: - return (message.body as sdk.IRequestClaimsForCTypes).content.ctypes.filter( + case MessageBodyType.REQUEST_CLAIMS_FOR_CTYPES: + return (message.body as IRequestClaimsForCTypes).content.ctypes.filter( Boolean - ) as Array - case sdk.MessageBodyType.SUBMIT_CLAIMS_FOR_CTYPES_CLASSIC: { - const cTypeHashes = (message.body as sdk.ISubmitClaimsForCTypesClassic).content.map( + ) as Array + case MessageBodyType.SUBMIT_CLAIMS_FOR_CTYPES_CLASSIC: { + const cTypeHashes = (message.body as ISubmitClaimsForCTypesClassic).content.map( attestedClaim => attestedClaim.request.claim.cTypeHash ) const uniqueCTypeHashes: Array = cTypeHashes.filter( @@ -284,11 +296,11 @@ class MessageRepository { return uniqueCTypeHashes } - case sdk.MessageBodyType.REJECT_ATTESTATION_FOR_CLAIM: - case sdk.MessageBodyType.REQUEST_ACCEPT_DELEGATION: - case sdk.MessageBodyType.SUBMIT_ACCEPT_DELEGATION: - case sdk.MessageBodyType.REJECT_ACCEPT_DELEGATION: - case sdk.MessageBodyType.INFORM_CREATE_DELEGATION: + case MessageBodyType.REJECT_ATTESTATION_FOR_CLAIM: + case MessageBodyType.REQUEST_ACCEPT_DELEGATION: + case MessageBodyType.SUBMIT_ACCEPT_DELEGATION: + case MessageBodyType.REJECT_ACCEPT_DELEGATION: + case MessageBodyType.INFORM_CREATE_DELEGATION: return [] default: @@ -296,24 +308,22 @@ class MessageRepository { } } - private static async handleDebugMode( - message: sdk.Message - ): Promise { + private static async handleDebugMode(message: Message): Promise { const debugMode = UiState.getDebugMode(PersistentStore.store.getState()) let manipulatedMessage = cloneDeep(message) if (debugMode) { - return new Promise(resolve => { + return new Promise(resolve => { FeedbackService.addBlockingNotification({ header: 'Manipulate your message before sending', message: ( { - manipulatedMessage = edit.updated_src as sdk.Message + manipulatedMessage = edit.updated_src as Message }} onAdd={(add: InteractionProps) => { - manipulatedMessage = add.updated_src as sdk.Message + manipulatedMessage = add.updated_src as Message }} > {message} diff --git a/yarn.lock b/yarn.lock index 170056de..3659dc60 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1081,10 +1081,10 @@ "@polkadot/util" "^3.5.1" "@polkadot/util-crypto" "^3.5.1" -"@kiltprotocol/sdk-js@^0.19.1-2": - version "0.19.1-2" - resolved "https://registry.yarnpkg.com/@kiltprotocol/sdk-js/-/sdk-js-0.19.1-2.tgz#df02d35f35b88093c4d5fd81c865ede6d9bf288e" - integrity sha512-tk5M8p2ct39XGkQmoAEUVGIJU21RxUSnWBJ9U6GXHXUDfldsS6eftX1VxeDu6mykRicchroFjHpVSsgICT0bHA== +"@kiltprotocol/sdk-js@^0.19.1-8": + version "0.19.1-8" + resolved "https://registry.yarnpkg.com/@kiltprotocol/sdk-js/-/sdk-js-0.19.1-8.tgz#7842283d79e587f3d9d48558093c796c83eabb97" + integrity sha512-EL8pWG3dgZByedxwPnEGnE//ENw7xaiJasq2x3Qust5qz59PBGUMvUnt4UPa8tBSJ/UTFG9BLXu2twtHoagFzQ== dependencies: "@kiltprotocol/portablegabi" "^0.4.0" "@polkadot/api" "^2.0.1"