Last active
February 24, 2024 14:11
-
-
Save giansalex/d20464064c166a94044510a2dc5755b9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { SigningStargateClient } from '@cosmjs/stargate' | |
import { fromBase64 } from "@cosmjs/encoding"; | |
import { | |
makeAuthInfoBytes, | |
makeSignDoc, | |
} from '@cosmjs/proto-signing' | |
import { Int53, Uint53 } from "@cosmjs/math"; | |
import { Any } from "cosmjs-types/google/protobuf/any"; | |
import { PubKey } from "cosmjs-types/cosmos/crypto/secp256k1/keys"; | |
import { TxRaw } from "cosmjs-types/cosmos/tx/v1beta1/tx"; | |
async function sign( | |
api, | |
client, // SigningStargateClient | |
signer, // keplr OfflineSigner | |
chainId, | |
signerAddress, | |
messages, | |
fee, | |
memo, | |
) { | |
// Query account info, because cosmjs doesn't support Evmos account | |
const { accountNumber, sequence } = await api.getAccountInfo(signerAddress) // GET /cosmos/auth/v1beta1/accounts/{address} | |
const accountFromSigner = (await signer.getAccounts()).find( | |
(account) => account.address === signerAddress, | |
); | |
if (!accountFromSigner) { | |
throw new Error("Failed to retrieve account from signer"); | |
} | |
pubkeyBytes = accountFromSigner.pubkey | |
// Custom typeUrl for EVMOS | |
const pubk = Any.fromPartial({ | |
typeUrl: "/ethermint.crypto.v1.ethsecp256k1.PubKey", | |
value: PubKey.encode({ | |
key: pubkeyBytes | |
}).finish(), | |
}) | |
const txBodyEncodeObject = { | |
typeUrl: "/cosmos.tx.v1beta1.TxBody", | |
value: { | |
messages: messages, | |
memo: memo, | |
}, | |
}; | |
const txBodyBytes = client.registry.encode(txBodyEncodeObject); | |
const gasLimit = Int53.fromString(fee.gas).toNumber(); | |
const authInfoBytes = makeAuthInfoBytes([{ pubkey: pubk, sequence }], fee.amount, gasLimit); | |
const signDoc = makeSignDoc(txBodyBytes, authInfoBytes, chainId, accountNumber); | |
const { signature, signed } = await signer.signDirect(signerAddress, signDoc); | |
// returns txBytes for broadcast | |
return TxRaw.encode({ | |
bodyBytes: signed.bodyBytes, | |
authInfoBytes: signed.authInfoBytes, | |
signatures: [fromBase64(signature.signature)], | |
}).finish(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment