Skip to content

Commit

Permalink
Upstream changes from develop (#1195)
Browse files Browse the repository at this point in the history
* chore: upstream changes from dev to v4

* chore: upstream changes from dev to v4

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
  • Loading branch information
towanTG and github-actions[bot] authored Feb 18, 2025
1 parent 1694fe4 commit 1ee20b3
Show file tree
Hide file tree
Showing 16 changed files with 178 additions and 79 deletions.
4 changes: 2 additions & 2 deletions packages/helpers/src/modules/assetValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ export class AssetValue extends BigIntArithmetics {

warnOnce(
!(asyncTokenLookup || tokenDecimal),
`Couldn't find static decimal for ${unsafeIdentifier} (Using default ${BaseDecimal[chain]} decimal as fallback).
`Couldn't find static decimal for one or more tokens on ${chain} (Using default ${BaseDecimal[chain]} decimal as fallback).
This can result in incorrect calculations and mess with amount sent on transactions.
You can load static assets by installing @swapkit/tokens package and calling AssetValue.loadStaticAssets()
or by passing asyncTokenLookup: true to the from() function, which will make it async and return a promise.`,
Expand Down Expand Up @@ -181,7 +181,7 @@ or by passing asyncTokenLookup: true to the from() function, which will make it
for (const tokenList of Object.values(tokenPackage.tokenLists)) {
for (const { identifier, chain, ...rest } of tokenList.tokens) {
staticTokensMap.set(
chain !== "SOL" ? (identifier.toUpperCase() as TokenNames) : identifier,
chain === "SOL" ? identifier : (identifier.toUpperCase() as TokenNames),
{
identifier,
decimal: "decimals" in rest ? rest.decimals : BaseDecimal[chain as Chain],
Expand Down
57 changes: 29 additions & 28 deletions packages/plugins/src/chainflip/broker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const registerAsBroker = (toolbox: Awaited<ReturnType<typeof ChainflipToolbox>>)
throw new SwapKitError("chainflip_broker_register");
}

return toolbox.signAndBroadcast(extrinsic);
return toolbox.signAndBroadcast({ tx: extrinsic, address: toolbox.getAddress() });
};

const withdrawFee =
Expand All @@ -70,35 +70,36 @@ const withdrawFee =
throw new SwapKitError("chainflip_broker_withdraw");
}

toolbox.signAndBroadcast(extrinsic, async (result) => {
if (!result.status?.isFinalized) {
return;
}
toolbox.signAndBroadcast({
tx: extrinsic,
callback: async (result) => {
if (!result.status?.isFinalized) {
return;
}

const withdrawEvent = result.events.find(
(event) => event.event.method === "WithdrawalRequested",
);

if (!withdrawEvent) {
throw new SwapKitError(
"chainflip_channel_error",
"Could not find 'WithdrawalRequested' event",
const withdrawEvent = result.events.find(
(event) => event.event.method === "WithdrawalRequested",
);
}

const {
event: {
data: { egressId, egressAsset, egressAmount, egressFee, destinationAddress },
},
} = withdrawEvent.toHuman() as any;

resolve({
egressId,
egressAsset,
egressAmount,
egressFee,
destinationAddress,
});

if (!withdrawEvent) {
throw new SwapKitError(
"chainflip_channel_error",
"Could not find 'WithdrawalRequested' event",
);
}
const {
event: {
data: { egressId, egressAsset, egressAmount, egressFee, destinationAddress },
},
} = withdrawEvent.toHuman() as any;
resolve({
egressId,
egressAsset,
egressAmount,
egressFee,
destinationAddress,
});
},
});
});
};
Expand Down
32 changes: 24 additions & 8 deletions packages/toolboxes/src/cosmos/thorchainUtils/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ import type { ThorchainDepositTxParams, ThorchainTransferTxParams } from "./type

type MsgSend = ReturnType<typeof transferMsgAmino>;
type MsgDeposit = ReturnType<typeof depositMsgAmino>;
type MsgSendForBroadcast = ReturnType<typeof prepareMessageForBroadcast<MsgSend>>;
type MsgDepositForBroadcast = ReturnType<typeof prepareMessageForBroadcast<MsgDeposit>>;
type DirectMsgSendForBroadcast = ReturnType<typeof parseAminoMessageForDirectSigning<MsgSend>>;
type DirectMsgDepositForBroadcast = ReturnType<
typeof parseAminoMessageForDirectSigning<MsgDeposit>
>;

export const THORCHAIN_GAS_VALUE = getDefaultChainFee(Chain.THORChain).gas;
export const MAYA_GAS_VALUE = getDefaultChainFee(Chain.Maya).gas;
Expand Down Expand Up @@ -92,7 +94,7 @@ export const buildAminoMsg = ({

// TODO I think the msg typing is wrong it should be not prepared for broadcast
export const convertToSignable = (
msg: MsgDepositForBroadcast | MsgSendForBroadcast,
msg: DirectMsgDepositForBroadcast | DirectMsgSendForBroadcast | MsgSend | MsgDeposit,
chain: Chain.THORChain | Chain.Maya,
) => {
const aminoTypes = createDefaultAminoTypes(chain);
Expand Down Expand Up @@ -127,6 +129,7 @@ export const buildTransferTx =
memo = "",
chain,
asSignable = true,
asAminoMessage = false,
}: ThorchainTransferTxParams) => {
const account = await getAccount({ rpcUrl, from });

Expand All @@ -138,7 +141,10 @@ export const buildTransferTx =
});

const msg = asSignable
? convertToSignable(prepareMessageForBroadcast(transferMsg), chain)
? convertToSignable(
asAminoMessage ? transferMsg : parseAminoMessageForDirectSigning(transferMsg),
chain,
)
: transferMsg;

const transaction = {
Expand All @@ -155,13 +161,23 @@ export const buildTransferTx =

export const buildDepositTx =
(rpcUrl: string) =>
async ({ from, assetValue, memo = "", chain, asSignable = true }: ThorchainDepositTxParams) => {
async ({
from,
assetValue,
memo = "",
chain,
asSignable = true,
asAminoMessage = false,
}: ThorchainDepositTxParams) => {
const account = await getAccount({ rpcUrl, from });

const depositMsg = depositMsgAmino({ from, assetValue, memo, chain });

const msg = asSignable
? convertToSignable(prepareMessageForBroadcast<MsgDeposit>(depositMsg), chain)
? convertToSignable(
asAminoMessage ? depositMsg : parseAminoMessageForDirectSigning<MsgDeposit>(depositMsg),
chain,
)
: depositMsg;

const transaction = {
Expand All @@ -176,7 +192,7 @@ export const buildDepositTx =
return transaction;
};

export function prepareMessageForBroadcast<T extends MsgDeposit | MsgSend>(msg: T) {
export function parseAminoMessageForDirectSigning<T extends MsgDeposit | MsgSend>(msg: T) {
if (msg.type === "thorchain/MsgSend" || msg.type === "mayachain/MsgSend") return msg as MsgSend;

return {
Expand Down Expand Up @@ -212,7 +228,7 @@ export const buildEncodedTxBody = ({
memo,
msgs,
}: {
msgs: MsgSendForBroadcast[] | MsgDepositForBroadcast[];
msgs: DirectMsgDepositForBroadcast[] | DirectMsgSendForBroadcast[];
memo: string;
chain: Chain.THORChain | Chain.Maya;
}) => {
Expand Down
14 changes: 10 additions & 4 deletions packages/toolboxes/src/cosmos/thorchainUtils/types/client-types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import type { MultisigThresholdPubkey, Pubkey, Secp256k1HdWallet } from "@cosmjs/amino";
import type {
MultisigThresholdPubkey,
OfflineAminoSigner,
Pubkey,
Secp256k1HdWallet,
} from "@cosmjs/amino";
import type { EncodeObject, OfflineDirectSigner, Registry } from "@cosmjs/proto-signing";
import type { AminoTypes, Account as CosmosAccount } from "@cosmjs/stargate";
import type { Asset, AssetValue, Chain, ChainId, SwapKitNumber } from "@swapkit/helpers";
Expand All @@ -9,7 +14,7 @@ import type {
buildEncodedTxBody,
buildTransferTx,
convertToSignable,
prepareMessageForBroadcast,
parseAminoMessageForDirectSigning,
} from "../../index";
import type { Signer, TransferParams } from "../../types";

Expand All @@ -33,7 +38,7 @@ export type NodeUrl = {
};

export type DepositParam = {
signer?: OfflineDirectSigner;
signer?: OfflineDirectSigner | OfflineAminoSigner;
walletIndex?: number;
assetValue: AssetValue;
memo: string;
Expand Down Expand Up @@ -91,6 +96,7 @@ export type ThorchainTransferTxParams = {
memo?: string;
chain: Chain.THORChain | Chain.Maya;
asSignable?: boolean;
asAminoMessage?: boolean;
};

export type ThorchainDepositTxParams = Omit<ThorchainTransferTxParams, "recipient">;
Expand Down Expand Up @@ -123,7 +129,7 @@ export type ThorchainToolboxType = BaseCosmosToolboxType & {
params: ThorchainDepositTxParams,
) => ReturnType<ReturnType<typeof buildDepositTx>>;
buildEncodedTxBody: typeof buildEncodedTxBody;
prepareMessageForBroadcast: typeof prepareMessageForBroadcast;
parseAminoMessageForDirectSigning: typeof parseAminoMessageForDirectSigning;
createMultisig: (pubKeys: string[], threshold: number) => Promise<MultisigThresholdPubkey>;
importSignature: (signature: string) => Uint8Array;
secp256k1HdWalletFromMnemonic: (mnemonic: string, index?: number) => Promise<Secp256k1HdWallet>;
Expand Down
47 changes: 39 additions & 8 deletions packages/toolboxes/src/cosmos/toolbox/thorchain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import {
convertToSignable,
createDefaultAminoTypes,
createDefaultRegistry,
prepareMessageForBroadcast,
parseAminoMessageForDirectSigning,
} from "../thorchainUtils/index";
import type {
DepositParam,
Expand All @@ -45,6 +45,7 @@ import {
getDefaultChainFee,
} from "../util";

import { TxRaw } from "cosmjs-types/cosmos/tx/v1beta1/tx";
import { BaseCosmosToolbox } from "./BaseCosmosToolbox";

function secp256k1HdWalletFromMnemonic({
Expand Down Expand Up @@ -91,7 +92,6 @@ async function signMultisigTx(
const msgForSigning = [];

for (const msg of msgs) {
// @ts-expect-error wrong typing of convertToSignable - investigation needed
const signMsg = convertToSignable(msg, chain);
msgForSigning.push(signMsg);
}
Expand All @@ -104,7 +104,11 @@ async function signMultisigTx(
chainId,
});

const bodyBytes = buildEncodedTxBody({ chain, memo, msgs: msgs.map(prepareMessageForBroadcast) });
const bodyBytes = buildEncodedTxBody({
chain,
memo,
msgs: msgs.map(parseAminoMessageForDirectSigning),
});

return { signature: exportSignature(signature as Uint8Array), bodyBytes };
}
Expand Down Expand Up @@ -236,17 +240,44 @@ export function BaseThorchainToolbox(chain: Chain.THORChain | Chain.Maya): Thorc
}: Omit<TransferParams, "recipient"> & { recipient?: string }) {
if (!signer) throw new Error("Signer not defined");

const isAminoSigner = "signAmino" in signer;
const registry = createDefaultRegistry();
const aminoTypes = createDefaultAminoTypes(chain);
const signingClient = await createSigningStargateClient(rpcUrl, signer, {
registry,
aminoTypes,
});

const msgSign = convertToSignable(
prepareMessageForBroadcast(buildAminoMsg({ assetValue, from, recipient, memo, chain })),
chain,
);
const aminoMessage = buildAminoMsg({ assetValue, from, recipient, memo, chain });

if (isAminoSigner) {
const msgSign = [convertToSignable(aminoMessage, chain)];

const { signatures, authInfoBytes } = await signingClient.sign(
from,
msgSign,
defaultFee,
memo,
);

const tx = TxRaw.encode({
signatures,
authInfoBytes,
bodyBytes: await buildEncodedTxBody({
chain,
msgs: [aminoMessage].map(parseAminoMessageForDirectSigning),
memo,
}),
}).finish();

const txResponse = await signingClient.broadcastTx(tx);

return txResponse.transactionHash;
}

const preparedMessage = parseAminoMessageForDirectSigning(aminoMessage);

const msgSign = convertToSignable(preparedMessage, chain);

const txResponse = await signingClient.signAndBroadcast(from, [msgSign], defaultFee, memo);

Expand All @@ -263,7 +294,7 @@ export function BaseThorchainToolbox(chain: Chain.THORChain | Chain.Maya): Thorc
buildDepositTx: buildDepositTx(rpcUrl),
buildTransferTx: buildTransferTx(rpcUrl),
buildEncodedTxBody,
prepareMessageForBroadcast,
parseAminoMessageForDirectSigning,
createDefaultAminoTypes: () => createDefaultAminoTypes(chain),
createDefaultRegistry,
secp256k1HdWalletFromMnemonic: secp256k1HdWalletFromMnemonic({
Expand Down
42 changes: 36 additions & 6 deletions packages/toolboxes/src/substrate/toolbox/baseSubstrateToolbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ const sign = async (signer: IKeyringPair, tx: SubmittableExtrinsic<"promise">) =
return signedTx;
};

const signAndBroadcast = (
const signAndBroadcastKeyring = (
signer: IKeyringPair,
tx: SubmittableExtrinsic<"promise">,
callback?: Callback<ISubmittableResult>,
Expand All @@ -145,6 +145,27 @@ const signAndBroadcast = (
return hash.toString();
};

const signAndBroadcast = async ({
signer,
address,
tx,
callback,
api,
}: {
signer: Signer;
address: string;
tx: SubmittableExtrinsic<"promise">;
api: ApiPromise;
callback?: Callback<ISubmittableResult>;
}) => {
const nonce = await getNonce(api, address);
if (callback) {
tx.signAndSend(address, { nonce, signer }, callback);
}
const hash = tx.signAndSend(address, { nonce, signer });
return hash.toString();
};

function convertAddress(address: string, newPrefix: number) {
const decodedAddress = decodePolkadotAddress(address);
const convertedAddress = encodePolkadotAddress(decodedAddress, newPrefix);
Expand Down Expand Up @@ -207,12 +228,21 @@ export const BaseSubstrateToolbox = ({
},
broadcast: (tx: SubmittableExtrinsic<"promise">, callback?: Callback<ISubmittableResult>) =>
broadcast(tx, callback),
signAndBroadcast: (
tx: SubmittableExtrinsic<"promise">,
callback?: Callback<ISubmittableResult>,
) => {
signAndBroadcast: ({
tx,
callback,
address,
}: {
tx: SubmittableExtrinsic<"promise">;
callback?: Callback<ISubmittableResult>;
address?: string;
}) => {
if (isKeyringPair(signer)) {
return signAndBroadcast(signer, tx, callback);
return signAndBroadcastKeyring(signer, tx, callback);
}

if (address) {
return signAndBroadcast({ signer, address, tx, callback, api });
}

throw new SwapKitError(
Expand Down
2 changes: 1 addition & 1 deletion packages/toolboxes/src/utxo/toolbox/utxo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ function getInputsAndTargetOutputs(chain: UTXOChain) {
};
}

function buildTx(chain: UTXOChain) {
export function buildTx(chain: UTXOChain) {
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO: refactor
return async function buildTx({
assetValue,
Expand Down
Loading

0 comments on commit 1ee20b3

Please sign in to comment.