Skip to content

Commit d4126a1

Browse files
committed
feat: Build esm and cjs using workspaces
1 parent 2dba14b commit d4126a1

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

45 files changed

+16130
-11822
lines changed

cjs/package.json

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
{
2+
"name": "@cheqd/sdk-cjs",
3+
"private": true,
4+
"version": "2.6.0",
5+
"description": "A TypeScript SDK built with CosmJS to interact with cheqd network ledger",
6+
"license": "Apache-2.0",
7+
"author": "Cheqd Foundation Limited (https://github.com/cheqd)",
8+
"exports": {
9+
".": {
10+
"types": "./build/types/index.d.ts",
11+
"require": "./build/index.js",
12+
"default": "./build/index.js"
13+
},
14+
"./*": {
15+
"types": "./build/types/*.d.ts",
16+
"require": "./build/*.js",
17+
"default": "./build/*.js"
18+
}
19+
},
20+
"scripts": {
21+
"test": "jest --colors --passWithNoTests --maxWorkers 1 --maxConcurrency 1",
22+
"test:watch": "jest --colors --passWithNoTests --maxWorkers 1 --maxConcurrency 1 --watch",
23+
"build": "npm run build:types && npm run build:cjs",
24+
"build:types": "tsc -p tsconfig.types.json",
25+
"build:cjs": "tsc -p tsconfig.json",
26+
"format": "prettier --write '**/*.{js,ts,cjs,mjs,json}'"
27+
},
28+
"dependencies": {
29+
"@cheqd/ts-proto": "^2.4.0",
30+
"@cosmjs/amino": "~0.30.1",
31+
"@cosmjs/crypto": "~0.30.1",
32+
"@cosmjs/encoding": "~0.30.1",
33+
"@cosmjs/math": "~0.30.1",
34+
"@cosmjs/proto-signing": "~0.30.1",
35+
"@cosmjs/stargate": "~0.30.1",
36+
"@cosmjs/tendermint-rpc": "~0.30.1",
37+
"@cosmjs/utils": "~0.30.1",
38+
"@stablelib/ed25519": "^1.0.3",
39+
"@types/secp256k1": "^4.0.6",
40+
"cosmjs-types": "^0.7.2",
41+
"did-jwt": "^8.0.4",
42+
"did-resolver": "^4.1.0",
43+
"file-type": "^16.5.4",
44+
"long": "^4.0.0",
45+
"multiformats": "^9.9.0",
46+
"secp256k1": "^5.0.0",
47+
"uuid": "^10.0.0"
48+
},
49+
"devDependencies": {
50+
"@types/node": "^18.19.47",
51+
"@types/uuid": "^10.0.0",
52+
"uint8arrays": "^3.1.1"
53+
},
54+
"engines": {
55+
"node": ">=18"
56+
}
57+
}

cjs/src/index.ts

Lines changed: 206 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,206 @@
1+
import { OfflineSigner, Registry } from '@cosmjs/proto-signing';
2+
import { DIDModule, MinimalImportableDIDModule, DidExtension } from './modules/did';
3+
import { MinimalImportableResourceModule, ResourceModule, ResourceExtension } from './modules/resource';
4+
import {
5+
AbstractCheqdSDKModule,
6+
applyMixins,
7+
instantiateCheqdSDKModule,
8+
instantiateCheqdSDKModuleRegistryTypes,
9+
instantiateCheqdSDKModuleQuerierExtensionSetup,
10+
} from './modules/_';
11+
import { createDefaultCheqdRegistry } from './registry';
12+
import { CheqdSigningStargateClient } from './signer';
13+
import { CheqdNetwork, IContext, IModuleMethodMap } from './types';
14+
import { GasPrice, QueryClient } from '@cosmjs/stargate';
15+
import { CheqdQuerier } from './querier';
16+
import { Tendermint37Client } from '@cosmjs/tendermint-rpc';
17+
import { FeemarketExtension, FeemarketModule } from './modules/feemarket';
18+
19+
export interface ICheqdSDKOptions {
20+
modules: AbstractCheqdSDKModule[];
21+
querierExtensions?: Record<string, any>[];
22+
rpcUrl: string;
23+
network?: CheqdNetwork;
24+
gasPrice?: GasPrice;
25+
authorizedMethods?: string[];
26+
readonly wallet: OfflineSigner;
27+
}
28+
29+
export type DefaultCheqdSDKModules = MinimalImportableDIDModule & MinimalImportableResourceModule;
30+
31+
export interface CheqdSDK extends DefaultCheqdSDKModules {}
32+
33+
export class CheqdSDK {
34+
methods: IModuleMethodMap;
35+
signer: CheqdSigningStargateClient;
36+
querier: CheqdQuerier & DidExtension & ResourceExtension & FeemarketExtension;
37+
options: ICheqdSDKOptions;
38+
private protectedMethods: string[] = ['constructor', 'build', 'loadModules', 'loadRegistry'];
39+
40+
constructor(options: ICheqdSDKOptions) {
41+
if (!options?.wallet) {
42+
throw new Error('No wallet provided');
43+
}
44+
45+
this.options = {
46+
authorizedMethods: [],
47+
network: CheqdNetwork.Testnet,
48+
...options,
49+
};
50+
51+
this.methods = {};
52+
this.signer = new CheqdSigningStargateClient(undefined, this.options.wallet, {});
53+
this.querier = <any>new QueryClient({} as unknown as Tendermint37Client);
54+
}
55+
56+
async execute<P = any, R = any>(method: string, ...params: P[]): Promise<R> {
57+
if (!Object.keys(this.methods).includes(method)) {
58+
throw new Error(`Method ${method} is not authorized`);
59+
}
60+
return await this.methods[method](...params, { sdk: this } as IContext);
61+
}
62+
63+
private async loadModules(modules: AbstractCheqdSDKModule[]): Promise<CheqdSDK> {
64+
this.options.modules = this.options.modules.map(
65+
(module: any) =>
66+
instantiateCheqdSDKModule(module, this.signer, this.querier, {
67+
sdk: this,
68+
} as IContext) as unknown as AbstractCheqdSDKModule
69+
);
70+
71+
const methods = applyMixins(this, modules);
72+
this.methods = {
73+
...this.methods,
74+
...filterUnauthorizedMethods(methods, this.options.authorizedMethods || [], this.protectedMethods),
75+
};
76+
77+
for (const method of Object.keys(this.methods)) {
78+
// @ts-ignore
79+
this[method] = async (...params: any[]) => {
80+
return await this.execute(method, ...params);
81+
};
82+
}
83+
84+
return this;
85+
}
86+
87+
private loadRegistry(): Registry {
88+
const registryTypes = this.options.modules
89+
.map((module: any) => instantiateCheqdSDKModuleRegistryTypes(module))
90+
.reduce((acc, types) => {
91+
return [...acc, ...types];
92+
});
93+
return createDefaultCheqdRegistry(registryTypes);
94+
}
95+
96+
private async loadQuerierExtensions(): Promise<
97+
CheqdQuerier & DidExtension & ResourceExtension & FeemarketExtension
98+
> {
99+
const querierExtensions = this.options.modules.map((module) =>
100+
instantiateCheqdSDKModuleQuerierExtensionSetup(module)
101+
);
102+
const querier = await CheqdQuerier.connectWithExtensions(this.options.rpcUrl, ...querierExtensions);
103+
return <CheqdQuerier & DidExtension & ResourceExtension & FeemarketExtension>querier;
104+
}
105+
106+
async build(): Promise<CheqdSDK> {
107+
const registry = this.loadRegistry();
108+
109+
this.querier = await this.loadQuerierExtensions();
110+
this.signer = await CheqdSigningStargateClient.connectWithSigner(this.options.rpcUrl, this.options.wallet, {
111+
registry,
112+
gasPrice: this.options?.gasPrice,
113+
});
114+
115+
return await this.loadModules(this.options.modules);
116+
}
117+
}
118+
119+
export function filterUnauthorizedMethods(
120+
methods: IModuleMethodMap,
121+
authorizedMethods: string[],
122+
protectedMethods: string[]
123+
): IModuleMethodMap {
124+
let _methods = Object.keys(methods);
125+
if (authorizedMethods.length === 0)
126+
return _methods
127+
.filter((method) => !protectedMethods.includes(method))
128+
.reduce((acc, method) => ({ ...acc, [method]: methods[method] }), {});
129+
130+
return _methods
131+
.filter((method) => authorizedMethods.includes(method) && !protectedMethods.includes(method))
132+
.reduce((acc, method) => ({ ...acc, [method]: methods[method] }), {});
133+
}
134+
135+
export async function createCheqdSDK(options: ICheqdSDKOptions): Promise<CheqdSDK> {
136+
return await new CheqdSDK(options).build();
137+
}
138+
139+
export { DIDModule, ResourceModule, FeemarketModule };
140+
export { AbstractCheqdSDKModule, applyMixins } from './modules/_';
141+
export {
142+
DidExtension,
143+
MinimalImportableDIDModule,
144+
MsgCreateDidDocEncodeObject,
145+
MsgCreateDidDocResponseEncodeObject,
146+
MsgUpdateDidDocEncodeObject,
147+
MsgUpdateDidDocResponseEncodeObject,
148+
MsgDeactivateDidDocEncodeObject,
149+
MsgDeactivateDidDocResponseEncodeObject,
150+
contexts,
151+
defaultDidExtensionKey,
152+
protobufLiterals as protobufLiteralsDid,
153+
typeUrlMsgCreateDidDoc,
154+
typeUrlMsgCreateDidDocResponse,
155+
typeUrlMsgUpdateDidDoc,
156+
typeUrlMsgUpdateDidDocResponse,
157+
typeUrlMsgDeactivateDidDoc,
158+
typeUrlMsgDeactivateDidDocResponse,
159+
setupDidExtension,
160+
isMsgCreateDidDocEncodeObject,
161+
isMsgUpdateDidDocEncodeObject,
162+
isMsgDeactivateDidDocEncodeObject,
163+
} from './modules/did';
164+
export {
165+
ResourceExtension,
166+
MinimalImportableResourceModule,
167+
defaultResourceExtensionKey,
168+
protobufLiterals as protobufLiteralsResource,
169+
typeUrlMsgCreateResource,
170+
typeUrlMsgCreateResourceResponse,
171+
setupResourceExtension,
172+
isMsgCreateResourceEncodeObject,
173+
} from './modules/resource';
174+
export {
175+
FeemarketExtension,
176+
MinimalImportableFeemarketModule,
177+
defaultFeemarketExtensionKey,
178+
protobufLiterals as protobufLiteralsFeemarket,
179+
typeUrlGasPriceResponse,
180+
typeUrlGasPricesResponse,
181+
typeUrlParamsResponse,
182+
setupFeemarketExtension,
183+
isGasPriceEncodeObject,
184+
isGasPricesEncodeObject,
185+
isParamsEncodeObject,
186+
} from './modules/feemarket';
187+
export * from './signer';
188+
export * from './querier';
189+
export * from './registry';
190+
export * from './types';
191+
export {
192+
TImportableEd25519Key,
193+
createKeyPairRaw,
194+
createKeyPairBase64,
195+
createKeyPairHex,
196+
createVerificationKeys,
197+
createDidVerificationMethod,
198+
createDidPayload,
199+
createSignInputsFromImportableEd25519Key,
200+
validateSpecCompliantPayload,
201+
isEqualKeyValuePair,
202+
createCosmosPayerWallet,
203+
getCosmosAccount,
204+
checkBalance,
205+
toMultibaseRaw,
206+
} from './utils';

cjs/src/modules/_.ts

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import { GeneratedType } from '@cosmjs/proto-signing';
2+
import { QueryClient } from '@cosmjs/stargate';
3+
import { CheqdSigningStargateClient } from '../signer';
4+
import { IModuleMethodMap, QueryExtensionSetup } from '../types';
5+
import { CheqdQuerier } from '../querier';
6+
7+
export abstract class AbstractCheqdSDKModule {
8+
_signer: CheqdSigningStargateClient;
9+
methods: IModuleMethodMap = {};
10+
querier: CheqdQuerier;
11+
readonly _protectedMethods: string[] = ['constructor', 'getRegistryTypes', 'getQuerierExtensionSetup'];
12+
static readonly registryTypes: Iterable<[string, GeneratedType]> = [];
13+
static readonly querierExtensionSetup: QueryExtensionSetup<any> = (base: QueryClient) => ({});
14+
15+
constructor(signer: CheqdSigningStargateClient, querier: CheqdQuerier) {
16+
if (!signer) {
17+
throw new Error('signer is required');
18+
}
19+
if (!querier) {
20+
throw new Error('querier is required');
21+
}
22+
this._signer = signer;
23+
this.querier = querier;
24+
}
25+
26+
abstract getRegistryTypes(): Iterable<[string, GeneratedType]>;
27+
}
28+
29+
type ProtectedMethods<T extends AbstractCheqdSDKModule, K extends keyof T> = T[K] extends string[]
30+
? T[K][number]
31+
: T[K];
32+
33+
export type MinimalImportableCheqdSDKModule<T extends AbstractCheqdSDKModule> = Omit<
34+
T,
35+
| '_signer'
36+
| '_protectedMethods'
37+
| 'registryTypes'
38+
| 'querierExtensionSetup'
39+
| 'getRegistryTypes'
40+
| 'getQuerierExtensionSetup'
41+
>;
42+
43+
export function instantiateCheqdSDKModule<T extends new (...args: any[]) => T>(
44+
module: T,
45+
...args: ConstructorParameters<T>
46+
): T {
47+
return new module(...args);
48+
}
49+
50+
export function instantiateCheqdSDKModuleRegistryTypes(module: any): Iterable<[string, GeneratedType]> {
51+
return module.registryTypes ?? [];
52+
}
53+
54+
export function instantiateCheqdSDKModuleQuerierExtensionSetup(module: any): QueryExtensionSetup<any> {
55+
return module.querierExtensionSetup ?? {};
56+
}
57+
58+
export function applyMixins(derivedCtor: any, constructors: any[]): IModuleMethodMap {
59+
let methods: IModuleMethodMap = {};
60+
61+
constructors.forEach((baseCtor) => {
62+
Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
63+
const property = baseCtor.prototype[name];
64+
if (
65+
typeof property !== 'function' ||
66+
derivedCtor.hasOwnProperty(name) ||
67+
derivedCtor?.protectedMethods.includes(name) ||
68+
baseCtor.prototype?._protectedMethods?.includes(name)
69+
)
70+
return;
71+
72+
methods = { ...methods, [name]: property };
73+
});
74+
});
75+
76+
return methods;
77+
}

0 commit comments

Comments
 (0)