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

refactor: Created utils package #265

Merged
merged 19 commits into from
May 17, 2022
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
9b8b784
Created basic package, exported isMobile method and replaced is-mobi…
amirsaran3 Apr 18, 2022
eb94625
Fixed parseBigNumber and parseNearAmount
amirsaran3 Apr 20, 2022
56d1f44
Merge branch 'dev' of https://github.com/near-projects/wallet-selecto…
amirsaran3 Apr 25, 2022
83eda63
Merge branch 'dev' of https://github.com/near-projects/wallet-selecto…
amirsaran3 Apr 28, 2022
d35b4f8
Added createAction and createTransaction
amirsaran3 Apr 28, 2022
9c3a5a3
Added createTransaction to near-wallet
amirsaran3 Apr 28, 2022
e05b6d9
Resolved conflicts with dev
amirsaran3 May 9, 2022
eb79fbe
Created wallet-utils package, added signTransactions
amirsaran3 May 11, 2022
e67d9ae
Fixed build errors, removed parse methods
amirsaran3 May 11, 2022
72d9401
Fixed math-wallet and ledger implementations of signTransactions
amirsaran3 May 11, 2022
2f137c0
Removed utils package, split up wallet-utils.ts, removed wallet.ts
amirsaran3 May 12, 2022
b610a4b
Adjusted param type of signTransactions method
amirsaran3 May 16, 2022
980cab1
Resolved conflicts
amirsaran3 May 16, 2022
20952dc
Fixed issue with rpc networkId
amirsaran3 May 16, 2022
4112715
Changed createAction param to be object not array
amirsaran3 May 16, 2022
3dff3d4
Removed accountId param from signTransactions
amirsaran3 May 16, 2022
3d88778
Fixed wallet-utils test
amirsaran3 May 16, 2022
d270d9c
Fixed defaulting for signing transactions
amirsaran3 May 16, 2022
2a3837b
Defaulted to first account when signerId not provided
amirsaran3 May 17, 2022
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"build:near-wallet": "nx run-many --target=build --projects=near-wallet --configuration=production",
"build:sender": "nx run-many --target=build --projects=sender --configuration=production",
"build:wallet-connect": "nx run-many --target=build --projects=wallet-connect --configuration=production",
"build:wallet-utils": "nx run-many --target=build --projects=wallet-utils --configuration=production",
"lint": "nx workspace-lint && nx run-many --target=lint --all --parallel",
"lint:fix": "nx run-many --target=lint --all --fix",
"serve:react": "nx serve react",
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ export {
AddKeyAction,
DeleteKeyAction,
DeleteAccountAction,
AddKeyPermission,
} from "./lib/wallet";

export { FinalExecutionOutcome } from "near-api-js/lib/providers";

export { transformActions } from "./lib/wallet";
export { waitFor } from "./lib/helpers";
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Provider, QueryParams, ViewAccessKeyParams } from "./provider.service";
import { Provider } from "./provider.service";
import { QueryParams, ViewAccessKeyParams } from "./provider.service.types";
import { mock } from "jest-mock-extended";
import {
FinalExecutionOutcome,
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/lib/wallet/transactions.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Action } from "./transactions.types";
import { AddKeyPermission } from "./transactions.types";
import { transactions, utils } from "near-api-js";
import { BN } from "bn.js";

import { Action, AddKeyPermission } from "./transactions.types";
import BN from "bn.js";

const getAccessKey = (permission: AddKeyPermission) => {
if (permission === "FullAccess") {
Expand Down
112 changes: 47 additions & 65 deletions packages/ledger/src/lib/ledger.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
import { transactions as nearTransactions, utils } from "near-api-js";
import { isMobile } from "is-mobile";
import { TypedError } from "near-api-js/lib/utils/errors";
import isMobile from "is-mobile";
import { signTransactions } from "@near-wallet-selector/wallet-utils";
import {
WalletModuleFactory,
WalletBehaviourFactory,
WalletBehaviourOptions,
AccountState,
HardwareWallet,
transformActions,
Transaction,
Optional,
} from "@near-wallet-selector/core";

import { isLedgerSupported, LedgerClient, Subscription } from "./ledger-client";
import { Signer, utils } from "near-api-js";

interface AuthData {
accountId: string;
Expand Down Expand Up @@ -60,6 +58,34 @@ const Ledger: WalletBehaviourFactory<HardwareWallet> = async ({
}) => {
const _state = setupLedgerState(storage);

const signer: Signer = {
createKey: () => {
throw Error("Not implemented");
},
getPublicKey: async () => {
if (!_state.authData) {
throw new Error(`${metadata.name} not connected`);
}

return utils.PublicKey.from(_state.authData.publicKey);
},
signMessage: async (message: Uint8Array) => {
if (!_state.authData) {
throw new Error(`${metadata.name} not connected`);
}

const signature = await _state.client.sign({
data: message,
derivationPath: _state.authData.derivationPath,
});

return {
signature,
publicKey: utils.PublicKey.from(_state.authData.publicKey),
};
},
};

const getAccounts = (
authData: AuthData | null = _state.authData
): Array<AccountState> => {
Expand Down Expand Up @@ -146,58 +172,6 @@ const Ledger: WalletBehaviourFactory<HardwareWallet> = async ({
return accountIds[0];
};

const signTransactions = async (
transactions: Array<Optional<Transaction, "signerId">>
) => {
if (!_state.authData) {
throw new Error(`${metadata.name} not connected`);
}

const { accountId, derivationPath, publicKey } = _state.authData;

const [block, accessKey] = await Promise.all([
provider.block({ finality: "final" }),
provider.viewAccessKey({ accountId, publicKey }),
]);

const signedTransactions: Array<nearTransactions.SignedTransaction> = [];

for (let i = 0; i < transactions.length; i++) {
const actions = transformActions(transactions[i].actions);

const transaction = nearTransactions.createTransaction(
accountId,
utils.PublicKey.from(publicKey),
transactions[i].receiverId,
accessKey.nonce + i + 1,
actions,
utils.serialize.base_decode(block.header.hash)
);

const serializedTx = utils.serialize.serialize(
nearTransactions.SCHEMA,
transaction
);

const signature = await _state.client.sign({
data: serializedTx,
derivationPath,
});

const signedTx = new nearTransactions.SignedTransaction({
transaction,
signature: new nearTransactions.Signature({
keyType: transaction.publicKey.keyType,
data: signature,
}),
});

signedTransactions.push(signedTx);
}

return signedTransactions;
};

return {
async connect({ derivationPath }) {
const existingAccounts = getAccounts();
Expand Down Expand Up @@ -266,14 +240,18 @@ const Ledger: WalletBehaviourFactory<HardwareWallet> = async ({
// Note: Connection must be triggered by user interaction.
await connectLedgerDevice();

const [signedTx] = await signTransactions([
{
receiverId,
actions,
},
]);
const signedTransactions = await signTransactions(
[
{
receiverId,
actions,
},
],
signer,
_state.authData.accountId
);

return provider.sendTransaction(signedTx);
return provider.sendTransaction(signedTransactions[0]);
},

async signAndSendTransactions({ transactions }) {
Expand All @@ -286,7 +264,11 @@ const Ledger: WalletBehaviourFactory<HardwareWallet> = async ({
// Note: Connection must be triggered by user interaction.
await connectLedgerDevice();

const signedTransactions = await signTransactions(transactions);
const signedTransactions = await signTransactions(
transactions,
signer,
_state.authData.accountId
);

return Promise.all(
signedTransactions.map((signedTx) => provider.sendTransaction(signedTx))
Expand Down
66 changes: 16 additions & 50 deletions packages/math-wallet/src/lib/math-wallet.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import { transactions as nearTransactions, utils } from "near-api-js";
import isMobile from "is-mobile";
import { isMobile } from "is-mobile";
import {
WalletModuleFactory,
WalletBehaviourFactory,
InjectedWallet,
AccountState,
transformActions,
waitFor,
} from "@near-wallet-selector/core";

import { InjectedMathWallet } from "./injected-math-wallet";
import { signTransactions } from "@near-wallet-selector/wallet-utils";

declare global {
interface Window {
Expand Down Expand Up @@ -114,33 +113,18 @@ const MathWallet: WalletBehaviourFactory<InjectedWallet> = async ({
throw new Error("Wallet not connected");
}

const { accountId, publicKey } = account;
const [block, accessKey] = await Promise.all([
provider.block({ finality: "final" }),
provider.viewAccessKey({ accountId, publicKey }),
]);

logger.log("MathWallet:signAndSendTransaction:block", block);
logger.log("MathWallet:signAndSendTransaction:accessKey", accessKey);

const transaction = nearTransactions.createTransaction(
accountId,
utils.PublicKey.from(publicKey),
receiverId,
accessKey.nonce + 1,
transformActions(actions),
utils.serialize.base_decode(block.header.hash)
);

const [hash, signedTx] = await nearTransactions.signTransaction(
transaction,
const signedTransactions = await signTransactions(
[
{
receiverId,
actions,
},
],
_state.wallet.signer,
accountId
account.accountId
);

logger.log("MathWallet:signAndSendTransaction:hash", hash);

return provider.sendTransaction(signedTx);
return provider.sendTransaction(signedTransactions[0]);
},

async signAndSendTransactions({ transactions }) {
Expand All @@ -161,29 +145,11 @@ const MathWallet: WalletBehaviourFactory<InjectedWallet> = async ({
logger.log("MathWallet:signAndSendTransactions:block", block);
logger.log("MathWallet:signAndSendTransactions:accessKey", accessKey);

const signedTransactions: Array<nearTransactions.SignedTransaction> = [];
let nonce = accessKey.nonce;

for (let i = 0; i < transactions.length; i++) {
const transaction = nearTransactions.createTransaction(
accountId,
utils.PublicKey.from(publicKey),
transactions[i].receiverId,
++nonce,
transformActions(transactions[i].actions),
utils.serialize.base_decode(block.header.hash)
);

const [hash, signedTx] = await nearTransactions.signTransaction(
transaction,
_state.wallet.signer,
accountId
);

logger.log("MathWallet:signAndSendTransactions:hash", hash);

signedTransactions.push(signedTx);
}
const signedTransactions = await signTransactions(
transactions,
_state.wallet.signer,
accountId
);

logger.log(
"MathWallet:signAndSendTransactions:signedTransactions",
Expand Down
19 changes: 12 additions & 7 deletions packages/near-wallet/src/lib/near-wallet.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import { WalletConnection, connect, keyStores, utils } from "near-api-js";
import * as nearApi from "near-api-js";
import {
WalletConnection,
connect,
keyStores,
transactions as nearTransactions,
utils,
} from "near-api-js";
import {
WalletModuleFactory,
WalletBehaviourFactory,
BrowserWallet,
Transaction,
Optional,
transformActions,
Network,
} from "@near-wallet-selector/core";
import { createAction } from "@near-wallet-selector/wallet-utils";

export interface NearWalletParams {
walletUrl?: string;
Expand Down Expand Up @@ -95,10 +100,10 @@ const NearWallet: WalletBehaviourFactory<

return Promise.all(
transactions.map(async (transaction, index) => {
const actions = transformActions(transaction.actions);
const actions = createAction(transaction.actions);
const accessKey = await account.accessKeyForTransaction(
transaction.receiverId,
actions,
createAction(transaction.actions),
localKey
);

Expand All @@ -110,7 +115,7 @@ const NearWallet: WalletBehaviourFactory<

const block = await provider.block({ finality: "final" });

return nearApi.transactions.createTransaction(
return nearTransactions.createTransaction(
account.accountId,
utils.PublicKey.from(accessKey.public_key),
transaction.receiverId,
Expand Down Expand Up @@ -169,7 +174,7 @@ const NearWallet: WalletBehaviourFactory<

return account["signAndSendTransaction"]({
receiverId,
actions: transformActions(actions),
actions: createAction(actions),
}).then(() => {
// Suppress response since transactions with deposits won't actually
// return FinalExecutionOutcome.
Expand Down
2 changes: 1 addition & 1 deletion packages/sender/src/lib/sender.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import isMobile from "is-mobile";
import { isMobile } from "is-mobile";
import {
WalletModuleFactory,
WalletBehaviourFactory,
Expand Down
3 changes: 3 additions & 0 deletions packages/wallet-utils/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": [["@nrwl/web/babel", { "useBuiltIns": "usage" }]]
}
18 changes: 18 additions & 0 deletions packages/wallet-utils/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"extends": ["../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
}
]
}
10 changes: 10 additions & 0 deletions packages/wallet-utils/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# @near-wallet-selector/wallet-utils

This is the Wallet Utils package for NEAR Wallet Selector.

## Installation and Usage


## License

This repository is distributed under the terms of both the MIT license and the Apache License (Version 2.0).
14 changes: 14 additions & 0 deletions packages/wallet-utils/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module.exports = {
displayName: "wallet-utils",
preset: "../../jest.preset.js",
globals: {
"ts-jest": {
tsconfig: "<rootDir>/tsconfig.spec.json",
},
},
transform: {
"^.+\\.[tj]sx?$": "ts-jest",
},
moduleFileExtensions: ["ts", "tsx", "js", "jsx"],
coverageDirectory: "../../coverage/packages/wallet-utils",
};
Loading