Merge pull request #766 from cosmos/734-typesafe-encode-objects

Add type-safe EncodeObjects
This commit is contained in:
Will Clark 2021-04-20 13:05:42 +02:00 committed by GitHub
commit 6a18c8e657
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 361 additions and 121 deletions

View File

@ -73,6 +73,17 @@ and this project adheres to
include `gasUsed` and `gasWanted` properties.
- @cosmjs/cosmwasm-stargate: `CosmWasmClient.broadcastTx` and `.getTx` results
now include `gasUsed` and `gasWanted` properties.
- @cosmjs/proto-signing: Export `DecodeObject` and `TxBodyEncodeObject`
interfaces as well as `isTxBodyEncodeObject` helper function.
- @cosmjs/stargate: Add `MsgDelegateEncodeObject`, `MsgSendEncodeObject`,
`MsgTransferEncodeObject`, `MsgUndelegateEncodeObject` and
`MsgWithdrawDelegatorRewardEncodeObject` interfaces as well as
`isMsgDelegateEncodeObject` etc helpers.
- @cosmjs/cosmwasm-stargate: Add `MsgClearAdminEncodeObject`,
`MsgExecuteContractEncodeObject`, `MsgInstantiateContractEncodeObject`,
`MsgMigrateContractEncodeObject`, `MsgStoreCodeEncodeObject` and
`MsgUpdateAdminEncodeObject` interfaces as well as
`isMsgClearAdminEncodeObject` etc helpers.
### Changed

View File

@ -6,6 +6,7 @@ import {
makeAuthInfoBytes,
makeSignDoc,
Registry,
TxBodyEncodeObject,
} from "@cosmjs/proto-signing";
import {
BroadcastTxResponse,
@ -13,6 +14,7 @@ import {
coins,
isBroadcastTxFailure,
isBroadcastTxSuccess,
isMsgSendEncodeObject,
} from "@cosmjs/stargate";
import { Tx, TxRaw } from "@cosmjs/stargate/build/codec/cosmos/tx/v1beta1/tx";
import { assert, sleep } from "@cosmjs/utils";
@ -51,7 +53,7 @@ async function sendTokens(
type: "tendermint/PubKeySecp256k1",
value: toBase64(pubkeyBytes),
});
const txBodyFields = {
const txBodyFields: TxBodyEncodeObject = {
typeUrl: "/cosmos.tx.v1beta1.TxBody",
value: {
messages: [
@ -231,9 +233,9 @@ describe("CosmWasmClient.getTx and .searchTx", () => {
// Check basic structure of all results
for (const result of results) {
const tx = Tx.decode(result.tx);
const filteredMsgs = tx.body!.messages.filter(({ typeUrl: typeUrl, value }) => {
if (typeUrl !== "/cosmos.bank.v1beta1.MsgSend") return false;
const decoded = registry.decode({ typeUrl: typeUrl, value: value });
const filteredMsgs = tx.body!.messages.filter((msg) => {
if (!isMsgSendEncodeObject(msg)) return false;
const decoded = registry.decode(msg);
return decoded.fromAddress === sendSuccessful?.sender;
});
expect(filteredMsgs.length).toBeGreaterThanOrEqual(1);
@ -259,9 +261,9 @@ describe("CosmWasmClient.getTx and .searchTx", () => {
// Check basic structure of all results
for (const result of results) {
const tx = Tx.decode(result.tx);
const filteredMsgs = tx.body!.messages.filter(({ typeUrl: typeUrl, value }) => {
if (typeUrl !== "/cosmos.bank.v1beta1.MsgSend") return false;
const decoded = registry.decode({ typeUrl: typeUrl, value: value });
const filteredMsgs = tx.body!.messages.filter((msg) => {
if (!isMsgSendEncodeObject(msg)) return false;
const decoded = registry.decode(msg);
return decoded.toAddress === sendSuccessful?.recipient;
});
expect(filteredMsgs.length).toBeGreaterThanOrEqual(1);
@ -345,9 +347,9 @@ describe("CosmWasmClient.getTx and .searchTx", () => {
// Check basic structure of all results
for (const result of results) {
const tx = Tx.decode(result.tx);
const { typeUrl, value } = fromOneElementArray(tx.body!.messages);
expect(typeUrl).toEqual("/cosmos.bank.v1beta1.MsgSend");
const decoded = registry.decode({ typeUrl: typeUrl, value: value });
const msg = fromOneElementArray(tx.body!.messages);
expect(msg.typeUrl).toEqual("/cosmos.bank.v1beta1.MsgSend");
const decoded = registry.decode(msg);
expect(decoded.toAddress).toEqual(sendSuccessful.recipient);
}

View File

@ -9,8 +9,9 @@ import {
makeAuthInfoBytes,
makeSignDoc,
Registry,
TxBodyEncodeObject,
} from "@cosmjs/proto-signing";
import { assertIsBroadcastTxSuccess, coins, logs, StdFee } from "@cosmjs/stargate";
import { assertIsBroadcastTxSuccess, coins, logs, MsgSendEncodeObject, StdFee } from "@cosmjs/stargate";
import { TxRaw } from "@cosmjs/stargate/build/codec/cosmos/tx/v1beta1/tx";
import { assert, sleep } from "@cosmjs/utils";
import { ReadonlyDate } from "readonly-date";
@ -173,7 +174,7 @@ describe("CosmWasmClient", () => {
const registry = new Registry();
const memo = "My first contract on chain";
const sendMsg = {
const sendMsg: MsgSendEncodeObject = {
typeUrl: "/cosmos.bank.v1beta1.MsgSend",
value: {
fromAddress: alice.address0,
@ -191,14 +192,14 @@ describe("CosmWasmClient", () => {
assert(sequenceResponse);
const { accountNumber, sequence } = sequenceResponse;
const pubkeyAny = encodePubkey(alice.pubkey0);
const txBody = {
messages: [sendMsg],
memo: memo,
};
const txBodyBytes = registry.encode({
const txBody: TxBodyEncodeObject = {
typeUrl: "/cosmos.tx.v1beta1.TxBody",
value: txBody,
});
value: {
messages: [sendMsg],
memo: memo,
},
};
const txBodyBytes = registry.encode(txBody);
const gasLimit = Int53.fromString(fee.gas).toNumber();
const authInfoBytes = makeAuthInfoBytes([pubkeyAny], fee.amount, gasLimit, sequence);
const signDoc = makeSignDoc(txBodyBytes, authInfoBytes, chainId, accountNumber);

View File

@ -0,0 +1,83 @@
import { EncodeObject } from "@cosmjs/proto-signing";
import {
MsgClearAdmin,
MsgExecuteContract,
MsgInstantiateContract,
MsgMigrateContract,
MsgStoreCode,
MsgUpdateAdmin,
} from "./codec/x/wasm/internal/types/tx";
export interface MsgStoreCodeEncodeObject extends EncodeObject {
readonly typeUrl: "/cosmwasm.wasm.v1beta1.MsgStoreCode";
readonly value: Partial<MsgStoreCode>;
}
export function isMsgStoreCodeEncodeObject(
encodeObject: EncodeObject,
): encodeObject is MsgStoreCodeEncodeObject {
return (encodeObject as MsgStoreCodeEncodeObject).typeUrl === "/cosmwasm.wasm.v1beta1.MsgStoreCode";
}
export interface MsgInstantiateContractEncodeObject extends EncodeObject {
readonly typeUrl: "/cosmwasm.wasm.v1beta1.MsgInstantiateContract";
readonly value: Partial<MsgInstantiateContract>;
}
export function isMsgInstantiateContractEncodeObject(
encodeObject: EncodeObject,
): encodeObject is MsgInstantiateContractEncodeObject {
return (
(encodeObject as MsgInstantiateContractEncodeObject).typeUrl ===
"/cosmwasm.wasm.v1beta1.MsgInstantiateContract"
);
}
export interface MsgUpdateAdminEncodeObject extends EncodeObject {
readonly typeUrl: "/cosmwasm.wasm.v1beta1.MsgUpdateAdmin";
readonly value: Partial<MsgUpdateAdmin>;
}
export function isMsgUpdateAdminEncodeObject(
encodeObject: EncodeObject,
): encodeObject is MsgUpdateAdminEncodeObject {
return (encodeObject as MsgUpdateAdminEncodeObject).typeUrl === "/cosmwasm.wasm.v1beta1.MsgUpdateAdmin";
}
export interface MsgClearAdminEncodeObject extends EncodeObject {
readonly typeUrl: "/cosmwasm.wasm.v1beta1.MsgClearAdmin";
readonly value: Partial<MsgClearAdmin>;
}
export function isMsgClearAdminEncodeObject(
encodeObject: EncodeObject,
): encodeObject is MsgClearAdminEncodeObject {
return (encodeObject as MsgClearAdminEncodeObject).typeUrl === "/cosmwasm.wasm.v1beta1.MsgClearAdmin";
}
export interface MsgMigrateContractEncodeObject extends EncodeObject {
readonly typeUrl: "/cosmwasm.wasm.v1beta1.MsgMigrateContract";
readonly value: Partial<MsgMigrateContract>;
}
export function isMsgMigrateEncodeObject(
encodeObject: EncodeObject,
): encodeObject is MsgMigrateContractEncodeObject {
return (
(encodeObject as MsgMigrateContractEncodeObject).typeUrl === "/cosmwasm.wasm.v1beta1.MsgMigrateContract"
);
}
export interface MsgExecuteContractEncodeObject extends EncodeObject {
readonly typeUrl: "/cosmwasm.wasm.v1beta1.MsgExecuteContract";
readonly value: Partial<MsgExecuteContract>;
}
export function isMsgExecuteEncodeObject(
encodeObject: EncodeObject,
): encodeObject is MsgExecuteContractEncodeObject {
return (
(encodeObject as MsgExecuteContractEncodeObject).typeUrl === "/cosmwasm.wasm.v1beta1.MsgExecuteContract"
);
}

View File

@ -1,5 +1,19 @@
export { cosmWasmTypes } from "./aminotypes";
export { CosmWasmClient } from "./cosmwasmclient";
export {
isMsgClearAdminEncodeObject,
isMsgExecuteEncodeObject,
isMsgInstantiateContractEncodeObject,
isMsgMigrateEncodeObject,
isMsgStoreCodeEncodeObject,
isMsgUpdateAdminEncodeObject,
MsgClearAdminEncodeObject,
MsgExecuteContractEncodeObject,
MsgInstantiateContractEncodeObject,
MsgMigrateContractEncodeObject,
MsgStoreCodeEncodeObject,
MsgUpdateAdminEncodeObject,
} from "./encodeobjects";
export {
defaultGasLimits,
SigningCosmWasmClient,

View File

@ -17,6 +17,11 @@ import Long from "long";
import { MsgExecuteContract, MsgInstantiateContract, MsgStoreCode } from "../codec/x/wasm/internal/types/tx";
import { ContractCodeHistoryOperationType } from "../codec/x/wasm/internal/types/types";
import {
MsgExecuteContractEncodeObject,
MsgInstantiateContractEncodeObject,
MsgStoreCodeEncodeObject,
} from "../encodeobjects";
import { SigningCosmWasmClient } from "../signingcosmwasmclient";
import {
alice,
@ -42,7 +47,7 @@ async function uploadContract(
contract: ContractUploadInstructions,
): Promise<BroadcastTxResponse> {
const memo = "My first contract on chain";
const theMsg = {
const theMsg: MsgStoreCodeEncodeObject = {
typeUrl: "/cosmwasm.wasm.v1beta1.MsgStoreCode",
value: MsgStoreCode.fromPartial({
sender: alice.address0,
@ -67,7 +72,7 @@ async function instantiateContract(
transferAmount?: readonly Coin[],
): Promise<BroadcastTxResponse> {
const memo = "Create an escrow instance";
const theMsg = {
const theMsg: MsgInstantiateContractEncodeObject = {
typeUrl: "/cosmwasm.wasm.v1beta1.MsgInstantiateContract",
value: MsgInstantiateContract.fromPartial({
sender: alice.address0,
@ -98,7 +103,7 @@ async function executeContract(
msg: Record<string, unknown>,
): Promise<BroadcastTxResponse> {
const memo = "Time for action";
const theMsg = {
const theMsg: MsgExecuteContractEncodeObject = {
typeUrl: "/cosmwasm.wasm.v1beta1.MsgExecuteContract",
value: MsgExecuteContract.fromPartial({
sender: alice.address0,

View File

@ -11,6 +11,8 @@ import {
coin,
coins,
GasPrice,
MsgDelegateEncodeObject,
MsgSendEncodeObject,
} from "@cosmjs/stargate";
import { DeepPartial, MsgSend } from "@cosmjs/stargate/build/codec/cosmos/bank/v1beta1/tx";
import { Coin } from "@cosmjs/stargate/build/codec/cosmos/base/v1beta1/coin";
@ -22,6 +24,7 @@ import pako from "pako";
import protobuf from "protobufjs/minimal";
import { MsgStoreCode } from "./codec/x/wasm/internal/types/tx";
import { MsgStoreCodeEncodeObject } from "./encodeobjects";
import { PrivateSigningCosmWasmClient, SigningCosmWasmClient } from "./signingcosmwasmclient";
import {
alice,
@ -557,7 +560,7 @@ describe("SigningCosmWasmClient", () => {
validatorAddress: validator.validatorAddress,
amount: coin(1234, "ustake"),
});
const msgAny = {
const msgAny: MsgDelegateEncodeObject = {
typeUrl: msgDelegateTypeUrl,
value: msg,
};
@ -582,7 +585,7 @@ describe("SigningCosmWasmClient", () => {
validatorAddress: validator.validatorAddress,
amount: coin(1234, "ustake"),
});
const msgAny = {
const msgAny: MsgDelegateEncodeObject = {
typeUrl: msgDelegateTypeUrl,
value: msg,
};
@ -618,7 +621,7 @@ describe("SigningCosmWasmClient", () => {
toAddress: makeRandomAddress(),
amount: coins(1234, "ucosm"),
};
const msgAny = {
const msgAny: MsgSendEncodeObject = {
typeUrl: "/cosmos.bank.v1beta1.MsgSend",
value: msgSend,
};
@ -642,7 +645,7 @@ describe("SigningCosmWasmClient", () => {
validatorAddress: validator.validatorAddress,
amount: coin(1234, "ustake"),
};
const msgAny = {
const msgAny: MsgDelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgDelegate",
value: msgDelegate,
};
@ -669,7 +672,7 @@ describe("SigningCosmWasmClient", () => {
builder: builder ?? "",
instantiatePermission: undefined,
};
const msgAny = {
const msgAny: MsgStoreCodeEncodeObject = {
typeUrl: "/cosmwasm.wasm.v1beta1.MsgStoreCode",
value: msgStoreCode,
};
@ -811,7 +814,7 @@ describe("SigningCosmWasmClient", () => {
validatorAddress: validator.validatorAddress,
amount: coin(1234, "ustake"),
};
const msgAny = {
const msgAny: MsgDelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgDelegate",
value: msg,
};
@ -849,7 +852,7 @@ describe("SigningCosmWasmClient", () => {
validatorAddress: validator.validatorAddress,
amount: coin(1234, "ustake"),
});
const msgAny = {
const msgAny: MsgDelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgDelegate",
value: msg,
};
@ -876,7 +879,7 @@ describe("SigningCosmWasmClient", () => {
validatorAddress: validator.validatorAddress,
amount: coin(1234, "ustake"),
});
const msgAny = {
const msgAny: MsgDelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgDelegate",
value: msg,
};
@ -912,7 +915,7 @@ describe("SigningCosmWasmClient", () => {
toAddress: makeRandomAddress(),
amount: coins(1234, "ucosm"),
};
const msgAny = {
const msgAny: MsgSendEncodeObject = {
typeUrl: "/cosmos.bank.v1beta1.MsgSend",
value: msgSend,
};
@ -939,7 +942,7 @@ describe("SigningCosmWasmClient", () => {
validatorAddress: validator.validatorAddress,
amount: coin(1234, "ustake"),
};
const msgAny = {
const msgAny: MsgDelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgDelegate",
value: msgDelegate,
};
@ -1085,7 +1088,7 @@ describe("SigningCosmWasmClient", () => {
validatorAddress: validator.validatorAddress,
amount: coin(1234, "ustake"),
};
const msgAny = {
const msgAny: MsgDelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgDelegate",
value: msg,
};

View File

@ -21,6 +21,7 @@ import {
makeSignDoc,
OfflineSigner,
Registry,
TxBodyEncodeObject,
} from "@cosmjs/proto-signing";
import {
AminoTypes,
@ -36,6 +37,10 @@ import {
GasPrice,
isBroadcastTxFailure,
logs,
MsgDelegateEncodeObject,
MsgSendEncodeObject,
MsgUndelegateEncodeObject,
MsgWithdrawDelegatorRewardEncodeObject,
SignerData,
StdFee,
} from "@cosmjs/stargate";
@ -58,6 +63,14 @@ import {
MsgUpdateAdmin,
} from "./codec/x/wasm/internal/types/tx";
import { CosmWasmClient } from "./cosmwasmclient";
import {
MsgClearAdminEncodeObject,
MsgExecuteContractEncodeObject,
MsgInstantiateContractEncodeObject,
MsgMigrateContractEncodeObject,
MsgStoreCodeEncodeObject,
MsgUpdateAdminEncodeObject,
} from "./encodeobjects";
/**
* These fees are used by the higher level methods of SigningCosmWasmClient
@ -179,7 +192,7 @@ export class SigningCosmWasmClient extends CosmWasmClient {
const source = meta.source || "";
const builder = prepareBuilder(meta.builder);
const compressed = pako.gzip(wasmCode, { level: 9 });
const storeCodeMsg = {
const storeCodeMsg: MsgStoreCodeEncodeObject = {
typeUrl: "/cosmwasm.wasm.v1beta1.MsgStoreCode",
value: MsgStoreCode.fromPartial({
sender: senderAddress,
@ -213,7 +226,7 @@ export class SigningCosmWasmClient extends CosmWasmClient {
label: string,
options: InstantiateOptions = {},
): Promise<InstantiateResult> {
const instantiateMsg = {
const instantiateContractMsg: MsgInstantiateContractEncodeObject = {
typeUrl: "/cosmwasm.wasm.v1beta1.MsgInstantiateContract",
value: MsgInstantiateContract.fromPartial({
sender: senderAddress,
@ -224,7 +237,12 @@ export class SigningCosmWasmClient extends CosmWasmClient {
admin: options.admin,
}),
};
const result = await this.signAndBroadcast(senderAddress, [instantiateMsg], this.fees.init, options.memo);
const result = await this.signAndBroadcast(
senderAddress,
[instantiateContractMsg],
this.fees.init,
options.memo,
);
if (isBroadcastTxFailure(result)) {
throw new Error(createBroadcastTxErrorMessage(result));
}
@ -243,7 +261,7 @@ export class SigningCosmWasmClient extends CosmWasmClient {
newAdmin: string,
memo = "",
): Promise<ChangeAdminResult> {
const updateAdminMsg = {
const updateAdminMsg: MsgUpdateAdminEncodeObject = {
typeUrl: "/cosmwasm.wasm.v1beta1.MsgUpdateAdmin",
value: MsgUpdateAdmin.fromPartial({
sender: senderAddress,
@ -266,7 +284,7 @@ export class SigningCosmWasmClient extends CosmWasmClient {
contractAddress: string,
memo = "",
): Promise<ChangeAdminResult> {
const clearAdminMsg = {
const clearAdminMsg: MsgClearAdminEncodeObject = {
typeUrl: "/cosmwasm.wasm.v1beta1.MsgClearAdmin",
value: MsgClearAdmin.fromPartial({
sender: senderAddress,
@ -290,7 +308,7 @@ export class SigningCosmWasmClient extends CosmWasmClient {
migrateMsg: Record<string, unknown>,
memo = "",
): Promise<MigrateResult> {
const msg = {
const migrateContractMsg: MsgMigrateContractEncodeObject = {
typeUrl: "/cosmwasm.wasm.v1beta1.MsgMigrateContract",
value: MsgMigrateContract.fromPartial({
sender: senderAddress,
@ -299,7 +317,7 @@ export class SigningCosmWasmClient extends CosmWasmClient {
migrateMsg: toUtf8(JSON.stringify(migrateMsg)),
}),
};
const result = await this.signAndBroadcast(senderAddress, [msg], this.fees.migrate, memo);
const result = await this.signAndBroadcast(senderAddress, [migrateContractMsg], this.fees.migrate, memo);
if (isBroadcastTxFailure(result)) {
throw new Error(createBroadcastTxErrorMessage(result));
}
@ -316,7 +334,7 @@ export class SigningCosmWasmClient extends CosmWasmClient {
memo = "",
transferAmount?: readonly Coin[],
): Promise<ExecuteResult> {
const executeMsg = {
const executeContractMsg: MsgExecuteContractEncodeObject = {
typeUrl: "/cosmwasm.wasm.v1beta1.MsgExecuteContract",
value: MsgExecuteContract.fromPartial({
sender: senderAddress,
@ -325,7 +343,7 @@ export class SigningCosmWasmClient extends CosmWasmClient {
funds: [...(transferAmount || [])],
}),
};
const result = await this.signAndBroadcast(senderAddress, [executeMsg], this.fees.exec, memo);
const result = await this.signAndBroadcast(senderAddress, [executeContractMsg], this.fees.exec, memo);
if (isBroadcastTxFailure(result)) {
throw new Error(createBroadcastTxErrorMessage(result));
}
@ -341,12 +359,12 @@ export class SigningCosmWasmClient extends CosmWasmClient {
transferAmount: readonly Coin[],
memo = "",
): Promise<BroadcastTxResponse> {
const sendMsg = {
const sendMsg: MsgSendEncodeObject = {
typeUrl: "/cosmos.bank.v1beta1.MsgSend",
value: {
fromAddress: senderAddress,
toAddress: recipientAddress,
amount: transferAmount,
amount: [...transferAmount],
},
};
return this.signAndBroadcast(senderAddress, [sendMsg], this.fees.send, memo);
@ -358,7 +376,7 @@ export class SigningCosmWasmClient extends CosmWasmClient {
amount: Coin,
memo = "",
): Promise<BroadcastTxResponse> {
const delegateMsg = {
const delegateMsg: MsgDelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgDelegate",
value: MsgDelegate.fromPartial({ delegatorAddress: delegatorAddress, validatorAddress, amount }),
};
@ -371,7 +389,7 @@ export class SigningCosmWasmClient extends CosmWasmClient {
amount: Coin,
memo = "",
): Promise<BroadcastTxResponse> {
const undelegateMsg = {
const undelegateMsg: MsgUndelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgUndelegate",
value: MsgUndelegate.fromPartial({ delegatorAddress: delegatorAddress, validatorAddress, amount }),
};
@ -383,11 +401,11 @@ export class SigningCosmWasmClient extends CosmWasmClient {
validatorAddress: string,
memo = "",
): Promise<BroadcastTxResponse> {
const withdrawMsg = {
const withdrawDelegatorRewardMsg: MsgWithdrawDelegatorRewardEncodeObject = {
typeUrl: "/cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward",
value: MsgWithdrawDelegatorReward.fromPartial({ delegatorAddress: delegatorAddress, validatorAddress }),
};
return this.signAndBroadcast(delegatorAddress, [withdrawMsg], this.fees.withdraw, memo);
return this.signAndBroadcast(delegatorAddress, [withdrawDelegatorRewardMsg], this.fees.withdraw, memo);
}
/**
@ -453,14 +471,14 @@ export class SigningCosmWasmClient extends CosmWasmClient {
const msgs = messages.map((msg) => this.aminoTypes.toAmino(msg));
const signDoc = makeSignDocAmino(msgs, fee, chainId, memo, accountNumber, sequence);
const { signature, signed } = await this.signer.signAmino(signerAddress, signDoc);
const signedTxBody = {
messages: signed.msgs.map((msg) => this.aminoTypes.fromAmino(msg)),
memo: signed.memo,
};
const signedTxBodyBytes = this.registry.encode({
const signedTxBody: TxBodyEncodeObject = {
typeUrl: "/cosmos.tx.v1beta1.TxBody",
value: signedTxBody,
});
value: {
messages: signed.msgs.map((msg) => this.aminoTypes.fromAmino(msg)),
memo: signed.memo,
},
};
const signedTxBodyBytes = this.registry.encode(signedTxBody);
const signedGasLimit = Int53.fromString(signed.fee.gas).toNumber();
const signedSequence = Int53.fromString(signed.sequence).toNumber();
const signedAuthInfoBytes = makeAuthInfoBytes(
@ -492,14 +510,14 @@ export class SigningCosmWasmClient extends CosmWasmClient {
throw new Error("Failed to retrieve account from signer");
}
const pubkey = encodePubkey(encodeSecp256k1Pubkey(accountFromSigner.pubkey));
const txBody = {
messages: messages,
memo: memo,
};
const txBodyBytes = this.registry.encode({
const txBody: TxBodyEncodeObject = {
typeUrl: "/cosmos.tx.v1beta1.TxBody",
value: txBody,
});
value: {
messages: messages,
memo: memo,
},
};
const txBodyBytes = this.registry.encode(txBody);
const gasLimit = Int53.fromString(fee.gas).toNumber();
const authInfoBytes = makeAuthInfoBytes([pubkey], fee.amount, gasLimit, sequence);
const signDoc = makeSignDoc(txBodyBytes, authInfoBytes, chainId, accountNumber);

View File

@ -2,13 +2,16 @@
export { Coin, coin, coins, parseCoins } from "@cosmjs/amino";
export {
isPbjsGeneratedType,
isTsProtoGeneratedType,
DecodeObject,
EncodeObject,
GeneratedType,
isTxBodyEncodeObject,
isPbjsGeneratedType,
isTsProtoGeneratedType,
PbjsGeneratedType,
Registry,
TsProtoGeneratedType,
PbjsGeneratedType,
TxBodyEncodeObject,
} from "./registry";
export { DirectSecp256k1HdWallet, DirectSecp256k1HdWalletOptions } from "./directsecp256k1hdwallet";
export { DirectSecp256k1Wallet } from "./directsecp256k1wallet";

View File

@ -40,17 +40,24 @@ export function isPbjsGeneratedType(type: GeneratedType): type is PbjsGeneratedT
return !isTsProtoGeneratedType(type);
}
export interface EncodeObject {
readonly typeUrl: string;
readonly value: any;
}
const defaultTypeUrls = {
cosmosCoin: "/cosmos.base.v1beta1.Coin",
cosmosMsgSend: "/cosmos.bank.v1beta1.MsgSend",
cosmosTxBody: "/cosmos.tx.v1beta1.TxBody",
googleAny: "/google.protobuf.Any",
};
export interface DecodeObject {
readonly typeUrl: string;
readonly value: Uint8Array;
}
export interface TxBodyValue {
export interface EncodeObject {
readonly typeUrl: string;
readonly value: any;
}
interface TxBodyValue {
readonly messages: readonly EncodeObject[];
readonly memo?: string;
readonly timeoutHeight?: Long;
@ -58,12 +65,14 @@ export interface TxBodyValue {
readonly nonCriticalExtensionOptions?: Any[];
}
const defaultTypeUrls = {
cosmosCoin: "/cosmos.base.v1beta1.Coin",
cosmosMsgSend: "/cosmos.bank.v1beta1.MsgSend",
cosmosTxBody: "/cosmos.tx.v1beta1.TxBody",
googleAny: "/google.protobuf.Any",
};
export interface TxBodyEncodeObject extends EncodeObject {
readonly typeUrl: "/cosmos.tx.v1beta1.TxBody";
readonly value: TxBodyValue;
}
export function isTxBodyEncodeObject(encodeObject: EncodeObject): encodeObject is TxBodyEncodeObject {
return (encodeObject as TxBodyEncodeObject).typeUrl === "/cosmos.tx.v1beta1.TxBody";
}
export class Registry {
private readonly types: Map<string, GeneratedType>;
@ -109,13 +118,14 @@ export class Registry {
return type;
}
public encode({ typeUrl, value }: EncodeObject): Uint8Array {
if (typeUrl === defaultTypeUrls.cosmosTxBody) {
public encode(encodeObject: EncodeObject): Uint8Array {
const { value, typeUrl } = encodeObject;
if (isTxBodyEncodeObject(encodeObject)) {
return this.encodeTxBody(value);
}
const type = this.lookupTypeWithError(typeUrl);
const instance = isTsProtoGeneratedType(type) ? type.fromPartial(value) : type.create(value);
return Uint8Array.from(type.encode(instance).finish());
return type.encode(instance).finish();
}
public encodeTxBody(txBodyFields: TxBodyValue): Uint8Array {
@ -130,7 +140,7 @@ export class Registry {
...txBodyFields,
messages: wrappedMessages,
});
return Uint8Array.from(TxBody.encode(txBody).finish());
return TxBody.encode(txBody).finish();
}
public decode({ typeUrl, value }: DecodeObject): any {

View File

@ -0,0 +1,62 @@
import { EncodeObject } from "@cosmjs/proto-signing";
import { MsgSend } from "./codec/cosmos/bank/v1beta1/tx";
import { MsgWithdrawDelegatorReward } from "./codec/cosmos/distribution/v1beta1/tx";
import { MsgDelegate, MsgUndelegate } from "./codec/cosmos/staking/v1beta1/tx";
import { MsgTransfer } from "./codec/ibc/applications/transfer/v1/tx";
export interface MsgSendEncodeObject extends EncodeObject {
readonly typeUrl: "/cosmos.bank.v1beta1.MsgSend";
readonly value: Partial<MsgSend>;
}
export function isMsgSendEncodeObject(encodeObject: EncodeObject): encodeObject is MsgSendEncodeObject {
return (encodeObject as MsgSendEncodeObject).typeUrl === "/cosmos.bank.v1beta1.MsgSend";
}
export interface MsgDelegateEncodeObject extends EncodeObject {
readonly typeUrl: "/cosmos.staking.v1beta1.MsgDelegate";
readonly value: Partial<MsgDelegate>;
}
export function isMsgDelegateEncodeObject(
encodeObject: EncodeObject,
): encodeObject is MsgDelegateEncodeObject {
return (encodeObject as MsgDelegateEncodeObject).typeUrl === "/cosmos.staking.v1beta1.MsgDelegate";
}
export interface MsgUndelegateEncodeObject extends EncodeObject {
readonly typeUrl: "/cosmos.staking.v1beta1.MsgUndelegate";
readonly value: Partial<MsgUndelegate>;
}
export function isMsgUndelegateEncodeObject(
encodeObject: EncodeObject,
): encodeObject is MsgUndelegateEncodeObject {
return (encodeObject as MsgUndelegateEncodeObject).typeUrl === "/cosmos.staking.v1beta1.MsgUndelegate";
}
export interface MsgWithdrawDelegatorRewardEncodeObject extends EncodeObject {
readonly typeUrl: "/cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward";
readonly value: Partial<MsgWithdrawDelegatorReward>;
}
export function isMsgWithdrawDelegatorRewardEncodeObject(
encodeObject: EncodeObject,
): encodeObject is MsgWithdrawDelegatorRewardEncodeObject {
return (
(encodeObject as MsgWithdrawDelegatorRewardEncodeObject).typeUrl ===
"/cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward"
);
}
export interface MsgTransferEncodeObject extends EncodeObject {
readonly typeUrl: "/ibc.applications.transfer.v1.MsgTransfer";
readonly value: Partial<MsgTransfer>;
}
export function isMsgTransferEncodeObject(
encodeObject: EncodeObject,
): encodeObject is MsgTransferEncodeObject {
return (encodeObject as MsgTransferEncodeObject).typeUrl === "/ibc.applications.transfer.v1.MsgTransfer";
}

View File

@ -39,6 +39,18 @@ export {
isAminoMsgWithdrawValidatorCommission,
} from "./aminomsgs";
export { AminoConverter, AminoTypes } from "./aminotypes";
export {
isMsgDelegateEncodeObject,
isMsgSendEncodeObject,
isMsgTransferEncodeObject,
isMsgUndelegateEncodeObject,
isMsgWithdrawDelegatorRewardEncodeObject,
MsgDelegateEncodeObject,
MsgSendEncodeObject,
MsgTransferEncodeObject,
MsgUndelegateEncodeObject,
MsgWithdrawDelegatorRewardEncodeObject,
} from "./encodeobjects";
export { buildFeeTable, FeeTable, GasLimits, GasPrice } from "./fee";
export * as logs from "./logs";
export { makeMultisignedTx } from "./multisignature";

View File

@ -10,6 +10,7 @@ import { assert } from "@cosmjs/utils";
import { MsgSend } from "./codec/cosmos/bank/v1beta1/tx";
import { TxRaw } from "./codec/cosmos/tx/v1beta1/tx";
import { MsgSendEncodeObject } from "./encodeobjects";
import { makeCompactBitArray, makeMultisignedTx } from "./multisignature";
import { SignerData, SigningStargateClient } from "./signingstargateclient";
import { assertIsBroadcastTxSuccess, StargateClient } from "./stargateclient";
@ -185,7 +186,7 @@ describe("multisignature", () => {
toAddress: "cosmos19rvl6ja9h0erq9dc2xxfdzypc739ej8k5esnhg",
amount: coins(1234, "ucosm"),
};
const msg = {
const msg: MsgSendEncodeObject = {
typeUrl: "/cosmos.bank.v1beta1.MsgSend",
value: msgSend,
};

View File

@ -4,6 +4,7 @@ import { Tendermint34Client } from "@cosmjs/tendermint-rpc";
import { sleep } from "@cosmjs/utils";
import { MsgDelegate } from "../codec/cosmos/staking/v1beta1/tx";
import { MsgDelegateEncodeObject } from "../encodeobjects";
import { SigningStargateClient } from "../signingstargateclient";
import { assertIsBroadcastTxSuccess } from "../stargateclient";
import { faucet, pendingWithoutSimapp, simapp, simappEnabled, validator } from "../testutils.spec";
@ -33,7 +34,7 @@ describe("DistributionExtension", () => {
validatorAddress: validator.validatorAddress,
amount: coin(25000, "ustake"),
};
const msgAny = {
const msgAny: MsgDelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgDelegate",
value: msg,
};

View File

@ -4,6 +4,7 @@ import { Tendermint34Client } from "@cosmjs/tendermint-rpc";
import { sleep } from "@cosmjs/utils";
import { MsgDelegate, MsgUndelegate } from "../codec/cosmos/staking/v1beta1/tx";
import { MsgDelegateEncodeObject, MsgUndelegateEncodeObject } from "../encodeobjects";
import { SigningStargateClient } from "../signingstargateclient";
import { assertIsBroadcastTxSuccess } from "../stargateclient";
import { faucet, pendingWithoutSimapp, simapp, simappEnabled, validator } from "../testutils.spec";
@ -34,7 +35,7 @@ describe("StakingExtension", () => {
validatorAddress: validator.validatorAddress,
amount: coin(25000, "ustake"),
};
const msgAny = {
const msgAny: MsgDelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgDelegate",
value: msg,
};
@ -48,7 +49,7 @@ describe("StakingExtension", () => {
validatorAddress: validator.validatorAddress,
amount: coin(100, "ustake"),
};
const msgAny = {
const msgAny: MsgUndelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgUndelegate",
value: msg,
};

View File

@ -10,6 +10,7 @@ import { MsgSend } from "./codec/cosmos/bank/v1beta1/tx";
import { Coin } from "./codec/cosmos/base/v1beta1/coin";
import { DeepPartial, MsgDelegate } from "./codec/cosmos/staking/v1beta1/tx";
import { AuthInfo, Tx, TxBody, TxRaw } from "./codec/cosmos/tx/v1beta1/tx";
import { MsgDelegateEncodeObject, MsgSendEncodeObject } from "./encodeobjects";
import { GasPrice } from "./fee";
import { PrivateSigningStargateClient, SigningStargateClient } from "./signingstargateclient";
import { assertIsBroadcastTxSuccess } from "./stargateclient";
@ -331,7 +332,7 @@ describe("SigningStargateClient", () => {
validatorAddress: validator.validatorAddress,
amount: coin(1234, "ustake"),
});
const msgAny = {
const msgAny: MsgDelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgDelegate",
value: msg,
};
@ -354,7 +355,7 @@ describe("SigningStargateClient", () => {
validatorAddress: validator.validatorAddress,
amount: coin(1234, "ustake"),
});
const msgAny = {
const msgAny: MsgDelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgDelegate",
value: msg,
};
@ -389,7 +390,7 @@ describe("SigningStargateClient", () => {
toAddress: makeRandomAddress(),
amount: coins(1234, "ucosm"),
};
const msgAny = {
const msgAny: MsgSendEncodeObject = {
typeUrl: "/cosmos.bank.v1beta1.MsgSend",
value: msgSend,
};
@ -412,7 +413,7 @@ describe("SigningStargateClient", () => {
validatorAddress: validator.validatorAddress,
amount: coin(1234, "ustake"),
};
const msgAny = {
const msgAny: MsgDelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgDelegate",
value: msgDelegate,
};
@ -551,7 +552,7 @@ describe("SigningStargateClient", () => {
validatorAddress: validator.validatorAddress,
amount: coin(1234, "ustake"),
};
const msgAny = {
const msgAny: MsgDelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgDelegate",
value: msg,
};
@ -588,7 +589,7 @@ describe("SigningStargateClient", () => {
validatorAddress: validator.validatorAddress,
amount: coin(1234, "ustake"),
});
const msgAny = {
const msgAny: MsgDelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgDelegate",
value: msg,
};
@ -614,7 +615,7 @@ describe("SigningStargateClient", () => {
validatorAddress: validator.validatorAddress,
amount: coin(1234, "ustake"),
});
const msgAny = {
const msgAny: MsgDelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgDelegate",
value: msg,
};
@ -649,7 +650,7 @@ describe("SigningStargateClient", () => {
toAddress: makeRandomAddress(),
amount: coins(1234, "ucosm"),
};
const msgAny = {
const msgAny: MsgSendEncodeObject = {
typeUrl: "/cosmos.bank.v1beta1.MsgSend",
value: msgSend,
};
@ -675,7 +676,7 @@ describe("SigningStargateClient", () => {
validatorAddress: validator.validatorAddress,
amount: coin(1234, "ustake"),
};
const msgAny = {
const msgAny: MsgDelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgDelegate",
value: msgDelegate,
};
@ -820,7 +821,7 @@ describe("SigningStargateClient", () => {
validatorAddress: validator.validatorAddress,
amount: coin(1234, "ustake"),
};
const msgAny = {
const msgAny: MsgDelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgDelegate",
value: msg,
};

View File

@ -10,6 +10,7 @@ import {
makeSignDoc,
OfflineSigner,
Registry,
TxBodyEncodeObject,
} from "@cosmjs/proto-signing";
import { Tendermint34Client } from "@cosmjs/tendermint-rpc";
import { assert } from "@cosmjs/utils";
@ -59,6 +60,13 @@ import {
MsgConnectionOpenInit,
MsgConnectionOpenTry,
} from "./codec/ibc/core/connection/v1/tx";
import {
MsgDelegateEncodeObject,
MsgSendEncodeObject,
MsgTransferEncodeObject,
MsgUndelegateEncodeObject,
MsgWithdrawDelegatorRewardEncodeObject,
} from "./encodeobjects";
import { buildFeeTable, FeeTable, GasLimits, GasPrice } from "./fee";
import { BroadcastTxResponse, StargateClient } from "./stargateclient";
@ -201,12 +209,12 @@ export class SigningStargateClient extends StargateClient {
transferAmount: readonly Coin[],
memo = "",
): Promise<BroadcastTxResponse> {
const sendMsg = {
const sendMsg: MsgSendEncodeObject = {
typeUrl: "/cosmos.bank.v1beta1.MsgSend",
value: {
fromAddress: senderAddress,
toAddress: recipientAddress,
amount: transferAmount,
amount: [...transferAmount],
},
};
return this.signAndBroadcast(senderAddress, [sendMsg], this.fees.send, memo);
@ -218,7 +226,7 @@ export class SigningStargateClient extends StargateClient {
amount: Coin,
memo = "",
): Promise<BroadcastTxResponse> {
const delegateMsg = {
const delegateMsg: MsgDelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgDelegate",
value: MsgDelegate.fromPartial({
delegatorAddress: delegatorAddress,
@ -235,7 +243,7 @@ export class SigningStargateClient extends StargateClient {
amount: Coin,
memo = "",
): Promise<BroadcastTxResponse> {
const undelegateMsg = {
const undelegateMsg: MsgUndelegateEncodeObject = {
typeUrl: "/cosmos.staking.v1beta1.MsgUndelegate",
value: MsgUndelegate.fromPartial({
delegatorAddress: delegatorAddress,
@ -251,7 +259,7 @@ export class SigningStargateClient extends StargateClient {
validatorAddress: string,
memo = "",
): Promise<BroadcastTxResponse> {
const withdrawMsg = {
const withdrawMsg: MsgWithdrawDelegatorRewardEncodeObject = {
typeUrl: "/cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward",
value: MsgWithdrawDelegatorReward.fromPartial({
delegatorAddress: delegatorAddress,
@ -275,7 +283,7 @@ export class SigningStargateClient extends StargateClient {
const timeoutTimestampNanoseconds = timeoutTimestamp
? Long.fromNumber(timeoutTimestamp).multiply(1_000_000_000)
: undefined;
const transferMsg = {
const transferMsg: MsgTransferEncodeObject = {
typeUrl: "/ibc.applications.transfer.v1.MsgTransfer",
value: MsgTransfer.fromPartial({
sourcePort: sourcePort,
@ -359,10 +367,11 @@ export class SigningStargateClient extends StargateClient {
messages: signed.msgs.map((msg) => this.aminoTypes.fromAmino(msg)),
memo: signed.memo,
};
const signedTxBodyBytes = this.registry.encode({
const signedTxBodyEncodeObject: TxBodyEncodeObject = {
typeUrl: "/cosmos.tx.v1beta1.TxBody",
value: signedTxBody,
});
};
const signedTxBodyBytes = this.registry.encode(signedTxBodyEncodeObject);
const signedGasLimit = Int53.fromString(signed.fee.gas).toNumber();
const signedSequence = Int53.fromString(signed.sequence).toNumber();
const signedAuthInfoBytes = makeAuthInfoBytes(
@ -394,14 +403,14 @@ export class SigningStargateClient extends StargateClient {
throw new Error("Failed to retrieve account from signer");
}
const pubkey = encodePubkey(encodeSecp256k1Pubkey(accountFromSigner.pubkey));
const txBody = {
messages: messages,
memo: memo,
};
const txBodyBytes = this.registry.encode({
const txBodyEncodeObject: TxBodyEncodeObject = {
typeUrl: "/cosmos.tx.v1beta1.TxBody",
value: txBody,
});
value: {
messages: messages,
memo: memo,
},
};
const txBodyBytes = this.registry.encode(txBodyEncodeObject);
const gasLimit = Int53.fromString(fee.gas).toNumber();
const authInfoBytes = makeAuthInfoBytes([pubkey], fee.amount, gasLimit, sequence);
const signDoc = makeSignDoc(txBodyBytes, authInfoBytes, chainId, accountNumber);

View File

@ -6,11 +6,13 @@ import {
makeAuthInfoBytes,
makeSignDoc,
Registry,
TxBodyEncodeObject,
} from "@cosmjs/proto-signing";
import { assert, sleep } from "@cosmjs/utils";
import { Coin } from "./codec/cosmos/base/v1beta1/coin";
import { Tx, TxRaw } from "./codec/cosmos/tx/v1beta1/tx";
import { isMsgSendEncodeObject } from "./encodeobjects";
import {
BroadcastTxResponse,
isBroadcastTxFailure,
@ -50,7 +52,7 @@ async function sendTokens(
type: "tendermint/PubKeySecp256k1",
value: toBase64(pubkeyBytes),
});
const txBodyFields = {
const txBodyFields: TxBodyEncodeObject = {
typeUrl: "/cosmos.tx.v1beta1.TxBody",
value: {
messages: [
@ -230,9 +232,9 @@ describe("StargateClient.getTx and .searchTx", () => {
// Check basic structure of all results
for (const result of results) {
const tx = Tx.decode(result.tx);
const filteredMsgs = tx.body!.messages.filter(({ typeUrl: typeUrl, value }) => {
if (typeUrl !== "/cosmos.bank.v1beta1.MsgSend") return false;
const decoded = registry.decode({ typeUrl: typeUrl, value: value });
const filteredMsgs = tx.body!.messages.filter((msg) => {
if (!isMsgSendEncodeObject(msg)) return false;
const decoded = registry.decode(msg);
return decoded.fromAddress === sendSuccessful?.sender;
});
expect(filteredMsgs.length).toBeGreaterThanOrEqual(1);
@ -258,9 +260,9 @@ describe("StargateClient.getTx and .searchTx", () => {
// Check basic structure of all results
for (const result of results) {
const tx = Tx.decode(result.tx);
const filteredMsgs = tx.body!.messages.filter(({ typeUrl: typeUrl, value }) => {
if (typeUrl !== "/cosmos.bank.v1beta1.MsgSend") return false;
const decoded = registry.decode({ typeUrl: typeUrl, value: value });
const filteredMsgs = tx.body!.messages.filter((msg) => {
if (!isMsgSendEncodeObject(msg)) return false;
const decoded = registry.decode(msg);
return decoded.toAddress === sendSuccessful?.recipient;
});
expect(filteredMsgs.length).toBeGreaterThanOrEqual(1);
@ -344,9 +346,9 @@ describe("StargateClient.getTx and .searchTx", () => {
// Check basic structure of all results
for (const result of results) {
const tx = Tx.decode(result.tx);
const { typeUrl, value } = fromOneElementArray(tx.body!.messages);
expect(typeUrl).toEqual("/cosmos.bank.v1beta1.MsgSend");
const decoded = registry.decode({ typeUrl: typeUrl, value: value });
const msg = fromOneElementArray(tx.body!.messages);
expect(msg.typeUrl).toEqual("/cosmos.bank.v1beta1.MsgSend");
const decoded = registry.decode(msg);
expect(decoded.toAddress).toEqual(sendSuccessful.recipient);
}

View File

@ -6,6 +6,7 @@ import {
makeAuthInfoBytes,
makeSignDoc,
Registry,
TxBodyEncodeObject,
} from "@cosmjs/proto-signing";
import { assert, sleep } from "@cosmjs/utils";
import { ReadonlyDate } from "readonly-date";
@ -289,7 +290,7 @@ describe("StargateClient", () => {
value: toBase64(pubkeyBytes),
});
const registry = new Registry();
const txBodyFields = {
const txBodyFields: TxBodyEncodeObject = {
typeUrl: "/cosmos.tx.v1beta1.TxBody",
value: {
messages: [
@ -350,7 +351,7 @@ describe("StargateClient", () => {
value: toBase64(pubkeyBytes),
});
const registry = new Registry();
const txBodyFields = {
const txBodyFields: TxBodyEncodeObject = {
typeUrl: "/cosmos.tx.v1beta1.TxBody",
value: {
messages: [