Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use station that is injected into the window object #6

Merged
merged 2 commits into from
Aug 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "cosmes",
"version": "0.0.27",
"version": "0.0.28",
"private": false,
"packageManager": "pnpm@8.3.0",
"sideEffects": false,
Expand Down
12 changes: 5 additions & 7 deletions src/wallet/wallets/station/StationController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,16 @@ import { ConnectedWallet } from "../ConnectedWallet";
import { ChainInfo, WalletController } from "../WalletController";
import { StationExtension } from "./StationExtension";
import { StationWalletConnectV1 } from "./StationWalletConnectV1";
import { ExtensionDispatcher } from "./extension/ExtensionDispatcher";

const TERRA_CLASSIC_CHAIN_ID = "columbus-5";
const TERRA_CHAIN_ID = "phoenix-1";
const TERRA_CHAINS = [TERRA_CLASSIC_CHAIN_ID, TERRA_CHAIN_ID];

export class StationController extends WalletController {
private readonly ext: ExtensionDispatcher;
private readonly wc: WalletConnectV1;

constructor() {
super(WalletName.STATION);
this.ext = new ExtensionDispatcher();
this.wc = new WalletConnectV1(
"cosmes.wallet.station.wcSession",
{
Expand All @@ -40,7 +37,7 @@ export class StationController extends WalletController {
}

public async isInstalled(type: WalletType) {
return type === WalletType.EXTENSION ? this.ext.isInstalled() : true;
return type === WalletType.EXTENSION ? "station" in window : true;
}

protected async connectWalletConnect<T extends string>(
Expand Down Expand Up @@ -73,10 +70,11 @@ export class StationController extends WalletController {

protected async connectExtension<T extends string>(chains: ChainInfo<T>[]) {
const wallets = new Map<T, ConnectedWallet>();
if (!this.ext.isInstalled()) {
const ext = window.station;
if (!ext) {
throw new Error("Station extension is not installed");
}
const { addresses, pubkey } = await this.ext.connect();
const { addresses, pubkey } = await ext.connect();
// Station will only return one or the other, but not both
// so we simply set the other one manually
addresses[TERRA_CLASSIC_CHAIN_ID] ??= addresses[TERRA_CHAIN_ID];
Expand All @@ -93,7 +91,7 @@ export class StationController extends WalletController {
await this.getPubKey(rpc, address);
wallets.set(
chainId,
new StationExtension(this.ext, chainId, key, address, rpc, gasPrice)
new StationExtension(ext, chainId, key, address, rpc, gasPrice)
);
}
return wallets;
Expand Down
51 changes: 32 additions & 19 deletions src/wallet/wallets/station/StationExtension.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { PlainMessage } from "@bufbuild/protobuf";
import { Adapter } from "cosmes/client";
import { fromStringToBase64 } from "cosmes/codec";
import { CosmosBaseV1beta1Coin as Coin } from "cosmes/protobufs";

import { WalletName } from "../../constants/WalletName";
Expand All @@ -10,13 +11,14 @@ import {
SignArbitraryResponse,
UnsignedTx,
} from "../ConnectedWallet";
import { ExtensionDispatcher } from "./extension/ExtensionDispatcher";
import { Station } from "./types";
import { toStationTx } from "./utils/toStationTx";

export class StationExtension extends ConnectedWallet {
private readonly ext: ExtensionDispatcher;
private readonly ext: Station;

constructor(
ext: ExtensionDispatcher,
ext: Station,
chainId: string,
pubKey: Adapter,
address: string,
Expand All @@ -36,14 +38,13 @@ export class StationExtension extends ConnectedWallet {
}

public async signArbitrary(data: string): Promise<SignArbitraryResponse> {
const { result, error } = await this.ext.signBytes(data);
if (error) {
throw new Error(error.message);
}
const { public_key, signature } = await this.normaliseError(
this.ext.signBytes(fromStringToBase64(data), true)
);
return {
data,
pubKey: result.public_key,
signature: result.signature,
pubKey: public_key,
signature: signature,
};
}

Expand All @@ -53,18 +54,30 @@ export class StationExtension extends ConnectedWallet {
): Promise<string> {
const { fee } = await this.prepBroadcastTx(unsignedTx, opts);
const { msgs, memo } = unsignedTx;
const { result, error } = await this.ext.signAndBroadcast(
this.chainId,
fee,
msgs,
memo
const { code, raw_log, txhash } = await this.normaliseError(
this.ext.post(toStationTx(this.chainId, fee, msgs, memo), true)
);
if (error) {
throw new Error(error.message);
if (code) {
throw new Error(raw_log);
}
if (result.code) {
throw new Error(result.raw_log);
return txhash;
}

/**
* Normalises the error thrown by the Station extension into a standard `Error`
* instance. Returns the result of the `promise` if it resolves successfully.
*/
private async normaliseError<T>(promise: Promise<T>): Promise<T> {
try {
return await promise;
} catch (err) {
if (typeof err === "string") {
throw new Error(err);
}
if (err instanceof Error) {
throw err;
}
throw new Error("Unknown error from Station extension: " + err);
}
return result.txhash;
}
}
4 changes: 2 additions & 2 deletions src/wallet/wallets/station/StationWalletConnectV1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export class StationWalletConnectV1 extends ConnectedWallet {
}

public async signArbitrary(data: string): Promise<SignArbitraryResponse> {
const res = await this.sendRequest<SignBytesResponse["result"]>(
const res = await this.sendRequest<SignBytesResponse>(
"signBytes",
fromStringToBase64(data)
);
Expand All @@ -57,7 +57,7 @@ export class StationWalletConnectV1 extends ConnectedWallet {
): Promise<string> {
const { fee } = await this.prepBroadcastTx(unsignedTx, opts);
const { msgs, memo } = unsignedTx;
const { txhash } = await this.sendRequest<PostResponse["result"]>(
const { txhash } = await this.sendRequest<PostResponse>(
"post",
toStationTx(this.chainId, fee, msgs, memo)
);
Expand Down
111 changes: 0 additions & 111 deletions src/wallet/wallets/station/extension/ExtensionDispatcher.ts

This file was deleted.

42 changes: 24 additions & 18 deletions src/wallet/wallets/station/types.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,24 @@
export type Window = {
isStationExtensionAvailable: boolean;
station: Station;
};

type ErrorResponse = {
code: number;
message: string;
/**
* A subset of the Station extension API that is injected into the `window` object.
*
* @see https://github.com/terra-money/wallet-kit/blob/79600bb096d64754160909871dfdf89944120ce8/src/%40terra-money/station-connector/index.ts#L66
*/
export type Station = {
connect: () => Promise<ConnectResponse>;
getPublicKey: () => Promise<GetPubKeyResponse>;
signBytes(bytes: string, purgeQueue?: boolean): Promise<SignBytesResponse>;
post: (tx: StationTx, purgeQueue?: boolean) => Promise<PostResponse>;
};

export type StationTx = {
chainID: string;
msgs: string[];
fee?: string;
memo?: string;
};

export type ConnectResponse = {
Expand Down Expand Up @@ -36,21 +50,13 @@ export type GetPubKeyResponse = {
};

export type SignBytesResponse = {
success: boolean;
result: {
public_key: string;
signature: string;
recid: number;
};
error?: ErrorResponse | undefined;
public_key: string;
signature: string;
recid: number;
};

export type PostResponse = {
success: boolean;
result: {
code?: number | undefined;
raw_log: string;
txhash: string;
};
error?: ErrorResponse | undefined;
code?: number | undefined;
raw_log: string;
txhash: string;
};
4 changes: 3 additions & 1 deletion src/wallet/wallets/station/utils/toStationTx.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { Adapter } from "cosmes/client";
import { CosmosTxV1beta1Fee as Fee } from "cosmes/protobufs";

import { StationTx } from "../types";

/**
* Translates the given args to a tx that can be sent to either
* the Station extension wallet or WalletConnect wallet.
Expand All @@ -10,7 +12,7 @@ export function toStationTx(
fee: Fee,
msgs: Adapter[],
memo?: string | undefined
) {
): StationTx {
return {
chainID: chainId,
fee: toStationFee(fee),
Expand Down
Loading