@cheqd/sdk 2.1.0-develop.1 → 2.2.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.
Files changed (127) hide show
  1. package/README.md +33 -6
  2. package/build/{index.d.ts → cjs/index.d.ts} +8 -3
  3. package/build/cjs/index.d.ts.map +1 -0
  4. package/build/cjs/index.js +144 -0
  5. package/build/cjs/index.js.map +1 -0
  6. package/build/{modules → cjs/modules}/_.d.ts +1 -1
  7. package/build/cjs/modules/_.d.ts.map +1 -0
  8. package/build/{modules → cjs/modules}/_.js +3 -0
  9. package/build/cjs/modules/_.js.map +1 -0
  10. package/build/{modules → cjs/modules}/did.d.ts +4 -2
  11. package/build/cjs/modules/did.d.ts.map +1 -0
  12. package/build/{modules → cjs/modules}/did.js +42 -25
  13. package/build/cjs/modules/did.js.map +1 -0
  14. package/build/{modules → cjs/modules}/resource.d.ts +2 -2
  15. package/build/cjs/modules/resource.d.ts.map +1 -0
  16. package/build/{modules → cjs/modules}/resource.js +13 -5
  17. package/build/cjs/modules/resource.js.map +1 -0
  18. package/build/cjs/querier.d.ts.map +1 -0
  19. package/build/cjs/querier.js.map +1 -0
  20. package/build/cjs/registry.d.ts.map +1 -0
  21. package/build/cjs/registry.js.map +1 -0
  22. package/build/cjs/signer.d.ts.map +1 -0
  23. package/build/cjs/signer.js.map +1 -0
  24. package/build/{types.d.ts → cjs/types.d.ts} +1 -1
  25. package/build/cjs/types.d.ts.map +1 -0
  26. package/build/cjs/types.js.map +1 -0
  27. package/build/cjs/utils.d.ts.map +1 -0
  28. package/build/{utils.js → cjs/utils.js} +2 -5
  29. package/build/cjs/utils.js.map +1 -0
  30. package/build/types/index.d.ts +45 -0
  31. package/build/types/index.d.ts.map +1 -0
  32. package/build/types/modules/_.d.ts +20 -0
  33. package/build/types/modules/_.d.ts.map +1 -0
  34. package/build/types/modules/did.d.ts +109 -0
  35. package/build/types/modules/did.d.ts.map +1 -0
  36. package/build/types/modules/resource.d.ts +62 -0
  37. package/build/types/modules/resource.d.ts.map +1 -0
  38. package/build/types/querier.d.ts +11 -0
  39. package/build/types/querier.d.ts.map +1 -0
  40. package/build/types/registry.d.ts +4 -0
  41. package/build/types/registry.d.ts.map +1 -0
  42. package/build/types/signer.d.ts +36 -0
  43. package/build/types/signer.d.ts.map +1 -0
  44. package/build/types/types.d.ts +80 -0
  45. package/build/types/types.d.ts.map +1 -0
  46. package/build/types/utils.d.ts +18 -0
  47. package/build/types/utils.d.ts.map +1 -0
  48. package/package.json +48 -25
  49. package/.github/ISSUE_TEMPLATE/bug-report.yml +0 -74
  50. package/.github/ISSUE_TEMPLATE/config.yml +0 -14
  51. package/.github/ISSUE_TEMPLATE/feature-request.yaml +0 -27
  52. package/.github/dependabot.yml +0 -42
  53. package/.github/linters/.commitlint.rules.js +0 -37
  54. package/.github/linters/.eslintrc.json +0 -18
  55. package/.github/linters/.markdown-lint.yml +0 -139
  56. package/.github/linters/mlc_config.json +0 -13
  57. package/.github/workflows/build.yml +0 -30
  58. package/.github/workflows/cleanup-actions.yml +0 -45
  59. package/.github/workflows/cleanup-cache-automatic.yml +0 -24
  60. package/.github/workflows/cleanup-cache-manual.yml +0 -21
  61. package/.github/workflows/codeql.yml +0 -40
  62. package/.github/workflows/dispatch.yml +0 -30
  63. package/.github/workflows/lint.yml +0 -51
  64. package/.github/workflows/pull-request.yml +0 -33
  65. package/.github/workflows/release.yml +0 -42
  66. package/.github/workflows/test.yml +0 -66
  67. package/.releaserc.json +0 -56
  68. package/CHANGELOG.md +0 -256
  69. package/CODE_OF_CONDUCT.md +0 -81
  70. package/NOTICE.md +0 -10
  71. package/SECURITY.md +0 -12
  72. package/build/index.d.ts.map +0 -1
  73. package/build/index.js +0 -97
  74. package/build/index.js.map +0 -1
  75. package/build/modules/_.d.ts.map +0 -1
  76. package/build/modules/_.js.map +0 -1
  77. package/build/modules/did.d.ts.map +0 -1
  78. package/build/modules/did.js.map +0 -1
  79. package/build/modules/resource.d.ts.map +0 -1
  80. package/build/modules/resource.js.map +0 -1
  81. package/build/querier.d.ts.map +0 -1
  82. package/build/querier.js.map +0 -1
  83. package/build/registry.d.ts.map +0 -1
  84. package/build/registry.js.map +0 -1
  85. package/build/signer.d.ts.map +0 -1
  86. package/build/signer.js.map +0 -1
  87. package/build/types.d.ts.map +0 -1
  88. package/build/types.js.map +0 -1
  89. package/build/utils.d.ts.map +0 -1
  90. package/build/utils.js.map +0 -1
  91. package/docker/Dockerfile +0 -55
  92. package/docker/entrypoint.sh +0 -58
  93. package/docker/localnet/build-latest.env +0 -7
  94. package/docker/localnet/container-env/observer-0.env +0 -13
  95. package/docker/localnet/container-env/seed-0.env +0 -17
  96. package/docker/localnet/container-env/validator-0.env +0 -13
  97. package/docker/localnet/container-env/validator-1.env +0 -13
  98. package/docker/localnet/container-env/validator-2.env +0 -13
  99. package/docker/localnet/container-env/validator-3.env +0 -13
  100. package/docker/localnet/docker-compose.yml +0 -281
  101. package/docker/localnet/gen-network-config.sh +0 -259
  102. package/docker/localnet/import-keys.sh +0 -31
  103. package/jest.config.js +0 -6
  104. package/src/index.ts +0 -128
  105. package/src/modules/_.ts +0 -55
  106. package/src/modules/did.ts +0 -564
  107. package/src/modules/resource.ts +0 -213
  108. package/src/querier.ts +0 -33
  109. package/src/registry.ts +0 -15
  110. package/src/signer.ts +0 -258
  111. package/src/types.ts +0 -101
  112. package/src/utils.ts +0 -243
  113. package/tests/index.test.ts +0 -135
  114. package/tests/modules/did.test.ts +0 -965
  115. package/tests/modules/resource.test.ts +0 -785
  116. package/tests/signer.test.ts +0 -179
  117. package/tests/testutils.test.ts +0 -24
  118. package/tests/utils.test.ts +0 -66
  119. package/tsconfig.json +0 -80
  120. /package/build/{querier.d.ts → cjs/querier.d.ts} +0 -0
  121. /package/build/{querier.js → cjs/querier.js} +0 -0
  122. /package/build/{registry.d.ts → cjs/registry.d.ts} +0 -0
  123. /package/build/{registry.js → cjs/registry.js} +0 -0
  124. /package/build/{signer.d.ts → cjs/signer.d.ts} +0 -0
  125. /package/build/{signer.js → cjs/signer.js} +0 -0
  126. /package/build/{types.js → cjs/types.js} +0 -0
  127. /package/build/{utils.d.ts → cjs/utils.d.ts} +0 -0
@@ -1,213 +0,0 @@
1
- import { AbstractCheqdSDKModule, MinimalImportableCheqdSDKModule } from './_';
2
- import { CheqdSigningStargateClient } from "../signer"
3
- import { EncodeObject, GeneratedType } from "@cosmjs/proto-signing"
4
- import { DidStdFee, IContext, ISignInputs, QueryExtensionSetup } from '../types';
5
- import { Metadata, MsgCreateResource, MsgCreateResourcePayload, MsgCreateResourceResponse, QueryClientImpl, QueryCollectionResourcesResponse, ResourceWithMetadata, protobufPackage } from "@cheqd/ts-proto/cheqd/resource/v2"
6
- import { DeliverTxResponse, QueryClient, createPagination, createProtobufRpcClient } from "@cosmjs/stargate"
7
- import { SignInfo } from "@cheqd/ts-proto/cheqd/did/v2";
8
- import { fromBuffer } from "file-type";
9
- import { assert } from '@cosmjs/utils';
10
- import { PageRequest } from '@cheqd/ts-proto/cosmos/base/query/v1beta1/pagination';
11
- import { CheqdQuerier } from '../querier';
12
-
13
- export const defaultResourceExtensionKey = 'resource' as const
14
-
15
- export const protobufLiterals = {
16
- MsgCreateResource: 'MsgCreateResource',
17
- MsgCreateResourceResponse: 'MsgCreateResourceResponse'
18
- } as const
19
-
20
- export const typeUrlMsgCreateResource = `/${protobufPackage}.${protobufLiterals.MsgCreateResource}`
21
- export const typeUrlMsgCreateResourceResponse = `/${protobufPackage}.${protobufLiterals.MsgCreateResourceResponse}`
22
-
23
- export interface MsgCreateResourceEncodeObject extends EncodeObject {
24
- readonly typeUrl: typeof typeUrlMsgCreateResource,
25
- readonly value: Partial<MsgCreateResource>
26
- }
27
-
28
- export function isMsgCreateResourceEncodeObject(obj: EncodeObject): obj is MsgCreateResourceEncodeObject {
29
- return obj.typeUrl === typeUrlMsgCreateResource
30
- }
31
-
32
- export type MinimalImportableResourceModule = MinimalImportableCheqdSDKModule<ResourceModule>
33
-
34
- export type ResourceExtension = {
35
- readonly [defaultResourceExtensionKey]: {
36
- readonly resource: (collectionId: string, resourceId: string) => Promise<ResourceWithMetadata>
37
- readonly resourceMetadata: (collectionId: string, resourceId: string) => Promise<Metadata>
38
- readonly collectionResources: (collectionId: string, paginationKey?: Uint8Array) => Promise<QueryCollectionResourcesResponse>
39
- }
40
- }
41
-
42
- export const setupResourceExtension = (base: QueryClient): ResourceExtension => {
43
- const rpc = createProtobufRpcClient(base)
44
-
45
- const queryService = new QueryClientImpl(rpc)
46
-
47
- return {
48
- [defaultResourceExtensionKey]: {
49
- resource: async (collectionId: string, resourceId: string) => {
50
- const { resource } = await queryService.Resource({ collectionId, id: resourceId })
51
- assert(resource)
52
- return resource
53
- },
54
- resourceMetadata: async (collectionId: string, resourceId: string) => {
55
- const { resource } = await queryService.ResourceMetadata({ collectionId, id: resourceId })
56
- assert(resource)
57
- return resource
58
- },
59
- collectionResources: async (collectionId: string, paginationKey?: Uint8Array) => {
60
- const response = await queryService.CollectionResources({ collectionId, pagination: createPagination(paginationKey) as PageRequest | undefined })
61
- return response
62
- }
63
- }
64
- } as ResourceExtension
65
- }
66
-
67
- export class ResourceModule extends AbstractCheqdSDKModule {
68
- static readonly registryTypes: Iterable<[string, GeneratedType]> = [
69
- [typeUrlMsgCreateResource, MsgCreateResource],
70
- [typeUrlMsgCreateResourceResponse, MsgCreateResourceResponse]
71
- ]
72
-
73
- static readonly baseMinimalDenom = 'ncheq' as const
74
-
75
- static readonly fees = {
76
- DefaultCreateResourceImageFee: { amount: '10000000000', denom: ResourceModule.baseMinimalDenom } as const,
77
- DefaultCreateResourceJsonFee: { amount: '2500000000', denom: ResourceModule.baseMinimalDenom } as const,
78
- DefaultCreateResourceDefaultFee: { amount: '5000000000', denom: ResourceModule.baseMinimalDenom } as const,
79
- } as const
80
-
81
- static readonly querierExtensionSetup: QueryExtensionSetup<ResourceExtension> = setupResourceExtension
82
-
83
- readonly querier: CheqdQuerier & ResourceExtension
84
-
85
- constructor(signer: CheqdSigningStargateClient, querier: CheqdQuerier & ResourceExtension) {
86
- super(signer, querier)
87
- this.querier = querier
88
- this.methods = {
89
- createLinkedResourceTx: this.createLinkedResourceTx.bind(this),
90
- queryLinkedResource: this.queryLinkedResource.bind(this),
91
- queryLinkedResourceMetadata: this.queryLinkedResourceMetadata.bind(this),
92
- queryLinkedResources: this.queryLinkedResources.bind(this),
93
- }
94
- }
95
-
96
- public getRegistryTypes(): Iterable<[string, GeneratedType]> {
97
- return ResourceModule.registryTypes
98
- }
99
-
100
- public getQuerierExtensionSetup(): QueryExtensionSetup<ResourceExtension> {
101
- return ResourceModule.querierExtensionSetup
102
- }
103
-
104
- static async signPayload(payload: MsgCreateResourcePayload, signInputs: ISignInputs[] | SignInfo[]): Promise<MsgCreateResource> {
105
- const signBytes = MsgCreateResourcePayload.encode(payload).finish()
106
- let signatures: SignInfo[]
107
- if(ISignInputs.isSignInput(signInputs)) {
108
- signatures = await CheqdSigningStargateClient.signIdentityTx(signBytes, signInputs)
109
- } else {
110
- signatures = signInputs
111
- }
112
-
113
- return {
114
- payload,
115
- signatures
116
- }
117
- }
118
-
119
- async createLinkedResourceTx(signInputs: ISignInputs[] | SignInfo[], resourcePayload: Partial<MsgCreateResourcePayload>, address: string, fee?: DidStdFee | 'auto' | number, memo?: string, context?: IContext): Promise<DeliverTxResponse> {
120
- if (!this._signer) {
121
- this._signer = context!.sdk!.signer
122
- }
123
-
124
- const payload = MsgCreateResourcePayload.fromPartial(resourcePayload)
125
-
126
- const msg = await ResourceModule.signPayload(payload, signInputs)
127
-
128
- const encObj: MsgCreateResourceEncodeObject = {
129
- typeUrl: typeUrlMsgCreateResource,
130
- value: msg
131
- }
132
-
133
- if (address === '') {
134
- address = (await context!.sdk!.options.wallet.getAccounts())[0].address
135
- }
136
-
137
- if (!fee) {
138
- if (payload.data.length === 0) {
139
- throw new Error('Linked resource data is empty')
140
- }
141
-
142
- fee = await async function() {
143
- const mimeType = await ResourceModule.readMimeType(payload.data)
144
-
145
- if (mimeType.startsWith('image/')) {
146
- return await ResourceModule.generateCreateResourceImageFees(address)
147
- }
148
-
149
- if (mimeType.startsWith('application/json')) {
150
- return await ResourceModule.generateCreateResourceJsonFees(address)
151
- }
152
-
153
- return await ResourceModule.generateCreateResourceDefaultFees(address)
154
- }()
155
- }
156
-
157
- return this._signer.signAndBroadcast(
158
- address,
159
- [encObj],
160
- fee!,
161
- memo
162
- )
163
- }
164
-
165
- async queryLinkedResource(collectionId: string, resourceId: string, context?: IContext): Promise<ResourceWithMetadata> {
166
- return await this.querier[defaultResourceExtensionKey].resource(collectionId, resourceId)
167
- }
168
-
169
- async queryLinkedResourceMetadata(collectionId: string, resourceId: string, context?: IContext): Promise<Metadata> {
170
- return await this.querier[defaultResourceExtensionKey].resourceMetadata(collectionId, resourceId)
171
- }
172
-
173
- async queryLinkedResources(collectionId: string, context?: IContext): Promise<QueryCollectionResourcesResponse> {
174
- return await this.querier[defaultResourceExtensionKey].collectionResources(collectionId)
175
- }
176
-
177
- static async readMimeType(content: Uint8Array): Promise<string> {
178
- return (await fromBuffer(content))?.mime ?? 'application/octet-stream'
179
- }
180
-
181
- static async generateCreateResourceImageFees(feePayer: string, granter?: string): Promise<DidStdFee> {
182
- return {
183
- amount: [
184
- ResourceModule.fees.DefaultCreateResourceImageFee
185
- ],
186
- gas: '360000',
187
- payer: feePayer,
188
- granter: granter
189
- } as DidStdFee
190
- }
191
-
192
- static async generateCreateResourceJsonFees(feePayer: string, granter?: string): Promise<DidStdFee> {
193
- return {
194
- amount: [
195
- ResourceModule.fees.DefaultCreateResourceJsonFee
196
- ],
197
- gas: '360000',
198
- payer: feePayer,
199
- granter: granter
200
- } as DidStdFee
201
- }
202
-
203
- static async generateCreateResourceDefaultFees(feePayer: string, granter?: string): Promise<DidStdFee> {
204
- return {
205
- amount: [
206
- ResourceModule.fees.DefaultCreateResourceDefaultFee
207
- ],
208
- gas: '360000',
209
- payer: feePayer,
210
- granter: granter
211
- } as DidStdFee
212
- }
213
- }
package/src/querier.ts DELETED
@@ -1,33 +0,0 @@
1
- import { QueryClient } from "@cosmjs/stargate";
2
- import { Tendermint34Client } from "@cosmjs/tendermint-rpc";
3
- import { QueryExtensionSetup, CheqdExtensions } from "./types";
4
-
5
- export class CheqdQuerier extends QueryClient {
6
- constructor(tmClient: Tendermint34Client) {
7
- super(tmClient)
8
- }
9
-
10
- static async connect(url: string): Promise<CheqdQuerier> {
11
- const tmClient = await Tendermint34Client.connect(url);
12
- return new CheqdQuerier(tmClient);
13
- }
14
-
15
- static async fromClient(client: Tendermint34Client): Promise<CheqdQuerier> {
16
- return new CheqdQuerier(client);
17
- }
18
-
19
- static async connectWithExtension(url: string, extension: QueryExtensionSetup<CheqdExtensions>): Promise<CheqdQuerier & CheqdExtensions> {
20
- const tmClient = await Tendermint34Client.connect(url);
21
- return CheqdQuerier.withExtensions(tmClient, extension);
22
- }
23
-
24
- static async connectWithExtensions(url: string, ...extensions: QueryExtensionSetup<CheqdExtensions>[]): Promise<CheqdQuerier & CheqdExtensions> {
25
- if (extensions.length === 1) {
26
- return CheqdQuerier.connectWithExtension(url, extensions[0]);
27
- }
28
-
29
- const tmClient = await Tendermint34Client.connect(url);
30
- const tupleLike = extensions as [QueryExtensionSetup<CheqdExtensions>, QueryExtensionSetup<CheqdExtensions>];
31
- return CheqdQuerier.withExtensions(tmClient, ...tupleLike);
32
- }
33
- }
package/src/registry.ts DELETED
@@ -1,15 +0,0 @@
1
- import {
2
- Registry,
3
- GeneratedType,
4
- } from '@cosmjs/proto-signing'
5
-
6
- import {
7
- defaultRegistryTypes
8
- } from '@cosmjs/stargate'
9
-
10
- export function createDefaultCheqdRegistry(customTypes?: Iterable<[string, GeneratedType]>): Registry {
11
- if (!customTypes) customTypes = [];
12
- return new Registry([...defaultRegistryTypes, ...customTypes])
13
- }
14
-
15
- export const CheqdRegistry = new Registry(defaultRegistryTypes)
package/src/signer.ts DELETED
@@ -1,258 +0,0 @@
1
- import { EncodeObject, isOfflineDirectSigner, OfflineSigner, encodePubkey, TxBodyEncodeObject, makeSignDoc } from "@cosmjs/proto-signing"
2
- import { DeliverTxResponse, GasPrice, HttpEndpoint, SigningStargateClient, SigningStargateClientOptions, calculateFee, SignerData } from "@cosmjs/stargate"
3
- import { Tendermint34Client } from "@cosmjs/tendermint-rpc"
4
- import { createDefaultCheqdRegistry } from "./registry"
5
- import { MsgCreateDidDocPayload, SignInfo, MsgUpdateDidDocPayload, MsgDeactivateDidDocPayload, VerificationMethod } from '@cheqd/ts-proto/cheqd/did/v2';
6
- import { DidStdFee, ISignInputs, TSignerAlgo, VerificationMethods } from './types';
7
- import { base64ToBytes, EdDSASigner, hexToBytes, Signer, ES256Signer, ES256KSigner } from 'did-jwt';
8
- import { assert, assertDefined } from '@cosmjs/utils'
9
- import { encodeSecp256k1Pubkey } from '@cosmjs/amino'
10
- import { Int53 } from '@cosmjs/math'
11
- import { fromBase64 } from '@cosmjs/encoding'
12
- import { AuthInfo, SignerInfo, TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx'
13
- import { SignMode } from 'cosmjs-types/cosmos/tx/signing/v1beta1/signing'
14
- import { Any } from 'cosmjs-types/google/protobuf/any'
15
- import { Coin } from 'cosmjs-types/cosmos/base/v1beta1/coin'
16
- import Long from 'long'
17
-
18
- export function calculateDidFee(gasLimit: number, gasPrice: string | GasPrice): DidStdFee {
19
- return calculateFee(gasLimit, gasPrice)
20
- }
21
-
22
- export function makeSignerInfos(
23
- signers: ReadonlyArray<{ readonly pubkey: Any; readonly sequence: number }>,
24
- signMode: SignMode,
25
- ): SignerInfo[] {
26
- return signers.map(
27
- ({ pubkey, sequence }): SignerInfo => ({
28
- publicKey: pubkey,
29
- modeInfo: {
30
- single: { mode: signMode },
31
- },
32
- sequence: Long.fromNumber(sequence),
33
- }),
34
- );
35
- }
36
-
37
- export function makeDidAuthInfoBytes(
38
- signers: ReadonlyArray<{ readonly pubkey: Any; readonly sequence: number }>,
39
- feeAmount: readonly Coin[],
40
- gasLimit: number,
41
- feePayer: string,
42
- signMode = SignMode.SIGN_MODE_DIRECT,
43
- ): Uint8Array {
44
- const authInfo = {
45
- signerInfos: makeSignerInfos(signers, signMode),
46
- fee: {
47
- amount: [...feeAmount],
48
- gasLimit: Long.fromNumber(gasLimit),
49
- payer: feePayer
50
- }
51
- }
52
- return AuthInfo.encode(AuthInfo.fromPartial(authInfo)).finish()
53
- }
54
-
55
- export class CheqdSigningStargateClient extends SigningStargateClient {
56
- private didSigners: TSignerAlgo = {}
57
- private readonly _gasPrice: GasPrice | undefined
58
- private readonly _signer: OfflineSigner
59
-
60
- public static async connectWithSigner(endpoint: string | HttpEndpoint, signer: OfflineSigner, options?: SigningStargateClientOptions | undefined): Promise<CheqdSigningStargateClient> {
61
- const tmClient = await Tendermint34Client.connect(endpoint)
62
- return new CheqdSigningStargateClient(tmClient, signer, {
63
- registry: options?.registry ? options.registry : createDefaultCheqdRegistry(),
64
- ...options
65
- })
66
- }
67
-
68
- constructor(
69
- tmClient: Tendermint34Client | undefined,
70
- signer: OfflineSigner,
71
- options: SigningStargateClientOptions = {}
72
- ) {
73
- super(tmClient, signer, options)
74
- this._signer = signer
75
- if (options.gasPrice) this._gasPrice = options.gasPrice
76
- }
77
-
78
- async signAndBroadcast(
79
- signerAddress: string,
80
- messages: readonly EncodeObject[],
81
- fee: DidStdFee | "auto" | number,
82
- memo = "",
83
- ): Promise<DeliverTxResponse> {
84
- let usedFee: DidStdFee
85
- if (fee == "auto" || typeof fee === "number") {
86
- assertDefined(this._gasPrice, "Gas price must be set in the client options when auto gas is used.")
87
- const gasEstimation = await this.simulate(signerAddress, messages, memo)
88
- const multiplier = typeof fee === "number" ? fee : 1.3
89
- usedFee = calculateDidFee(Math.round(gasEstimation * multiplier), this._gasPrice)
90
- usedFee.payer = signerAddress
91
- } else {
92
- usedFee = fee
93
- assertDefined(usedFee.payer, "Payer address must be set when fee is not auto.")
94
- signerAddress = usedFee.payer!
95
- }
96
- const txRaw = await this.sign(signerAddress, messages, usedFee, memo)
97
- const txBytes = TxRaw.encode(txRaw).finish()
98
- return this.broadcastTx(txBytes, this.broadcastTimeoutMs, this.broadcastPollIntervalMs)
99
- }
100
-
101
- public async sign(
102
- signerAddress: string,
103
- messages: readonly EncodeObject[],
104
- fee: DidStdFee,
105
- memo: string,
106
- explicitSignerData?: SignerData,
107
- ): Promise<TxRaw> {
108
- let signerData: SignerData
109
- if (explicitSignerData) {
110
- signerData = explicitSignerData
111
- } else {
112
- const { accountNumber, sequence } = await this.getSequence(signerAddress)
113
- const chainId = await this.getChainId()
114
- signerData = {
115
- accountNumber: accountNumber,
116
- sequence: sequence,
117
- chainId: chainId,
118
- }
119
- }
120
-
121
- return this._signDirect(signerAddress, messages, fee, memo, signerData)
122
- }
123
-
124
- private async _signDirect(
125
- signerAddress: string,
126
- messages: readonly EncodeObject[],
127
- fee: DidStdFee,
128
- memo: string,
129
- { accountNumber, sequence, chainId }: SignerData,
130
- ): Promise<TxRaw> {
131
- assert(isOfflineDirectSigner(this._signer))
132
- const accountFromSigner = (await this._signer.getAccounts()).find(
133
- (account) => account.address === signerAddress,
134
- )
135
- if (!accountFromSigner) {
136
- throw new Error("Failed to retrieve account from signer")
137
- }
138
- const pubkey = encodePubkey(encodeSecp256k1Pubkey(accountFromSigner.pubkey))
139
- const txBodyEncodeObject: TxBodyEncodeObject = {
140
- typeUrl: "/cosmos.tx.v1beta1.TxBody",
141
- value: {
142
- messages: messages,
143
- memo: memo,
144
- },
145
- }
146
- const txBodyBytes = this.registry.encode(txBodyEncodeObject)
147
- const gasLimit = Int53.fromString(fee.gas).toNumber()
148
- const authInfoBytes = makeDidAuthInfoBytes([{ pubkey, sequence }], fee.amount, gasLimit, fee.payer!)
149
- const signDoc = makeSignDoc(txBodyBytes, authInfoBytes, chainId, accountNumber)
150
- const { signature, signed } = await this._signer.signDirect(signerAddress, signDoc)
151
- return TxRaw.fromPartial({
152
- bodyBytes: signed.bodyBytes,
153
- authInfoBytes: signed.authInfoBytes,
154
- signatures: [fromBase64(signature.signature)],
155
- })
156
- }
157
-
158
- async checkDidSigners(verificationMethods: Partial<VerificationMethod>[] = []): Promise<TSignerAlgo> {
159
- if (verificationMethods.length === 0) {
160
- throw new Error('No verification methods provided')
161
- }
162
-
163
- verificationMethods.forEach((verificationMethod) => {
164
- if (!(Object.values(VerificationMethods) as string[]).includes(verificationMethod.verificationMethodType ?? '')) {
165
- throw new Error(`Unsupported verification method type: ${verificationMethod.verificationMethodType}`)
166
- }
167
- if (!this.didSigners[verificationMethod.verificationMethodType ?? '']) {
168
- this.didSigners[verificationMethod.verificationMethodType ?? ''] = EdDSASigner
169
- }
170
- })
171
-
172
- return this.didSigners
173
- }
174
-
175
- async getDidSigner(verificationMethodId: string, verificationMethods: Partial<VerificationMethod>[]): Promise<(secretKey: Uint8Array) => Signer> {
176
- await this.checkDidSigners(verificationMethods)
177
- const verificationMethod = verificationMethods.find(method => method.id === verificationMethodId)?.verificationMethodType
178
- if (!verificationMethod) {
179
- throw new Error(`Verification method for ${verificationMethodId} not found`)
180
- }
181
- return this.didSigners[verificationMethod]!
182
- }
183
-
184
- async signcreateDidDocTx(signInputs: ISignInputs[], payload: MsgCreateDidDocPayload): Promise<SignInfo[]> {
185
- await this.checkDidSigners(payload?.verificationMethod)
186
-
187
- const signBytes = MsgCreateDidDocPayload.encode(payload).finish()
188
- const signInfos: SignInfo[] = await Promise.all(signInputs.map(async (signInput) => {
189
- return {
190
- verificationMethodId: signInput.verificationMethodId,
191
- signature: base64ToBytes((await (await this.getDidSigner(signInput.verificationMethodId, payload.verificationMethod))(hexToBytes(signInput.privateKeyHex))(signBytes)) as string)
192
- }
193
- }))
194
-
195
- return signInfos
196
- }
197
-
198
- async signupdateDidDocTx(signInputs: ISignInputs[], payload: MsgUpdateDidDocPayload): Promise<SignInfo[]> {
199
- await this.checkDidSigners(payload?.verificationMethod)
200
-
201
- const signBytes = MsgUpdateDidDocPayload.encode(payload).finish()
202
- const signInfos: SignInfo[] = await Promise.all(signInputs.map(async (signInput) => {
203
- return {
204
- verificationMethodId: signInput.verificationMethodId,
205
- signature: base64ToBytes((await (await this.getDidSigner(signInput.verificationMethodId, payload.verificationMethod))(hexToBytes(signInput.privateKeyHex))(signBytes)) as string)
206
- }
207
- }))
208
-
209
- return signInfos
210
- }
211
-
212
- async signdeactivateDidDocTx(signInputs: ISignInputs[], payload: MsgDeactivateDidDocPayload, verificationMethod: VerificationMethod[]): Promise<SignInfo[]> {
213
- await this.checkDidSigners(verificationMethod)
214
-
215
- const signBytes = MsgDeactivateDidDocPayload.encode(payload).finish()
216
- const signInfos: SignInfo[] = await Promise.all(signInputs.map(async (signInput) => {
217
- return {
218
- verificationMethodId: signInput.verificationMethodId,
219
- signature: base64ToBytes((await (await this.getDidSigner(signInput.verificationMethodId, verificationMethod))(hexToBytes(signInput.privateKeyHex))(signBytes)) as string)
220
- }
221
- }))
222
-
223
- return signInfos
224
- }
225
-
226
- static async signIdentityTx(signBytes: Uint8Array, signInputs: ISignInputs[]): Promise<SignInfo[]> {
227
- let signInfos: SignInfo[] = [];
228
-
229
- for (let signInput of signInputs) {
230
- if (typeof(signInput.keyType) === undefined) {
231
- throw new Error('Key type is not defined')
232
- }
233
-
234
- let signature: string;
235
-
236
- switch (signInput.keyType) {
237
- case 'Ed25519':
238
- signature = (await EdDSASigner(hexToBytes(signInput.privateKeyHex))(signBytes)) as string;
239
- break;
240
- case 'Secp256k1':
241
- signature = (await ES256KSigner(hexToBytes(signInput.privateKeyHex))(signBytes)) as string;
242
- break;
243
- case 'P256':
244
- signature = (await ES256Signer(hexToBytes(signInput.privateKeyHex))(signBytes)) as string;
245
- break;
246
- default:
247
- throw new Error(`Unsupported signature type: ${signInput.keyType}`);
248
- }
249
-
250
- signInfos.push({
251
- verificationMethodId: signInput.verificationMethodId,
252
- signature: base64ToBytes(signature)
253
- });
254
- }
255
-
256
- return signInfos
257
- }
258
- }
package/src/types.ts DELETED
@@ -1,101 +0,0 @@
1
- import { Service as ProtobufService, VerificationMethod as ProtobufVerificationMethod } from "@cheqd/ts-proto/cheqd/did/v2"
2
- import { CheqdSDK } from "."
3
- import { Coin } from "@cosmjs/proto-signing"
4
- import { Signer } from "did-jwt"
5
- import { QueryClient } from "@cosmjs/stargate"
6
- import { DIDResolutionResult } from "did-resolver"
7
- import { DidExtension } from "./modules/did"
8
- import { ResourceExtension } from './modules/resource';
9
- export { DIDDocument, VerificationMethod, Service, ServiceEndpoint, JsonWebKey } from "did-resolver"
10
-
11
- export enum CheqdNetwork {
12
- Mainnet = 'mainnet',
13
- Testnet = 'testnet',
14
- }
15
-
16
- export type QueryExtensionSetup<T> = (base: QueryClient) => T
17
-
18
- export type CheqdExtension<K extends string, V = any> = {
19
- [P in K]: (Record<P, V> & Partial<Record<Exclude<K, P>, never>>) extends infer O
20
- ? { [Q in keyof O]: O[Q] }
21
- : never
22
- }[K]
23
-
24
- export type CheqdExtensions = DidExtension | ResourceExtension
25
-
26
- export interface IModuleMethod {
27
- (...args: any[]): Promise<any>
28
- }
29
-
30
- export interface IModuleMethodMap extends Record<string, IModuleMethod> {}
31
-
32
- export interface IContext {
33
- sdk: CheqdSDK
34
- }
35
-
36
- export type DIDDocumentWithMetadata = Pick<DIDResolutionResult, 'didDocument' | 'didDocumentMetadata'>
37
-
38
- export type SpecValidationResult = {
39
- valid: boolean
40
- error?: string
41
- protobufVerificationMethod?: ProtobufVerificationMethod[]
42
- protobufService?: ProtobufService[]
43
- }
44
-
45
- export enum VerificationMethods {
46
- Ed255192020 = 'Ed25519VerificationKey2020',
47
- Ed255192018 = 'Ed25519VerificationKey2018',
48
- JWK = 'JsonWebKey2020',
49
- }
50
-
51
- export enum MethodSpecificIdAlgo {
52
- Base58 = 'base58btc',
53
- Uuid = 'uuid',
54
- }
55
-
56
- export type TSignerAlgo = {
57
- [key in VerificationMethods as string]?: (secretKey: Uint8Array) => Signer
58
- }
59
-
60
- export interface ISignInputs {
61
- verificationMethodId: string
62
- keyType?: 'Ed25519' | 'Secp256k1' | 'P256'
63
- privateKeyHex: string
64
- }
65
-
66
- export interface IKeyPair {
67
- publicKey: string
68
- privateKey: string
69
- algo?: MethodSpecificIdAlgo
70
- }
71
-
72
- export interface IKeyValuePair {
73
- key: string
74
- value: any
75
- }
76
-
77
- export type TVerificationKeyPrefix = string
78
-
79
- export type TVerificationKey<K extends TVerificationKeyPrefix, N extends number> = `${K}-${N}`
80
-
81
- export interface IVerificationKeys {
82
- readonly methodSpecificId: TMethodSpecificId
83
- readonly didUrl: `did:cheqd:${CheqdNetwork}:${IVerificationKeys['methodSpecificId']}` extends string ? string : never
84
- readonly keyId: `${IVerificationKeys['didUrl']}#${TVerificationKey<TVerificationKeyPrefix, number>}`
85
- readonly publicKey: string
86
- }
87
-
88
- export type TMethodSpecificId = string
89
-
90
- export interface DidStdFee {
91
- readonly amount: readonly Coin[]
92
- readonly gas: string
93
- payer?: string
94
- granter?: string
95
- }
96
-
97
- export const ISignInputs = {
98
- isSignInput(object: Object[]): object is ISignInputs[] {
99
- return object.some((x)=> 'privateKeyHex' in x)
100
- }
101
- }