UNPKG

@daevm/cheqd-sdk

Version:

A TypeScript SDK built with CosmJS to interact with cheqd network ledger

207 lines 10.2 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.CheqdSigningStargateClient = exports.makeDidAuthInfoBytes = exports.makeSignerInfos = exports.calculateDidFee = void 0; const proto_signing_1 = require("@cosmjs/proto-signing"); const stargate_1 = require("@cosmjs/stargate"); const tendermint_rpc_1 = require("@cosmjs/tendermint-rpc"); const registry_1 = require("./registry"); const v2_1 = require("@cheqd/ts-proto/cheqd/did/v2"); const types_1 = require("./types"); const did_jwt_1 = require("did-jwt"); const utils_1 = require("@cosmjs/utils"); const amino_1 = require("@cosmjs/amino"); const math_1 = require("@cosmjs/math"); const encoding_1 = require("@cosmjs/encoding"); const tx_1 = require("cosmjs-types/cosmos/tx/v1beta1/tx"); const signing_1 = require("cosmjs-types/cosmos/tx/signing/v1beta1/signing"); const long_1 = __importDefault(require("long")); function calculateDidFee(gasLimit, gasPrice) { return (0, stargate_1.calculateFee)(gasLimit, gasPrice); } exports.calculateDidFee = calculateDidFee; function makeSignerInfos(signers, signMode) { return signers.map(({ pubkey, sequence }) => ({ publicKey: pubkey, modeInfo: { single: { mode: signMode }, }, sequence: long_1.default.fromNumber(sequence), })); } exports.makeSignerInfos = makeSignerInfos; function makeDidAuthInfoBytes(signers, feeAmount, gasLimit, feePayer, signMode = signing_1.SignMode.SIGN_MODE_DIRECT) { const authInfo = { signerInfos: makeSignerInfos(signers, signMode), fee: { amount: [...feeAmount], gasLimit: long_1.default.fromNumber(gasLimit), payer: feePayer } }; return tx_1.AuthInfo.encode(tx_1.AuthInfo.fromPartial(authInfo)).finish(); } exports.makeDidAuthInfoBytes = makeDidAuthInfoBytes; class CheqdSigningStargateClient extends stargate_1.SigningStargateClient { didSigners = {}; _gasPrice; _signer; static async connectWithSigner(endpoint, signer, options) { const tmClient = await tendermint_rpc_1.Tendermint34Client.connect(endpoint); return new CheqdSigningStargateClient(tmClient, signer, { registry: options?.registry ? options.registry : (0, registry_1.createDefaultCheqdRegistry)(), ...options }); } constructor(tmClient, signer, options = {}) { super(tmClient, signer, options); this._signer = signer; if (options.gasPrice) this._gasPrice = options.gasPrice; } async signAndBroadcast(signerAddress, messages, fee, memo = "") { let usedFee; if (fee == "auto" || typeof fee === "number") { (0, utils_1.assertDefined)(this._gasPrice, "Gas price must be set in the client options when auto gas is used."); const gasEstimation = await this.simulate(signerAddress, messages, memo); const multiplier = typeof fee === "number" ? fee : 1.3; usedFee = calculateDidFee(Math.round(gasEstimation * multiplier), this._gasPrice); usedFee.payer = signerAddress; } else { usedFee = fee; (0, utils_1.assertDefined)(usedFee.payer, "Payer address must be set when fee is not auto."); signerAddress = usedFee.payer; } const txRaw = await this.sign(signerAddress, messages, usedFee, memo); const txBytes = tx_1.TxRaw.encode(txRaw).finish(); return this.broadcastTx(txBytes, this.broadcastTimeoutMs, this.broadcastPollIntervalMs); } async sign(signerAddress, messages, fee, memo, explicitSignerData) { let signerData; if (explicitSignerData) { signerData = explicitSignerData; } else { const { accountNumber, sequence } = await this.getSequence(signerAddress); const chainId = await this.getChainId(); signerData = { accountNumber: accountNumber, sequence: sequence, chainId: chainId, }; } return this._signDirect(signerAddress, messages, fee, memo, signerData); } async _signDirect(signerAddress, messages, fee, memo, { accountNumber, sequence, chainId }) { (0, utils_1.assert)((0, proto_signing_1.isOfflineDirectSigner)(this._signer)); const accountFromSigner = (await this._signer.getAccounts()).find((account) => account.address === signerAddress); if (!accountFromSigner) { throw new Error("Failed to retrieve account from signer"); } const pubkey = (0, proto_signing_1.encodePubkey)((0, amino_1.encodeSecp256k1Pubkey)(accountFromSigner.pubkey)); const txBodyEncodeObject = { typeUrl: "/cosmos.tx.v1beta1.TxBody", value: { messages: messages, memo: memo, }, }; const txBodyBytes = this.registry.encode(txBodyEncodeObject); const gasLimit = math_1.Int53.fromString(fee.gas).toNumber(); const authInfoBytes = makeDidAuthInfoBytes([{ pubkey, sequence }], fee.amount, gasLimit, fee.payer); const signDoc = (0, proto_signing_1.makeSignDoc)(txBodyBytes, authInfoBytes, chainId, accountNumber); const { signature, signed } = await this._signer.signDirect(signerAddress, signDoc); return tx_1.TxRaw.fromPartial({ bodyBytes: signed.bodyBytes, authInfoBytes: signed.authInfoBytes, signatures: [(0, encoding_1.fromBase64)(signature.signature)], }); } async checkDidSigners(verificationMethods = []) { if (verificationMethods.length === 0) { throw new Error('No verification methods provided'); } verificationMethods.forEach((verificationMethod) => { if (!Object.values(types_1.VerificationMethods).includes(verificationMethod.verificationMethodType ?? '')) { throw new Error(`Unsupported verification method type: ${verificationMethod.verificationMethodType}`); } if (!this.didSigners[verificationMethod.verificationMethodType ?? '']) { this.didSigners[verificationMethod.verificationMethodType ?? ''] = did_jwt_1.EdDSASigner; } }); return this.didSigners; } async getDidSigner(verificationMethodId, verificationMethods) { await this.checkDidSigners(verificationMethods); const verificationMethod = verificationMethods.find(method => method.id === verificationMethodId)?.verificationMethodType; if (!verificationMethod) { throw new Error(`Verification method for ${verificationMethodId} not found`); } return this.didSigners[verificationMethod]; } async signcreateDidDocTx(signInputs, payload) { await this.checkDidSigners(payload?.verificationMethod); const signBytes = v2_1.MsgCreateDidDocPayload.encode(payload).finish(); const signInfos = await Promise.all(signInputs.map(async (signInput) => { return { verificationMethodId: signInput.verificationMethodId, signature: (0, did_jwt_1.base64ToBytes)((await (await this.getDidSigner(signInput.verificationMethodId, payload.verificationMethod))((0, did_jwt_1.hexToBytes)(signInput.privateKeyHex))(signBytes))) }; })); return signInfos; } async signupdateDidDocTx(signInputs, payload) { await this.checkDidSigners(payload?.verificationMethod); const signBytes = v2_1.MsgUpdateDidDocPayload.encode(payload).finish(); const signInfos = await Promise.all(signInputs.map(async (signInput) => { return { verificationMethodId: signInput.verificationMethodId, signature: (0, did_jwt_1.base64ToBytes)((await (await this.getDidSigner(signInput.verificationMethodId, payload.verificationMethod))((0, did_jwt_1.hexToBytes)(signInput.privateKeyHex))(signBytes))) }; })); return signInfos; } async signdeactivateDidDocTx(signInputs, payload, verificationMethod) { await this.checkDidSigners(verificationMethod); const signBytes = v2_1.MsgDeactivateDidDocPayload.encode(payload).finish(); const signInfos = await Promise.all(signInputs.map(async (signInput) => { return { verificationMethodId: signInput.verificationMethodId, signature: (0, did_jwt_1.base64ToBytes)((await (await this.getDidSigner(signInput.verificationMethodId, verificationMethod))((0, did_jwt_1.hexToBytes)(signInput.privateKeyHex))(signBytes))) }; })); return signInfos; } static async signIdentityTx(signBytes, signInputs) { let signInfos = []; for (let signInput of signInputs) { if (typeof (signInput.keyType) === undefined) { throw new Error('Key type is not defined'); } let signature; switch (signInput.keyType) { case 'Ed25519': signature = (await (0, did_jwt_1.EdDSASigner)((0, did_jwt_1.hexToBytes)(signInput.privateKeyHex))(signBytes)); break; case 'Secp256k1': signature = (await (0, did_jwt_1.ES256KSigner)((0, did_jwt_1.hexToBytes)(signInput.privateKeyHex))(signBytes)); break; case 'P256': signature = (await (0, did_jwt_1.ES256Signer)((0, did_jwt_1.hexToBytes)(signInput.privateKeyHex))(signBytes)); break; default: throw new Error(`Unsupported signature type: ${signInput.keyType}`); } signInfos.push({ verificationMethodId: signInput.verificationMethodId, signature: (0, did_jwt_1.base64ToBytes)(signature) }); } return signInfos; } } exports.CheqdSigningStargateClient = CheqdSigningStargateClient; //# sourceMappingURL=signer.js.map