Skip to content

Commit

Permalink
ledger migration to v2
Browse files Browse the repository at this point in the history
  • Loading branch information
nnoln committed Sep 18, 2024
1 parent d697a86 commit 682b3f5
Show file tree
Hide file tree
Showing 4 changed files with 225 additions and 32 deletions.
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@
"release:dry": "release-it --dry-run"
},
"dependencies": {
"@cosmjs/encoding": "^0.31.0",
"@cosmjs/stargate": "^0.31.3",
"@cosmjs/encoding": "^0.32.2",
"@cosmjs/stargate": "^0.32.2",
"@cosmjs/cosmwasm-stargate": "^0.32.2",
"@ethersproject/abstract-signer": "^5.7.0",
"@ethersproject/wallet": "^5.7.0",
"axios": "^1.5.0",
Expand Down
75 changes: 65 additions & 10 deletions src/handlers/cosmos/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
export * from "./cctpProto";

import Long from "long";
import { fromBech32, toBech32, toUtf8 } from "@cosmjs/encoding";
import { calculateFee, Coin, GasPrice, StargateClient } from "@cosmjs/stargate";
import {
AminoTypes,
calculateFee,
Coin,
createIbcAminoConverters,
DeliverTxResponse,
GasPrice,
StargateClient,
} from "@cosmjs/stargate";
import { SigningCosmWasmClient, createWasmAminoConverters } from "@cosmjs/cosmwasm-stargate";

import {
CosmosSigner,
Expand Down Expand Up @@ -59,7 +69,7 @@ export class CosmosHandler {
}: {
data: ExecuteRoute;
params: RouteParamsPopulated;
}): Promise<TxRaw> {
}): Promise<TxRaw | DeliverTxResponse> {
await this.validateBalance({ data, params });

const { route } = data;
Expand Down Expand Up @@ -100,10 +110,35 @@ export class CosmosHandler {
throw new Error(`Cosmos message ${cosmosMsg.typeUrl} not supported`);
}

// This conversion is needed for Ledger, They only supports Amino messages
// TODO: At the moment there's a limit on Ledger Nano S models
// This limit prevents WASM_TYPE messages to be signed (because payload message is too big)
const aminoTypes = this.getAminoTypeConverters();
const firstMsg = msgs[0];
const formattedMsg = {
...firstMsg,
value: {
...firstMsg.value,
// Memo cannot be undefined, otherwise amino converter throws error
memo: (firstMsg.value as any).memo || "",
// Timeout wasn't formatted in the right way, so getting it manually
timeoutTimestamp: this.getTimeoutTimestamp(),
},
};

const aminoMsg = aminoTypes.toAmino(formattedMsg);
const fromAminoMsg = aminoTypes.fromAmino(aminoMsg);

// simulate tx to estimate gas cost
const estimatedGas = await signer.simulate(signerAddress, msgs, "");
const gasMultiplier = Number(route.transactionRequest?.maxFeePerGas) || 1.3;
const estimatedGas = await signer.simulate(signerAddress, [fromAminoMsg], "");

const gasMultiplier = Number(route.transactionRequest?.maxFeePerGas) || 1.5;

const gasPrice = route.transactionRequest?.gasPrice as string;
const fee = calculateFee(
Math.trunc(estimatedGas * gasMultiplier),
GasPrice.fromString(gasPrice),
);

let memo = "";
if (data.route.transactionRequest?.requestId) {
Expand All @@ -112,12 +147,32 @@ export class CosmosHandler {
});
}

return signer.sign(
signerAddress,
msgs,
calculateFee(Math.trunc(estimatedGas * gasMultiplier), GasPrice.fromString(gasPrice)),
memo,
);
const useBroadcast = data.useBroadcast ?? false;
if (useBroadcast) {
return (signer as SigningCosmWasmClient).signAndBroadcast(
signerAddress,
[fromAminoMsg],
fee,
memo,
);
}

return (signer as SigningCosmWasmClient).sign(signerAddress, [fromAminoMsg], fee, memo);
}

private getAminoTypeConverters(): AminoTypes {
return new AminoTypes({
...createIbcAminoConverters(),
...createWasmAminoConverters(),
});
}

private getTimeoutTimestamp(): number {
const PACKET_LIFETIME_NANOS = 3600 * 1_000_000_000; // 1 Hour

const currentTimeNanos = Math.floor(Date.now() * 1_000_000);
const timeoutTimestamp = Long.fromNumber(currentTimeNanos + PACKET_LIFETIME_NANOS);
return timeoutTimestamp.toNumber();
}

async getBalances({
Expand Down
8 changes: 5 additions & 3 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import {
RouteRequest,
RouteResponse as _RouteResponse,
} from "@0xsquid/squid-types";
import { SigningStargateClient } from "@cosmjs/stargate";
import { DeliverTxResponse, SigningStargateClient } from "@cosmjs/stargate";

import { EvmWallet, TransactionResponse, RpcProvider, Contract, GasData } from "./ethers";
import { TxRaw } from "cosmjs-types/cosmos/tx/v1beta1/tx";
import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";

export * from "@0xsquid/squid-types";
export * from "./cosmos";
Expand All @@ -34,22 +35,23 @@ export type ExecutionSettings = {
infiniteApproval?: boolean;
};

export type CosmosSigner = SigningStargateClient;
export type CosmosSigner = SigningStargateClient | SigningCosmWasmClient;

export type ExecuteRoute = {
signer: EvmWallet | CosmosSigner;
route: _RouteResponse["route"];
executionSettings?: ExecutionSettings;
overrides?: OverrideParams;
signerAddress?: string; // cosmos specific
useBroadcast?: boolean,
};

export type RouteResponse = _RouteResponse & {
requestId?: string;
integratorId?: string;
};

export type TransactionResponses = TransactionResponse | TxRaw;
export type TransactionResponses = TransactionResponse | TxRaw | DeliverTxResponse;

export type GetStatus = {
transactionId: string;
Expand Down
Loading

0 comments on commit 682b3f5

Please sign in to comment.