@cheqd/sdk 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.releaserc.json CHANGED
@@ -28,7 +28,8 @@
28
28
  { "type": "revert", "release": false },
29
29
  { "type": "style", "release": false },
30
30
  { "type": "test", "release": false },
31
- { "scope": "no-release", "release": false }
31
+ { "scope": "no-release", "release": false },
32
+ { "scope": "release", "release": "patch" }
32
33
  ],
33
34
  "presetConfig": true
34
35
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.1.0](https://github.com/cheqd/sdk/compare/1.0.0...1.1.0) (2022-07-29)
4
+
5
+
6
+ ### Features
7
+
8
+ * **registry:** Fixed registration logic & improved extensibility ([3d76466](https://github.com/cheqd/sdk/commit/3d76466e322657817d380bf384d9f6c45c1eb793))
9
+
3
10
  ## 1.0.0 (2022-07-28)
4
11
 
5
12
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cheqd/sdk",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "A TypeScript SDK built with CosmJS to interact with cheqd network ledger",
5
5
  "licence": "Apache-2.0",
6
6
  "author": "Cheqd Foundation Limited (https://github.com/cheqd)",
package/src/index.ts CHANGED
@@ -1,90 +1,103 @@
1
- import { OfflineSigner } from '@cosmjs/proto-signing';
1
+ import { GeneratedType, OfflineSigner, Registry } from '@cosmjs/proto-signing'
2
2
  import { DIDModule, MinimalImportableDIDModule } from './modules/did'
3
3
  import { MinimalImportableResourcesModule, ResourcesModule } from './modules/resources'
4
- import { AbstractCheqdSDKModule, applyMixins, instantiateCheqdSDKModule, } from './modules/_'
4
+ import { AbstractCheqdSDKModule, applyMixins, instantiateCheqdSDKModule, instantiateCheqdSDKModuleRegistryTypes, } from './modules/_'
5
+ import { createDefaultCheqdRegistry } from './registry'
5
6
  import { CheqdSigningStargateClient } from './signer'
6
7
  import { CheqdNetwork, IContext, IModuleMethodMap } from './types'
7
8
 
8
9
  export interface ICheqdSDKOptions {
9
- modules: AbstractCheqdSDKModule[]
10
- authorizedMethods?: string[]
11
- network?: CheqdNetwork
12
- rpcUrl: string
13
- readonly wallet: OfflineSigner
10
+ modules: AbstractCheqdSDKModule[]
11
+ authorizedMethods?: string[]
12
+ network?: CheqdNetwork
13
+ rpcUrl: string
14
+ readonly wallet: OfflineSigner
14
15
  }
15
16
 
16
17
  export type DefaultCheqdSDKModules = MinimalImportableDIDModule & MinimalImportableResourcesModule
17
18
 
18
- export interface CheqdSDK extends DefaultCheqdSDKModules {}
19
+ export interface CheqdSDK extends DefaultCheqdSDKModules { }
19
20
 
20
21
  export class CheqdSDK {
21
- methods: IModuleMethodMap
22
- signer: CheqdSigningStargateClient
23
- options: ICheqdSDKOptions
24
- private protectedMethods: string[] = ['constructor', 'build', 'loadModules']
25
-
26
- constructor(options: ICheqdSDKOptions) {
27
- if (!options?.wallet) {
28
- throw new Error('No wallet provided')
29
- }
30
-
31
- this.options = {
32
- authorizedMethods: [],
33
- network: CheqdNetwork.Testnet,
34
- ...options
35
- }
36
-
37
- this.methods = {}
38
- this.signer = new CheqdSigningStargateClient(undefined, this.options.wallet, {})
22
+ methods: IModuleMethodMap
23
+ signer: CheqdSigningStargateClient
24
+ options: ICheqdSDKOptions
25
+ private protectedMethods: string[] = ['constructor', 'build', 'loadModules', 'loadRegistry']
26
+
27
+ constructor(options: ICheqdSDKOptions) {
28
+ if (!options?.wallet) {
29
+ throw new Error('No wallet provided')
30
+ }
31
+
32
+ this.options = {
33
+ authorizedMethods: [],
34
+ network: CheqdNetwork.Testnet,
35
+ ...options
36
+ }
37
+
38
+ this.methods = {}
39
+ this.signer = new CheqdSigningStargateClient(undefined, this.options.wallet, {})
40
+ }
41
+
42
+ async execute<P = any, R = any>(method: string, ...params: P[]): Promise<R> {
43
+ if (!Object.keys(this.methods).includes(method)) {
44
+ throw new Error(`Method ${method} is not authorized`)
45
+ }
46
+ return await this.methods[method](...params, { sdk: this } as IContext)
47
+ }
48
+
49
+ private loadModules(modules: AbstractCheqdSDKModule[]): CheqdSDK {
50
+ this.options.modules = this.options.modules.map((module: any) => instantiateCheqdSDKModule(module, this.signer, { sdk: this } as IContext) as unknown as AbstractCheqdSDKModule)
51
+
52
+ const methods = applyMixins(this, modules)
53
+ this.methods = { ...this.methods, ...filterUnauthorizedMethods(methods, this.options.authorizedMethods || [], this.protectedMethods) }
54
+
55
+ for (const method of Object.keys(this.methods)) {
56
+ // @ts-ignore
57
+ this[method] = async (...params: any[]) => {
58
+ return await this.execute(method, ...params)
59
+ }
60
+ }
61
+
62
+ return this
63
+ }
64
+
65
+ private loadRegistry(): Registry {
66
+ const registryTypes = this.options.modules.map((module: any) => instantiateCheqdSDKModuleRegistryTypes(module)).reduce((acc, types) => {
67
+ return [...acc, ...types]
68
+ })
69
+ return createDefaultCheqdRegistry(registryTypes)
39
70
  }
40
71
 
41
- async execute<P = any, R = any>(method: string, ...params: P[]): Promise<R> {
42
- if (!Object.keys(this.methods).includes(method)) {
43
- throw new Error(`Method ${method} is not authorized`)
44
- }
45
- return await this.methods[method](...params, { sdk: this } as IContext)
46
- }
47
-
48
- private loadModules(modules: AbstractCheqdSDKModule[]): CheqdSDK {
49
- this.options.modules = this.options.modules.map((module: any) => instantiateCheqdSDKModule(module, this.signer, { sdk: this } as IContext) as unknown as AbstractCheqdSDKModule)
72
+ async build(): Promise<CheqdSDK> {
73
+ const registry = this.loadRegistry()
50
74
 
51
- const methods = applyMixins(this, modules)
52
- this.methods = { ...this.methods, ...filterUnauthorizedMethods(methods, this.options.authorizedMethods || [], this.protectedMethods) }
53
-
54
- for(const method of Object.keys(this.methods)) {
55
- // @ts-ignore
56
- this[method] = async (...params: any[]) => {
57
- return await this.execute(method, ...params)
75
+ this.signer = await CheqdSigningStargateClient.connectWithSigner(
76
+ this.options.rpcUrl,
77
+ this.options.wallet,
78
+ {
79
+ registry,
58
80
  }
59
- }
81
+ )
60
82
 
61
- return this
62
- }
63
-
64
- async build() {
65
- this.signer = await CheqdSigningStargateClient.connectWithSigner(
66
- this.options.rpcUrl,
67
- this.options.wallet
68
- )
69
-
70
- return this.loadModules(this.options.modules)
71
- }
83
+ return this.loadModules(this.options.modules)
84
+ }
72
85
  }
73
86
 
74
87
  export function filterUnauthorizedMethods(methods: IModuleMethodMap, authorizedMethods: string[], protectedMethods: string[]): IModuleMethodMap {
75
- let _methods = Object.keys(methods)
76
- if (authorizedMethods.length === 0)
77
- return _methods
78
- .filter(method => !protectedMethods.includes(method))
79
- .reduce((acc, method) => ({ ...acc, [method]: methods[method] }), {})
80
-
81
- return _methods
82
- .filter(method => authorizedMethods.includes(method) && !protectedMethods.includes(method))
83
- .reduce((acc, method) => ({ ...acc, [method]: methods[method] }), {})
88
+ let _methods = Object.keys(methods)
89
+ if (authorizedMethods.length === 0)
90
+ return _methods
91
+ .filter(method => !protectedMethods.includes(method))
92
+ .reduce((acc, method) => ({ ...acc, [method]: methods[method] }), {})
93
+
94
+ return _methods
95
+ .filter(method => authorizedMethods.includes(method) && !protectedMethods.includes(method))
96
+ .reduce((acc, method) => ({ ...acc, [method]: methods[method] }), {})
84
97
  }
85
98
 
86
99
  export async function createCheqdSDK(options: ICheqdSDKOptions): Promise<CheqdSDK> {
87
- return await (new CheqdSDK(options)).build()
100
+ return await (new CheqdSDK(options)).build()
88
101
  }
89
102
 
90
- export { DIDModule, ResourcesModule }
103
+ export { DIDModule, ResourcesModule }
package/src/modules/_.ts CHANGED
@@ -2,57 +2,62 @@ import { GeneratedType, Registry } from "@cosmjs/proto-signing"
2
2
  import { QueryClient } from "@cosmjs/stargate"
3
3
  import { CheqdSigningStargateClient } from '../signer'
4
4
  import { IModuleMethodMap } from "../types"
5
- import { setupDidExtension } from './did'
5
+ import { DIDModule, setupDidExtension } from './did'
6
6
 
7
7
  export abstract class AbstractCheqdSDKModule {
8
- _signer: CheqdSigningStargateClient
9
- methods: IModuleMethodMap = {}
10
- readonly _protectedMethods: string[] = ['constructor', 'exportMethods', 'registryTypes']
11
-
12
- constructor(signer: CheqdSigningStargateClient) {
13
- if (!signer) {
14
- throw new Error("signer is required")
15
- }
16
- this._signer = signer
17
- }
18
-
19
- static registryTypes(): Iterable<[string, GeneratedType]> {
20
- return []
21
- }
8
+ _signer: CheqdSigningStargateClient
9
+ methods: IModuleMethodMap = {}
10
+ readonly _protectedMethods: string[] = ['constructor', 'getRegistryTypes']
11
+ static readonly registryTypes: Iterable<[string, GeneratedType]> = []
12
+
13
+ constructor(signer: CheqdSigningStargateClient) {
14
+ if (!signer) {
15
+ throw new Error("signer is required")
16
+ }
17
+ this._signer = signer
18
+ }
19
+
20
+ abstract getRegistryTypes(): Iterable<[string, GeneratedType]>
22
21
  }
23
22
 
24
- export type MinimalImportableCheqdSDKModule<T extends AbstractCheqdSDKModule> = Omit<T, '_signer' | '_protectedMethods'>
23
+ type ProtectedMethods<T extends AbstractCheqdSDKModule, K extends keyof T> = T[K] extends string[] ? T[K][number] : T[K]
24
+
25
+ export type MinimalImportableCheqdSDKModule<T extends AbstractCheqdSDKModule> = Omit<T, '_signer' | '_protectedMethods' | 'registryTypes' | 'getRegistryTypes'>
25
26
 
26
27
  export function instantiateCheqdSDKModule<T extends new (...args: any[]) => T>(module: T, ...args: ConstructorParameters<T>): T {
27
- return new module(...args)
28
+ return new module(...args)
29
+ }
30
+
31
+ export function instantiateCheqdSDKModuleRegistryTypes(module: any): Iterable<[string, GeneratedType]> {
32
+ return module.registryTypes ?? []
28
33
  }
29
34
 
30
35
  export function applyMixins(derivedCtor: any, constructors: any[]): IModuleMethodMap {
31
- let methods: IModuleMethodMap = {}
36
+ let methods: IModuleMethodMap = {}
32
37
 
33
- constructors.forEach((baseCtor) => {
34
- Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
35
- const property = baseCtor.prototype[name]
36
- if (typeof property !== 'function' || derivedCtor.hasOwnProperty(name) || derivedCtor?.protectedMethods.includes(name) || baseCtor.prototype?._protectedMethods?.includes(name)) return
38
+ constructors.forEach((baseCtor) => {
39
+ Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
40
+ const property = baseCtor.prototype[name]
41
+ if (typeof property !== 'function' || derivedCtor.hasOwnProperty(name) || derivedCtor?.protectedMethods.includes(name) || baseCtor.prototype?._protectedMethods?.includes(name)) return
37
42
 
38
- methods = { ...methods, [name]: property }
39
- });
40
- });
43
+ methods = { ...methods, [name]: property }
44
+ });
45
+ });
41
46
 
42
- return methods
47
+ return methods
43
48
  }
44
49
 
45
50
  export type CheqdExtension<K extends string, V = any> = {
46
- [P in K]: (Record<P, V> & Partial<Record<Exclude<K, P>, never>>) extends infer O
47
- ? { [Q in keyof O]: O[Q] }
48
- : never
51
+ [P in K]: (Record<P, V> & Partial<Record<Exclude<K, P>, never>>) extends infer O
52
+ ? { [Q in keyof O]: O[Q] }
53
+ : never
49
54
  }[K]
50
55
 
51
56
  export type CheqdExtensions = CheqdExtension<'did' | 'resources', any>
52
57
 
53
58
  export const setupCheqdExtensions = (base: QueryClient): CheqdExtensions => {
54
- return {
55
- ...setupDidExtension(base),
56
- /** setupResourcesExtension(base) */
57
- }
58
- }
59
+ return {
60
+ ...setupDidExtension(base),
61
+ /** setupResourcesExtension(base) */
62
+ }
63
+ }
@@ -1,87 +1,139 @@
1
- import { createProtobufRpcClient, DeliverTxResponse, QueryClient, StdFee } from "@cosmjs/stargate"
1
+ import { createProtobufRpcClient, DeliverTxResponse, QueryClient } from "@cosmjs/stargate"
2
2
  /* import { QueryClientImpl } from '@cheqd/ts-proto/cheqd/v1/query' */
3
3
  import { CheqdExtension, AbstractCheqdSDKModule, MinimalImportableCheqdSDKModule } from "./_"
4
4
  import { CheqdSigningStargateClient } from "../signer"
5
5
  import { DidStdFee, IContext, ISignInputs } from "../types"
6
- import { MsgCreateDid, MsgCreateDidPayload, MsgUpdateDid, MsgUpdateDidPayload } from "@cheqd/ts-proto/cheqd/v1/tx"
7
- import { MsgCreateDidEncodeObject, MsgUpdateDidEncodeObject, typeUrlMsgCreateDid, typeUrlMsgUpdateDid } from "../registry"
6
+ import { MsgCreateDid, MsgCreateDidPayload, MsgCreateDidResponse, MsgUpdateDid, MsgUpdateDidPayload, MsgUpdateDidResponse, protobufPackage } from "@cheqd/ts-proto/cheqd/v1/tx"
7
+ import { EncodeObject, GeneratedType } from "@cosmjs/proto-signing"
8
8
 
9
- export class DIDModule extends AbstractCheqdSDKModule {
10
- constructor(signer: CheqdSigningStargateClient){
11
- super(signer)
12
- this.methods = {
13
- createDidTx: this.createDidTx.bind(this),
14
- updateDidTx: this.updateDidTx.bind(this)
15
- }
16
- }
9
+ export const typeUrlMsgCreateDid = `/${protobufPackage}.MsgCreateDid`
10
+ export const typeUrlMsgCreateDidResponse = `/${protobufPackage}.MsgCreateDidResponse`
11
+ export const typeUrlMsgUpdateDid = `/${protobufPackage}.MsgUpdateDid`
12
+ export const typeUrlMsgUpdateDidResponse = `/${protobufPackage}.MsgUpdateDidResponse`
17
13
 
18
- async createDidTx(signInputs: ISignInputs[], didPayload: Partial<MsgCreateDidPayload>, address: string, fee: DidStdFee | 'auto' | number, memo?: string, context?: IContext): Promise<DeliverTxResponse> {
19
- if (!this._signer) {
20
- this._signer = context!.sdk!.signer
21
- }
22
-
23
- const payload = MsgCreateDidPayload.fromPartial(didPayload)
24
- const signatures = await this._signer.signCreateDidTx(signInputs, payload)
25
-
26
- const value: MsgCreateDid = {
27
- payload,
28
- signatures
29
- }
30
-
31
- const createDidMsg: MsgCreateDidEncodeObject = {
32
- typeUrl: typeUrlMsgCreateDid,
33
- value
34
- }
35
-
36
- return this._signer.signAndBroadcast(
37
- address,
38
- [createDidMsg],
39
- fee,
40
- memo
41
- )
42
- }
14
+ export interface MsgCreateDidEncodeObject extends EncodeObject {
15
+ readonly typeUrl: typeof typeUrlMsgCreateDid,
16
+ readonly value: Partial<MsgCreateDid>
17
+ }
18
+
19
+ export function isMsgCreateDidEncodeObject(obj: EncodeObject): obj is MsgCreateDidEncodeObject {
20
+ return obj.typeUrl === typeUrlMsgCreateDid
21
+ }
22
+
23
+ export interface MsgCreateDidResponseEncodeObject extends EncodeObject {
24
+ readonly typeUrl: typeof typeUrlMsgCreateDidResponse,
25
+ readonly value: Partial<MsgCreateDidResponse>
26
+ }
27
+
28
+ export function MsgCreateDidResponseEncodeObject(obj: EncodeObject): obj is MsgCreateDidResponseEncodeObject {
29
+ return obj.typeUrl === typeUrlMsgCreateDidResponse
30
+ }
31
+
32
+ export interface MsgUpdateDidEncodeObject extends EncodeObject {
33
+ readonly typeUrl: typeof typeUrlMsgUpdateDid,
34
+ readonly value: Partial<MsgUpdateDid>
35
+ }
36
+
37
+ export function MsgUpdateDidEncodeObject(obj: EncodeObject): obj is MsgUpdateDidEncodeObject {
38
+ return obj.typeUrl === typeUrlMsgUpdateDid
39
+ }
43
40
 
44
- async updateDidTx(signInputs: ISignInputs[], didPayload: Partial<MsgUpdateDidPayload>, address: string, fee: DidStdFee | 'auto' | number, memo?: string, context?: IContext): Promise<DeliverTxResponse> {
45
- if (!this._signer) {
46
- this._signer = context!.sdk!.signer
47
- }
48
-
49
- const payload = MsgUpdateDidPayload.fromPartial(didPayload)
50
- const signatures = await this._signer.signUpdateDidTx(signInputs, payload)
51
-
52
- const value: MsgUpdateDid = {
53
- payload,
54
- signatures
55
- }
56
-
57
- const updateDidMsg: MsgUpdateDidEncodeObject = {
58
- typeUrl: typeUrlMsgUpdateDid,
59
- value
60
- }
61
-
62
- return this._signer.signAndBroadcast(
63
- address,
64
- [updateDidMsg],
65
- fee,
66
- memo
67
- )
41
+ export interface MsgUpdateDidResponseEncodeObject extends EncodeObject {
42
+ readonly typeUrl: typeof typeUrlMsgUpdateDidResponse,
43
+ readonly value: Partial<MsgUpdateDidResponse>
44
+ }
45
+
46
+ export function MsgUpdateDidResponseEncodeObject(obj: EncodeObject): obj is MsgUpdateDidResponseEncodeObject {
47
+ return obj.typeUrl === typeUrlMsgUpdateDidResponse
48
+ }
49
+
50
+ export class DIDModule extends AbstractCheqdSDKModule {
51
+ static readonly registryTypes: Iterable<[string, GeneratedType]> = [
52
+ [typeUrlMsgCreateDid, MsgCreateDid],
53
+ [typeUrlMsgCreateDidResponse, MsgCreateDidResponse],
54
+ [typeUrlMsgUpdateDid, MsgUpdateDid],
55
+ [typeUrlMsgUpdateDidResponse, MsgUpdateDidResponse],
56
+ ]
57
+
58
+ constructor(signer: CheqdSigningStargateClient) {
59
+ super(signer)
60
+ this.methods = {
61
+ createDidTx: this.createDidTx.bind(this),
62
+ updateDidTx: this.updateDidTx.bind(this)
63
+ }
64
+ }
65
+
66
+ public getRegistryTypes(): Iterable<[string, GeneratedType]> {
67
+ return DIDModule.registryTypes
68
68
  }
69
+
70
+ async createDidTx(signInputs: ISignInputs[], didPayload: Partial<MsgCreateDidPayload>, address: string, fee: DidStdFee | 'auto' | number, memo?: string, context?: IContext): Promise<DeliverTxResponse> {
71
+ if (!this._signer) {
72
+ this._signer = context!.sdk!.signer
73
+ }
74
+
75
+ const payload = MsgCreateDidPayload.fromPartial(didPayload)
76
+ const signatures = await this._signer.signCreateDidTx(signInputs, payload)
77
+
78
+ const value: MsgCreateDid = {
79
+ payload,
80
+ signatures
81
+ }
82
+
83
+ const createDidMsg: MsgCreateDidEncodeObject = {
84
+ typeUrl: typeUrlMsgCreateDid,
85
+ value
86
+ }
87
+
88
+ return this._signer.signAndBroadcast(
89
+ address,
90
+ [createDidMsg],
91
+ fee,
92
+ memo
93
+ )
94
+ }
95
+
96
+ async updateDidTx(signInputs: ISignInputs[], didPayload: Partial<MsgUpdateDidPayload>, address: string, fee: DidStdFee | 'auto' | number, memo?: string, context?: IContext): Promise<DeliverTxResponse> {
97
+ if (!this._signer) {
98
+ this._signer = context!.sdk!.signer
99
+ }
100
+
101
+ const payload = MsgUpdateDidPayload.fromPartial(didPayload)
102
+ const signatures = await this._signer.signUpdateDidTx(signInputs, payload)
103
+
104
+ const value: MsgUpdateDid = {
105
+ payload,
106
+ signatures
107
+ }
108
+
109
+ const updateDidMsg: MsgUpdateDidEncodeObject = {
110
+ typeUrl: typeUrlMsgUpdateDid,
111
+ value
112
+ }
113
+
114
+ return this._signer.signAndBroadcast(
115
+ address,
116
+ [updateDidMsg],
117
+ fee,
118
+ memo
119
+ )
120
+ }
69
121
  }
70
122
 
71
123
  export type MinimalImportableDIDModule = MinimalImportableCheqdSDKModule<DIDModule>
72
124
 
73
125
  export interface DidExtension extends CheqdExtension<string, {}> {
74
- did: {}
126
+ did: {}
75
127
  }
76
128
 
77
129
  export const setupDidExtension = (base: QueryClient): DidExtension => {
78
- const rpc = createProtobufRpcClient(base)
130
+ const rpc = createProtobufRpcClient(base)
79
131
 
80
- /* const queryService = new QueryClientImpl(rpc) */
132
+ /* const queryService = new QueryClientImpl(rpc) */
81
133
 
82
- return {
83
- did: {
84
- //...
85
- }
86
- }
87
- }
134
+ return {
135
+ did: {
136
+ //...
137
+ }
138
+ }
139
+ }
@@ -1,11 +1,18 @@
1
1
  import { AbstractCheqdSDKModule, MinimalImportableCheqdSDKModule } from "./_"
2
2
  import { CheqdSigningStargateClient } from "../signer"
3
+ import { GeneratedType } from "@cosmjs/proto-signing"
3
4
 
4
5
 
5
6
  export class ResourcesModule extends AbstractCheqdSDKModule {
6
- constructor(signer: CheqdSigningStargateClient) {
7
- super(signer)
8
- }
7
+ registryTypes: Iterable<[string, GeneratedType]> = []
8
+
9
+ constructor(signer: CheqdSigningStargateClient) {
10
+ super(signer)
11
+ }
12
+
13
+ public getRegistryTypes(): Iterable<[string, GeneratedType]> {
14
+ return []
15
+ }
9
16
  }
10
17
 
11
- export type MinimalImportableResourcesModule = MinimalImportableCheqdSDKModule<ResourcesModule>
18
+ export type MinimalImportableResourcesModule = MinimalImportableCheqdSDKModule<ResourcesModule>
package/src/registry.ts CHANGED
@@ -1,71 +1,15 @@
1
1
  import {
2
- Registry,
3
- GeneratedType,
4
- EncodeObject
2
+ Registry,
3
+ GeneratedType,
5
4
  } from '@cosmjs/proto-signing'
6
5
 
7
6
  import {
8
- defaultRegistryTypes
7
+ defaultRegistryTypes
9
8
  } from '@cosmjs/stargate'
10
9
 
11
- import {
12
- MsgCreateDid, MsgCreateDidResponse, MsgUpdateDid, MsgUpdateDidResponse
13
- } from '@cheqd/ts-proto/cheqd/v1/tx'
14
-
15
- export const typeUrlMsgCreateDid = '/cheqdid.cheqdnode.cheqd.v1.MsgCreateDid'
16
- export const typeUrlMsgCreateDidResponse = '/cheqdid.cheqdnode.cheqd.v1.MsgCreateDidResponse'
17
- export const typeUrlMsgUpdateDid = '/cheqdid.cheqdnode.cheqd.v1.MsgUpdateDid'
18
- export const typeUrlMsgUpdateDidResponse = '/cheqdid.cheqdnode.cheqd.v1.MsgUpdateDidResponse'
19
-
20
- const defaultCheqdRegistryTypes: Iterable<[string, GeneratedType]> = [
21
- ...defaultRegistryTypes,
22
-
23
- /** Move them as registrations to each module's constructor. */
24
-
25
- [typeUrlMsgCreateDid, MsgCreateDid],
26
- [typeUrlMsgCreateDidResponse, MsgCreateDidResponse],
27
- [typeUrlMsgUpdateDid, MsgUpdateDid],
28
- [typeUrlMsgUpdateDidResponse, MsgUpdateDidResponse],
29
- ]
30
-
31
- export function createDefaultCheqdRegistry(): Registry {
32
- return new Registry(defaultCheqdRegistryTypes)
33
- }
34
-
35
- export const CheqdRegistry = new Registry(defaultCheqdRegistryTypes)
36
-
37
- export interface MsgCreateDidEncodeObject extends EncodeObject {
38
- readonly typeUrl: typeof typeUrlMsgCreateDid,
39
- readonly value: Partial<MsgCreateDid>
40
- }
41
-
42
- export function isMsgCreateDidEncodeObject(obj: EncodeObject): obj is MsgCreateDidEncodeObject {
43
- return obj.typeUrl === typeUrlMsgCreateDid
44
- }
45
-
46
- export interface MsgCreateDidResponseEncodeObject extends EncodeObject {
47
- readonly typeUrl: typeof typeUrlMsgCreateDidResponse,
48
- readonly value: Partial<MsgCreateDidResponse>
49
- }
50
-
51
- export function MsgCreateDidResponseEncodeObject(obj: EncodeObject): obj is MsgCreateDidResponseEncodeObject {
52
- return obj.typeUrl === typeUrlMsgCreateDidResponse
53
- }
54
-
55
- export interface MsgUpdateDidEncodeObject extends EncodeObject {
56
- readonly typeUrl: typeof typeUrlMsgUpdateDid,
57
- readonly value: Partial<MsgUpdateDid>
58
- }
59
-
60
- export function MsgUpdateDidEncodeObject(obj: EncodeObject): obj is MsgUpdateDidEncodeObject {
61
- return obj.typeUrl === typeUrlMsgUpdateDid
62
- }
63
-
64
- export interface MsgUpdateDidResponseEncodeObject extends EncodeObject {
65
- readonly typeUrl: typeof typeUrlMsgUpdateDidResponse,
66
- readonly value: Partial<MsgUpdateDidResponse>
10
+ export function createDefaultCheqdRegistry(customTypes?: Iterable<[string, GeneratedType]>): Registry {
11
+ if (!customTypes) customTypes = [];
12
+ return new Registry([...defaultRegistryTypes, ...customTypes])
67
13
  }
68
14
 
69
- export function MsgUpdateDidResponseEncodeObject(obj: EncodeObject): obj is MsgUpdateDidResponseEncodeObject {
70
- return obj.typeUrl === typeUrlMsgUpdateDidResponse
71
- }
15
+ export const CheqdRegistry = new Registry(defaultRegistryTypes)
package/src/signer.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { CheqdExtensions } from './modules/_'
2
- import { EncodeObject, isOfflineDirectSigner, OfflineSigner, encodePubkey, TxBodyEncodeObject, makeSignDoc } from "@cosmjs/proto-signing"
2
+ import { EncodeObject, isOfflineDirectSigner, OfflineSigner, encodePubkey, TxBodyEncodeObject, makeSignDoc, Registry } from "@cosmjs/proto-signing"
3
3
  import { DeliverTxResponse, GasPrice, HttpEndpoint, QueryClient, SigningStargateClient, SigningStargateClientOptions, calculateFee, SignerData } from "@cosmjs/stargate"
4
4
  import { Tendermint34Client } from "@cosmjs/tendermint-rpc"
5
5
  import { createDefaultCheqdRegistry } from "./registry"
@@ -19,211 +19,210 @@ import { Coin } from 'cosmjs-types/cosmos/base/v1beta1/coin'
19
19
  import Long from 'long'
20
20
 
21
21
  export function calculateDidFee(gasLimit: number, gasPrice: string | GasPrice): DidStdFee {
22
- return calculateFee(gasLimit, gasPrice)
22
+ return calculateFee(gasLimit, gasPrice)
23
23
  }
24
24
 
25
25
  export function makeSignerInfos(
26
- signers: ReadonlyArray<{ readonly pubkey: Any; readonly sequence: number }>,
27
- signMode: SignMode,
26
+ signers: ReadonlyArray<{ readonly pubkey: Any; readonly sequence: number }>,
27
+ signMode: SignMode,
28
28
  ): SignerInfo[] {
29
- return signers.map(
30
- ({ pubkey, sequence }): SignerInfo => ({
31
- publicKey: pubkey,
32
- modeInfo: {
33
- single: { mode: signMode },
34
- },
35
- sequence: Long.fromNumber(sequence),
36
- }),
37
- );
29
+ return signers.map(
30
+ ({ pubkey, sequence }): SignerInfo => ({
31
+ publicKey: pubkey,
32
+ modeInfo: {
33
+ single: { mode: signMode },
34
+ },
35
+ sequence: Long.fromNumber(sequence),
36
+ }),
37
+ );
38
38
  }
39
39
 
40
40
  export function makeDidAuthInfoBytes(
41
- signers: ReadonlyArray<{ readonly pubkey: Any; readonly sequence: number }>,
42
- feeAmount: readonly Coin[],
43
- gasLimit: number,
44
- feePayer: string,
45
- signMode = SignMode.SIGN_MODE_DIRECT,
41
+ signers: ReadonlyArray<{ readonly pubkey: Any; readonly sequence: number }>,
42
+ feeAmount: readonly Coin[],
43
+ gasLimit: number,
44
+ feePayer: string,
45
+ signMode = SignMode.SIGN_MODE_DIRECT,
46
46
  ): Uint8Array {
47
- const authInfo = {
48
- signerInfos: makeSignerInfos(signers, signMode),
49
- fee: {
50
- amount: [...feeAmount],
51
- gasLimit: Long.fromNumber(gasLimit),
52
- payer: feePayer
53
- }
54
- }
55
- return AuthInfo.encode(AuthInfo.fromPartial(authInfo)).finish()
47
+ const authInfo = {
48
+ signerInfos: makeSignerInfos(signers, signMode),
49
+ fee: {
50
+ amount: [...feeAmount],
51
+ gasLimit: Long.fromNumber(gasLimit),
52
+ payer: feePayer
53
+ }
54
+ }
55
+ return AuthInfo.encode(AuthInfo.fromPartial(authInfo)).finish()
56
56
  }
57
57
 
58
58
 
59
59
  export class CheqdSigningStargateClient extends SigningStargateClient {
60
- public readonly cheqdExtensions: CheqdExtensions | undefined
61
- private didSigners: TSignerAlgo = {}
62
- private readonly _gasPrice: GasPrice | undefined
63
- private readonly _signer: OfflineSigner
64
-
65
- public static async connectWithSigner(endpoint: string | HttpEndpoint, signer: OfflineSigner, options?: SigningStargateClientOptions | undefined): Promise<CheqdSigningStargateClient> {
66
- const tmClient = await Tendermint34Client.connect(endpoint)
67
- return new CheqdSigningStargateClient(tmClient, signer, {
68
- registry: createDefaultCheqdRegistry(),
69
- ...options
70
- })
71
- }
72
-
73
- constructor(
74
- tmClient: Tendermint34Client | undefined,
75
- signer: OfflineSigner,
76
- options: SigningStargateClientOptions = {}
77
- ) {
78
- super(tmClient, signer, options)
79
- this._signer = signer
80
- if (options.gasPrice) this._gasPrice = options.gasPrice
81
-
82
- /** GRPC Connection */
83
-
84
- /* if (tmClient) {
85
- this.cheqdExtensions = QueryClient.withExtensions(tmClient, setupCheqdExtensions)
86
- } */
87
- }
88
-
89
- async signAndBroadcast(
90
- signerAddress: string,
91
- messages: readonly EncodeObject[],
92
- fee: DidStdFee | "auto" | number,
93
- memo = "",
94
- ): Promise<DeliverTxResponse> {
95
- let usedFee: DidStdFee
96
- if (fee == "auto" || typeof fee === "number") {
97
- assertDefined(this._gasPrice, "Gas price must be set in the client options when auto gas is used.")
98
- const gasEstimation = await this.simulate(signerAddress, messages, memo)
99
- const multiplier = typeof fee === "number" ? fee : 1.3
100
- usedFee = calculateDidFee(Math.round(gasEstimation * multiplier), this._gasPrice)
101
- usedFee.payer = signerAddress
102
- } else {
103
- usedFee = fee
104
- assertDefined(usedFee.payer, "Payer address must be set when fee is not auto.")
105
- signerAddress = usedFee.payer!
106
- }
107
- const txRaw = await this.sign(signerAddress, messages, usedFee, memo)
108
- const txBytes = TxRaw.encode(txRaw).finish()
109
- return this.broadcastTx(txBytes, this.broadcastTimeoutMs, this.broadcastPollIntervalMs)
110
- }
111
-
112
- public async sign(
113
- signerAddress: string,
114
- messages: readonly EncodeObject[],
115
- fee: DidStdFee,
116
- memo: string,
117
- explicitSignerData?: SignerData,
118
- ): Promise<TxRaw> {
119
- let signerData: SignerData
120
- if (explicitSignerData) {
121
- signerData = explicitSignerData
122
- } else {
123
- const { accountNumber, sequence } = await this.getSequence(signerAddress)
124
- const chainId = await this.getChainId()
125
- signerData = {
126
- accountNumber: accountNumber,
127
- sequence: sequence,
128
- chainId: chainId,
129
- }
130
- }
131
-
132
- return this._signDirect(signerAddress, messages, fee, memo, signerData)
133
-
134
- // TODO: override signAmino as well
135
- /* return isOfflineDirectSigner(this._signer)
136
- ? this._signDirect(signerAddress, messages, fee, memo, signerData)
137
- : this._signAmino(signerAddress, messages, fee, memo, signerData) */
138
- }
139
-
140
- private async _signDirect(
141
- signerAddress: string,
142
- messages: readonly EncodeObject[],
143
- fee: DidStdFee,
144
- memo: string,
145
- { accountNumber, sequence, chainId }: SignerData,
146
- ): Promise<TxRaw> {
147
- assert(isOfflineDirectSigner(this._signer))
148
- const accountFromSigner = (await this._signer.getAccounts()).find(
149
- (account) => account.address === signerAddress,
150
- )
151
- if (!accountFromSigner) {
152
- throw new Error("Failed to retrieve account from signer")
153
- }
154
- const pubkey = encodePubkey(encodeSecp256k1Pubkey(accountFromSigner.pubkey))
155
- const txBodyEncodeObject: TxBodyEncodeObject = {
156
- typeUrl: "/cosmos.tx.v1beta1.TxBody",
157
- value: {
158
- messages: messages,
159
- memo: memo,
160
- },
161
- }
162
- const txBodyBytes = this.registry.encode(txBodyEncodeObject)
163
- const gasLimit = Int53.fromString(fee.gas).toNumber()
164
- const authInfoBytes = makeDidAuthInfoBytes([{ pubkey, sequence }], fee.amount, gasLimit, fee.payer!)
165
- const signDoc = makeSignDoc(txBodyBytes, authInfoBytes, chainId, accountNumber)
166
- const { signature, signed } = await this._signer.signDirect(signerAddress, signDoc)
167
- return TxRaw.fromPartial({
168
- bodyBytes: signed.bodyBytes,
169
- authInfoBytes: signed.authInfoBytes,
170
- signatures: [fromBase64(signature.signature)],
171
- })
172
- }
173
-
174
- async checkDidSigners(verificationMethods: Partial<VerificationMethod>[] = []): Promise<TSignerAlgo> {
175
- if (verificationMethods.length === 0) {
176
- throw new Error('No verification methods provided')
177
- }
178
-
179
- verificationMethods.forEach((verificationMethod) => {
180
- if (!(Object.values(VerificationMethods) as string[]).includes(verificationMethod.type ?? '')) {
181
- throw new Error(`Unsupported verification method type: ${verificationMethod.type}`)
182
- }
183
- if (!this.didSigners[verificationMethod.type ?? '']) {
184
- this.didSigners[verificationMethod.type ?? ''] = EdDSASigner
185
- }
186
- })
187
-
188
- return this.didSigners
189
- }
190
-
191
- async getDidSigner(verificationMethodId: string, verificationMethods: Partial<VerificationMethod>[]): Promise<(secretKey: Uint8Array) => Signer> {
192
- await this.checkDidSigners(verificationMethods)
193
- const verificationMethod = verificationMethods.find(method => method.id === verificationMethodId)?.type
194
- if (!verificationMethod) {
195
- throw new Error(`Verification method for ${verificationMethodId} not found`)
196
- }
197
- return this.didSigners[verificationMethod]!
198
- }
199
-
200
- async signCreateDidTx(signInputs: ISignInputs[], payload: MsgCreateDidPayload): Promise<SignInfo[]> {
201
- await this.checkDidSigners(payload?.verificationMethod)
202
-
203
- const signBytes = MsgCreateDidPayload.encode(payload).finish()
204
- const signInfos: SignInfo[] = await Promise.all(signInputs.map(async (signInput) => {
205
- return {
206
- verificationMethodId: signInput.verificationMethodId,
207
- // TODO: We can't rely on `payload.verificationMethod` here because `CreateResourceTx` doesn't have it
208
- signature: toString(base64ToBytes((await (await this.getDidSigner(signInput.verificationMethodId, payload.verificationMethod))(hexToBytes(signInput.privateKeyHex))(signBytes)) as string), 'base64pad')
209
- }
210
- }))
211
-
212
- return signInfos
213
- }
214
-
215
- async signUpdateDidTx(signInputs: ISignInputs[], payload: MsgUpdateDidPayload): Promise<SignInfo[]> {
216
- await this.checkDidSigners(payload?.verificationMethod)
217
-
218
- const signBytes = MsgUpdateDidPayload.encode(payload).finish()
219
- const signInfos: SignInfo[] = await Promise.all(signInputs.map(async (signInput) => {
220
- return {
221
- verificationMethodId: signInput.verificationMethodId,
222
- // TODO: We can't rely on `payload.verificationMethod` here because `CreateResourceTx` doesn't have it
223
- signature: toString(base64ToBytes((await (await this.getDidSigner(signInput.verificationMethodId, payload.verificationMethod))(hexToBytes(signInput.privateKeyHex))(signBytes)) as string), 'base64pad')
224
- }
225
- }))
226
-
227
- return signInfos
228
- }
229
- }
60
+ public readonly cheqdExtensions: CheqdExtensions | undefined
61
+ private didSigners: TSignerAlgo = {}
62
+ private readonly _gasPrice: GasPrice | undefined
63
+ private readonly _signer: OfflineSigner
64
+
65
+ public static async connectWithSigner(endpoint: string | HttpEndpoint, signer: OfflineSigner, options?: SigningStargateClientOptions | undefined): Promise<CheqdSigningStargateClient> {
66
+ const tmClient = await Tendermint34Client.connect(endpoint)
67
+ return new CheqdSigningStargateClient(tmClient, signer, {
68
+ registry: options?.registry ? options.registry : createDefaultCheqdRegistry(),
69
+ ...options
70
+ })
71
+ }
72
+
73
+ constructor(
74
+ tmClient: Tendermint34Client | undefined,
75
+ signer: OfflineSigner,
76
+ options: SigningStargateClientOptions = {}
77
+ ) {
78
+ super(tmClient, signer, options)
79
+ this._signer = signer
80
+ if (options.gasPrice) this._gasPrice = options.gasPrice
81
+ /** GRPC Connection */
82
+
83
+ /* if (tmClient) {
84
+ this.cheqdExtensions = QueryClient.withExtensions(tmClient, setupCheqdExtensions)
85
+ } */
86
+ }
87
+
88
+ async signAndBroadcast(
89
+ signerAddress: string,
90
+ messages: readonly EncodeObject[],
91
+ fee: DidStdFee | "auto" | number,
92
+ memo = "",
93
+ ): Promise<DeliverTxResponse> {
94
+ let usedFee: DidStdFee
95
+ if (fee == "auto" || typeof fee === "number") {
96
+ assertDefined(this._gasPrice, "Gas price must be set in the client options when auto gas is used.")
97
+ const gasEstimation = await this.simulate(signerAddress, messages, memo)
98
+ const multiplier = typeof fee === "number" ? fee : 1.3
99
+ usedFee = calculateDidFee(Math.round(gasEstimation * multiplier), this._gasPrice)
100
+ usedFee.payer = signerAddress
101
+ } else {
102
+ usedFee = fee
103
+ assertDefined(usedFee.payer, "Payer address must be set when fee is not auto.")
104
+ signerAddress = usedFee.payer!
105
+ }
106
+ const txRaw = await this.sign(signerAddress, messages, usedFee, memo)
107
+ const txBytes = TxRaw.encode(txRaw).finish()
108
+ return this.broadcastTx(txBytes, this.broadcastTimeoutMs, this.broadcastPollIntervalMs)
109
+ }
110
+
111
+ public async sign(
112
+ signerAddress: string,
113
+ messages: readonly EncodeObject[],
114
+ fee: DidStdFee,
115
+ memo: string,
116
+ explicitSignerData?: SignerData,
117
+ ): Promise<TxRaw> {
118
+ let signerData: SignerData
119
+ if (explicitSignerData) {
120
+ signerData = explicitSignerData
121
+ } else {
122
+ const { accountNumber, sequence } = await this.getSequence(signerAddress)
123
+ const chainId = await this.getChainId()
124
+ signerData = {
125
+ accountNumber: accountNumber,
126
+ sequence: sequence,
127
+ chainId: chainId,
128
+ }
129
+ }
130
+
131
+ return this._signDirect(signerAddress, messages, fee, memo, signerData)
132
+
133
+ // TODO: override signAmino as well
134
+ /* return isOfflineDirectSigner(this._signer)
135
+ ? this._signDirect(signerAddress, messages, fee, memo, signerData)
136
+ : this._signAmino(signerAddress, messages, fee, memo, signerData) */
137
+ }
138
+
139
+ private async _signDirect(
140
+ signerAddress: string,
141
+ messages: readonly EncodeObject[],
142
+ fee: DidStdFee,
143
+ memo: string,
144
+ { accountNumber, sequence, chainId }: SignerData,
145
+ ): Promise<TxRaw> {
146
+ assert(isOfflineDirectSigner(this._signer))
147
+ const accountFromSigner = (await this._signer.getAccounts()).find(
148
+ (account) => account.address === signerAddress,
149
+ )
150
+ if (!accountFromSigner) {
151
+ throw new Error("Failed to retrieve account from signer")
152
+ }
153
+ const pubkey = encodePubkey(encodeSecp256k1Pubkey(accountFromSigner.pubkey))
154
+ const txBodyEncodeObject: TxBodyEncodeObject = {
155
+ typeUrl: "/cosmos.tx.v1beta1.TxBody",
156
+ value: {
157
+ messages: messages,
158
+ memo: memo,
159
+ },
160
+ }
161
+ const txBodyBytes = this.registry.encode(txBodyEncodeObject)
162
+ const gasLimit = Int53.fromString(fee.gas).toNumber()
163
+ const authInfoBytes = makeDidAuthInfoBytes([{ pubkey, sequence }], fee.amount, gasLimit, fee.payer!)
164
+ const signDoc = makeSignDoc(txBodyBytes, authInfoBytes, chainId, accountNumber)
165
+ const { signature, signed } = await this._signer.signDirect(signerAddress, signDoc)
166
+ return TxRaw.fromPartial({
167
+ bodyBytes: signed.bodyBytes,
168
+ authInfoBytes: signed.authInfoBytes,
169
+ signatures: [fromBase64(signature.signature)],
170
+ })
171
+ }
172
+
173
+ async checkDidSigners(verificationMethods: Partial<VerificationMethod>[] = []): Promise<TSignerAlgo> {
174
+ if (verificationMethods.length === 0) {
175
+ throw new Error('No verification methods provided')
176
+ }
177
+
178
+ verificationMethods.forEach((verificationMethod) => {
179
+ if (!(Object.values(VerificationMethods) as string[]).includes(verificationMethod.type ?? '')) {
180
+ throw new Error(`Unsupported verification method type: ${verificationMethod.type}`)
181
+ }
182
+ if (!this.didSigners[verificationMethod.type ?? '']) {
183
+ this.didSigners[verificationMethod.type ?? ''] = EdDSASigner
184
+ }
185
+ })
186
+
187
+ return this.didSigners
188
+ }
189
+
190
+ async getDidSigner(verificationMethodId: string, verificationMethods: Partial<VerificationMethod>[]): Promise<(secretKey: Uint8Array) => Signer> {
191
+ await this.checkDidSigners(verificationMethods)
192
+ const verificationMethod = verificationMethods.find(method => method.id === verificationMethodId)?.type
193
+ if (!verificationMethod) {
194
+ throw new Error(`Verification method for ${verificationMethodId} not found`)
195
+ }
196
+ return this.didSigners[verificationMethod]!
197
+ }
198
+
199
+ async signCreateDidTx(signInputs: ISignInputs[], payload: MsgCreateDidPayload): Promise<SignInfo[]> {
200
+ await this.checkDidSigners(payload?.verificationMethod)
201
+
202
+ const signBytes = MsgCreateDidPayload.encode(payload).finish()
203
+ const signInfos: SignInfo[] = await Promise.all(signInputs.map(async (signInput) => {
204
+ return {
205
+ verificationMethodId: signInput.verificationMethodId,
206
+ // TODO: We can't rely on `payload.verificationMethod` here because `CreateResourceTx` doesn't have it
207
+ signature: toString(base64ToBytes((await (await this.getDidSigner(signInput.verificationMethodId, payload.verificationMethod))(hexToBytes(signInput.privateKeyHex))(signBytes)) as string), 'base64pad')
208
+ }
209
+ }))
210
+
211
+ return signInfos
212
+ }
213
+
214
+ async signUpdateDidTx(signInputs: ISignInputs[], payload: MsgUpdateDidPayload): Promise<SignInfo[]> {
215
+ await this.checkDidSigners(payload?.verificationMethod)
216
+
217
+ const signBytes = MsgUpdateDidPayload.encode(payload).finish()
218
+ const signInfos: SignInfo[] = await Promise.all(signInputs.map(async (signInput) => {
219
+ return {
220
+ verificationMethodId: signInput.verificationMethodId,
221
+ // TODO: We can't rely on `payload.verificationMethod` here because `CreateResourceTx` doesn't have it
222
+ signature: toString(base64ToBytes((await (await this.getDidSigner(signInput.verificationMethodId, payload.verificationMethod))(hexToBytes(signInput.privateKeyHex))(signBytes)) as string), 'base64pad')
223
+ }
224
+ }))
225
+
226
+ return signInfos
227
+ }
228
+ }
@@ -1,8 +1,9 @@
1
- import { DirectSecp256k1HdWallet } from '@cosmjs/proto-signing'
1
+ import { DirectSecp256k1HdWallet, GeneratedType } from '@cosmjs/proto-signing'
2
2
  import { createCheqdSDK, DIDModule, ICheqdSDKOptions } from '../src/index'
3
3
  import { exampleCheqdNetwork, faucet } from './testutils.test'
4
4
  import { AbstractCheqdSDKModule } from '../src/modules/_'
5
5
  import { CheqdSigningStargateClient } from '../src/signer'
6
+ import { createDefaultCheqdRegistry } from '../src/registry'
6
7
 
7
8
  describe(
8
9
  'CheqdSDK', () => {
@@ -27,15 +28,18 @@ describe(
27
28
  it('should use module methods', async () => {
28
29
  const rpcUrl = exampleCheqdNetwork.rpcUrl
29
30
  const wallet = await DirectSecp256k1HdWallet.fromMnemonic(faucet.mnemonic)
30
- const testSigner = await CheqdSigningStargateClient.connectWithSigner(rpcUrl, wallet)
31
31
 
32
32
  class TestModule extends AbstractCheqdSDKModule {
33
+ registryTypes: Iterable<[string, GeneratedType]> = []
33
34
  methods = {
34
35
  doSomething: this.doSomething.bind(this)
35
36
  }
36
37
  constructor(signer: CheqdSigningStargateClient) {
37
38
  super(signer)
38
39
  }
40
+ public getRegistryTypes(): Iterable<[string, GeneratedType]> {
41
+ return TestModule.registryTypes
42
+ }
39
43
  async doSomething(): Promise<string> {
40
44
  return 'did something'
41
45
  }
@@ -58,6 +62,20 @@ describe(
58
62
  await cheqdSDK.doSomething()
59
63
  expect(spy).toHaveBeenCalled()
60
64
  })
65
+
66
+ it('should instantiate registry from passed modules', async () => {
67
+ const options = {
68
+ modules: [DIDModule as unknown as AbstractCheqdSDKModule],
69
+ rpcUrl: exampleCheqdNetwork.rpcUrl,
70
+ wallet: await DirectSecp256k1HdWallet.fromMnemonic(faucet.mnemonic)
71
+ } as ICheqdSDKOptions
72
+ const cheqdSDK = await createCheqdSDK(options)
73
+
74
+ const didRegistryTypes = DIDModule.registryTypes
75
+ const cheqdRegistry = createDefaultCheqdRegistry(didRegistryTypes)
76
+
77
+ expect(cheqdSDK.signer.registry).toStrictEqual(cheqdRegistry)
78
+ })
61
79
  })
62
80
  }
63
81
  )
@@ -3,11 +3,13 @@ import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing"
3
3
  import { DeliverTxResponse } from "@cosmjs/stargate"
4
4
  import { fromString, toString } from 'uint8arrays'
5
5
  import { DIDModule } from "../../src"
6
+ import { AbstractCheqdSDKModule } from "../../src/modules/_"
7
+ import { createDefaultCheqdRegistry } from "../../src/registry"
6
8
  import { CheqdSigningStargateClient } from "../../src/signer"
7
9
  import { DidStdFee, ISignInputs, MethodSpecificIdAlgo, VerificationMethods } from "../../src/types"
8
10
  import { createDidPayload, createDidVerificationMethod, createKeyPairBase64, createVerificationKeys, exampleCheqdNetwork, faucet } from "../testutils.test"
9
11
 
10
- const defaultAsyncTxTimeout = 10000
12
+ const defaultAsyncTxTimeout = 20000
11
13
 
12
14
  describe('DIDModule', () => {
13
15
  describe('constructor', () => {
@@ -22,7 +24,8 @@ describe('DIDModule', () => {
22
24
  describe('createDidTx', () => {
23
25
  it('should create a new multibase DID', async () => {
24
26
  const wallet = await DirectSecp256k1HdWallet.fromMnemonic(faucet.mnemonic, {prefix: faucet.prefix})
25
- const signer = await CheqdSigningStargateClient.connectWithSigner(exampleCheqdNetwork.rpcUrl, wallet)
27
+ const registry = createDefaultCheqdRegistry(DIDModule.registryTypes)
28
+ const signer = await CheqdSigningStargateClient.connectWithSigner(exampleCheqdNetwork.rpcUrl, wallet, { registry })
26
29
  const didModule = new DIDModule(signer)
27
30
  const keyPair = createKeyPairBase64()
28
31
  const verificationKeys = createVerificationKeys(keyPair, MethodSpecificIdAlgo.Base58, 'key-1', 16)
@@ -59,7 +62,8 @@ describe('DIDModule', () => {
59
62
 
60
63
  it('should create a new uuid DID', async () => {
61
64
  const wallet = await DirectSecp256k1HdWallet.fromMnemonic(faucet.mnemonic, {prefix: faucet.prefix})
62
- const signer = await CheqdSigningStargateClient.connectWithSigner(exampleCheqdNetwork.rpcUrl, wallet)
65
+ const registry = createDefaultCheqdRegistry(DIDModule.registryTypes)
66
+ const signer = await CheqdSigningStargateClient.connectWithSigner(exampleCheqdNetwork.rpcUrl, wallet, { registry })
63
67
  const didModule = new DIDModule(signer)
64
68
  const keyPair = createKeyPairBase64()
65
69
  const verificationKeys = createVerificationKeys(keyPair, MethodSpecificIdAlgo.Uuid, 'key-1', 16)
@@ -98,7 +102,8 @@ describe('DIDModule', () => {
98
102
  describe('updateDidTx', () => {
99
103
  it('should update a DID', async () => {
100
104
  const wallet = await DirectSecp256k1HdWallet.fromMnemonic(faucet.mnemonic, {prefix: faucet.prefix})
101
- const signer = await CheqdSigningStargateClient.connectWithSigner(exampleCheqdNetwork.rpcUrl, wallet)
105
+ const registry = createDefaultCheqdRegistry(DIDModule.registryTypes)
106
+ const signer = await CheqdSigningStargateClient.connectWithSigner(exampleCheqdNetwork.rpcUrl, wallet, { registry })
102
107
  const didModule = new DIDModule(signer)
103
108
 
104
109
  const keyPair = createKeyPairBase64()
@@ -2,7 +2,7 @@ import { VerificationMethod } from "@cheqd/ts-proto/cheqd/v1/did"
2
2
  import { MsgCreateDid, MsgCreateDidPayload, SignInfo } from "@cheqd/ts-proto/cheqd/v1/tx"
3
3
  import { DirectSecp256k1HdWallet, Registry } from "@cosmjs/proto-signing"
4
4
  import { base64ToBytes, EdDSASigner } from "did-jwt"
5
- import { typeUrlMsgCreateDid } from "../src/registry"
5
+ import { typeUrlMsgCreateDid } from '../src/modules/did'
6
6
  import { CheqdSigningStargateClient } from "../src/signer"
7
7
  import { ISignInputs, MethodSpecificIdAlgo, VerificationMethods } from "../src/types"
8
8
  import { fromString, toString } from 'uint8arrays'