import * as mamClient from 'mam.tools.js' ; import { trytesToAscii } from '@iota/converter' ; import { encodeToDid , decodeFromDid , createMetaPublicKeys } from './did' ; import { Seed , Did , DidDocument , TangleProvider , PublicKeyPem } from '../../types' ; const FIRST_MESSAGE = '{}' ; const DEFAULT_PROVIDER = 'https://tangle.puyuma.org' ; /**
 * An identity registry is based on the MAM channel, it uses the channel root
 * of the first message to generate the Decentralized Identifier (DID), and
 * store each revision of the DID document.
 */ export class IdenityRegistry { provider : TangleProvider ; constructor param { object } params . provider constructor ( provider = DEFAULT_PROVIDER ) { this . provider = provider ; } param { string } seed param { string [ ] } publicKeys returns { Promise } public async publish ( seed , publicKeys = [ ] ) { const iota = mamClient . getIota ( this . provider ) ; const client = await mamClient . createMamFrom ( { iota , seed , mode : 'public' } ) ; if ( client . mam . channel . start !== 0 ) { throw new Error ( 'This identifier is already registered.' ) ; } const { root } = await mamClient . publish ( FIRST_MESSAGE , client . mam , client . iota ) ; const did = encodeToDid ( root ) ; const document = { '@context' : [ 'https://w3id.org/did/v1' , 'https://w3id.org/security/v2' ] , id : did } ; if ( publicKeys . length > 0 ) { document . publicKey = createMetaPublicKeys ( did , publicKeys ) ; document . assertionMethod = document . publicKey . map ( publicKey => publicKey . id ) ; } const message = JSON . stringify ( document ) ; await mamClient . publish ( message , client . mam , client . iota ) ; return { did , document } ; } param { string } did returns { Promise < string > } Promise object represents the
     *    https .
      public async fetch ( did ) { const decoded = decodeFromDid ( did ) ; const iota = mamClient . getIota ( this . provider ) ; const { messages } = await mamClient . getMessages ( decoded . channelRoot , 'public' , null , iota ) ; if ( messages . length === 0 ) { throw new Error ( 'Could not find the corresponding DID document' ) ; } const firstMessage = trytesToAscii ( messages [ 0 ] ) ; if ( firstMessage !== FIRST_MESSAGE ) { throw new Error ( `Root message does not match: ${ FIRST_MESSAGE }` ) ; } const index = messages . length - 1 ; const document = JSON . parse ( trytesToAscii ( messages [ index ] ) ) ; return document ; } }