Add decodeOptionalPubkey and use it

This commit is contained in:
Simon Warta
2023-10-25 11:23:15 +02:00
parent 1dad9eec11
commit d27736589d
3 changed files with 28 additions and 4 deletions
+1 -1
View File
@@ -8,7 +8,7 @@ export {
} from "./directsecp256k1hdwallet";
export { DirectSecp256k1Wallet } from "./directsecp256k1wallet";
export { makeCosmoshubPath } from "./paths";
export { anyToSinglePubkey, decodePubkey, encodePubkey } from "./pubkey";
export { anyToSinglePubkey, decodeOptionalPubkey, decodePubkey, encodePubkey } from "./pubkey";
export {
DecodeObject,
EncodeObject,
+25 -1
View File
@@ -97,6 +97,30 @@ export function decodePubkey(pubkey: Any): Pubkey {
return out;
}
default:
throw new Error(`Pubkey type_url ${pubkey.typeUrl} not recognized`);
throw new Error(`Pubkey type URL '${pubkey.typeUrl}' not recognized`);
}
}
/**
* Decodes an optional pubkey from a protobuf `Any` into `Pubkey | null`.
* This supports single pubkeys such as Cosmos ed25519 and secp256k1 keys
* as well as multisig threshold pubkeys.
*/
export function decodeOptionalPubkey(pubkey: Any | null | undefined): Pubkey | null {
if (!pubkey) return null;
if (pubkey.typeUrl) {
if (pubkey.value.length) {
// both set
return decodePubkey(pubkey);
} else {
throw new Error(`Pubkey is an Any with type URL '${pubkey.typeUrl}' but an empty value`);
}
} else {
if (pubkey.value.length) {
throw new Error(`Pubkey is an Any with an empty type URL but a value set`);
} else {
// both unset, assuming this empty instance means null
return null;
}
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
import { Pubkey } from "@cosmjs/amino";
import { Uint64 } from "@cosmjs/math";
import { decodePubkey } from "@cosmjs/proto-signing";
import { decodeOptionalPubkey } from "@cosmjs/proto-signing";
import { assert } from "@cosmjs/utils";
import { BaseAccount, ModuleAccount } from "cosmjs-types/cosmos/auth/v1beta1/auth";
import {
@@ -25,7 +25,7 @@ function uint64FromProto(input: number | bigint): Uint64 {
function accountFromBaseAccount(input: BaseAccount): Account {
const { address, pubKey, accountNumber, sequence } = input;
const pubkey = pubKey ? decodePubkey(pubKey) : null;
const pubkey = decodeOptionalPubkey(pubKey);
return {
address: address,
pubkey: pubkey,