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

Custom nonce update #386

Merged
merged 4 commits into from
Aug 14, 2024
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
4 changes: 4 additions & 0 deletions packages/fetch-extension/src/stores/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ export class RootStore {
public readonly proposalStore: ProposalStore;
public readonly activityStore: ActivityStore;
public readonly tokenGraphStore: TokenGraphStore;
public readonly accountBaseStore: ExtensionKVStore;

protected readonly interactionStore: InteractionStore;
public readonly permissionStore: PermissionStore;
Expand Down Expand Up @@ -249,11 +250,14 @@ export class RootStore {
this.chainStore
);

this.accountBaseStore = new ExtensionKVStore("store_account_config");

this.accountStore = new AccountStore(
window,
this.chainStore,
this.activityStore,
this.tokenGraphStore,
this.accountBaseStore,
() => {
return {
suggestChain: false,
Expand Down
30 changes: 28 additions & 2 deletions packages/stores/src/account/base.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,30 @@ import { AccountSetBase, WalletStatus } from "./base";
import { ChainStore } from "../chain";
import { AppCurrency, ChainInfo } from "@keplr-wallet/types";
import { MockKeplr } from "@keplr-wallet/provider-mock";
import { KVStore } from "@keplr-wallet/common";

class MockKVStore implements KVStore {
private store: Map<string, any> = new Map();
private prefixValue: string = "mock-prefix";

async get<T = unknown>(key: string): Promise<T | undefined> {
return this.store.get(key) as T | undefined;
}

async set<T = unknown>(key: string, data: T | null): Promise<void> {
if (data === null) {
this.store.delete(key);
} else {
this.store.set(key, data);
}
}

prefix(): string {
return this.prefixValue;
}
}

const accountBaseKVStore = new MockKVStore();

describe("Test Account set base", () => {
test("Account set base should be inited automatically if `autoInit` is true", async () => {
Expand Down Expand Up @@ -43,7 +67,8 @@ describe("Test Account set base", () => {
"curious kitchen brief change imitate open close knock cause romance trim offer"
);
},
}
},
accountBaseKVStore
);

expect(accountSetBase.walletStatus).toBe(WalletStatus.Loading);
Expand Down Expand Up @@ -101,7 +126,8 @@ describe("Test Account set base", () => {
"curious kitchen brief change imitate open close knock cause romance trim offer"
);
},
}
},
accountBaseKVStore
);

expect(accountSetBase.walletStatus).toBe(WalletStatus.NotInit);
Expand Down
56 changes: 54 additions & 2 deletions packages/stores/src/account/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import {
StdFee,
} from "@keplr-wallet/types";
import { ChainGetter } from "../common";
import { DenomHelper, toGenerator } from "@keplr-wallet/common";
import { KVStore, DenomHelper, toGenerator } from "@keplr-wallet/common";
import { Bech32Address } from "@keplr-wallet/cosmos";
import { MakeTxResponse } from "./types";
import { Int } from "@keplr-wallet/unit";

export enum WalletStatus {
NotInit = "NotInit",
Expand Down Expand Up @@ -48,6 +49,10 @@ export class AccountSetBase {

@observable
protected _bech32Address: string = "";

@observable
protected _customSequence: Int = new Int(0);

@observable
protected _isNanoLedger: boolean = false;
@observable
Expand Down Expand Up @@ -89,7 +94,8 @@ export class AccountSetBase {
},
protected readonly chainGetter: ChainGetter,
protected readonly chainId: string,
protected readonly opts: AccountSetOpts
protected readonly opts: AccountSetOpts,
protected readonly kvStore: KVStore
) {
makeObservable(this);

Expand Down Expand Up @@ -200,6 +206,16 @@ export class AccountSetBase {
this._name = key.name;
this._pubKey = key.pubKey;

if (this._bech32Address) {
const savedTxnNonce =
(yield* toGenerator(
this.kvStore.get<any>(
`extension_txn_nonce-${this.bech32Address}-${this.chainId}`
)
)) || 0;
this._customSequence = new Int(savedTxnNonce);
}

// Set the wallet status as loaded after getting all necessary infos.
this._walletStatus = WalletStatus.Loaded;
} catch (e) {
Expand Down Expand Up @@ -331,6 +347,10 @@ export class AccountSetBase {
return this._bech32Address;
}

get customSequence(): Int {
return this._customSequence;
}

get pubKey(): Uint8Array {
return this._pubKey.slice();
}
Expand Down Expand Up @@ -377,6 +397,38 @@ export class AccountSetBase {
this.chainGetter.getChain(this.chainId).bech32Config.bech32PrefixAccAddr
).toHex(true);
}

@action
setCustomNonce(nonce: Int): void {
let newNonce = new Int(0);
if (nonce.gt(this._customSequence)) {
newNonce = nonce;
} else {
newNonce = this._customSequence;
}
this._customSequence = newNonce;
this.saveNonce();
}

@action
increaseCustomSequence(): void {
this._customSequence = this._customSequence.add(new Int(1));
this.saveNonce();
}

@flow
*saveNonce() {
yield this.kvStore.set<any>(
`extension_txn_nonce-${this._bech32Address}-${this.chainId}`,
JSON.parse(JSON.stringify(this._customSequence.toString()))
);
}

@action
resetCustomNonce(nonce: Int): void {
this._customSequence = nonce;
this.saveNonce();
}
}

export class AccountSetBaseSuper extends AccountSetBase {
Expand Down
14 changes: 13 additions & 1 deletion packages/stores/src/account/cosmos.ts
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,14 @@ export class CosmosAccountImpl {
this.base.setTxTypeInProgress("");
this.activityStore.setPendingTxnTypes(type, false);

// resetting custom nonce here
const account = await BaseAccount.fetchFromRest(
this.chainGetter.getChain(this.chainId).rest,
this.base.bech32Address,
true
);
this.base.resetCustomNonce(account.getSequence());

if (this.txOpts.preTxEvents?.onBroadcastFailed) {
this.txOpts.preTxEvents.onBroadcastFailed(this.chainId, e);
}
Expand Down Expand Up @@ -584,10 +592,12 @@ export class CosmosAccountImpl {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const keplr = (await this.base.getKeplr())!;

this.base.setCustomNonce(account.getSequence());

const signDocRaw: StdSignDoc = {
chain_id: this.chainId,
account_number: account.getAccountNumber().toString(),
sequence: account.getSequence().toString(),
sequence: this.base.customSequence.toString(),
fee: fee,
msgs: aminoMsgs,
memo: escapeHTML(memo),
Expand Down Expand Up @@ -718,6 +728,8 @@ export class CosmosAccountImpl {
: [new Uint8Array(0)],
}).finish();

this.base.increaseCustomSequence();

return {
txHash: await keplr.sendTx(this.chainId, signedTx, mode as BroadcastMode),
signDoc: signResponse.signed,
Expand Down
5 changes: 4 additions & 1 deletion packages/stores/src/account/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
import { AccountSetBase, AccountSetBaseSuper, AccountSetOpts } from "./base";
import { DeepReadonly, UnionToIntersection } from "utility-types";
import { TokenGraphStore } from "src/token-graph";
import { KVStore } from "@keplr-wallet/common";

// eslint-disable-next-line @typescript-eslint/ban-types
export interface IAccountStore<T extends IObject = {}> {
Expand All @@ -35,6 +36,7 @@ export class AccountStore<
protected readonly chainGetter: ChainGetter,
protected readonly activityStore: ActivityStore,
protected readonly tokenGraphStore: TokenGraphStore,
protected readonly accountBaseStore: KVStore,
protected readonly storeOptsCreator: (chainId: string) => AccountSetOpts,
...accountSetCreators: ChainedFunctionifyTuple<
AccountSetBaseSuper,
Expand All @@ -49,7 +51,8 @@ export class AccountStore<
eventListener,
chainGetter,
chainId,
storeOptsCreator(chainId)
storeOptsCreator(chainId),
this.accountBaseStore
);

return mergeStores(
Expand Down
Loading