Skip to content

Commit

Permalink
Merge pull request #6 from leapwallet/fix/sign-amino
Browse files Browse the repository at this point in the history
Fixes sign amino
  • Loading branch information
leapsamvel authored Aug 18, 2023
2 parents 8b9aaa8 + 7102412 commit 990cbda
Show file tree
Hide file tree
Showing 22 changed files with 5,537 additions and 5,220 deletions.
74 changes: 42 additions & 32 deletions packages/cosmos-snap-provider/README.md
Original file line number Diff line number Diff line change
@@ -1,59 +1,69 @@
# cosmos-snap-provider
## **cosmos-snap-provider**

Cosmos Snap provider has been created for directly using the [Leap Cosmos Snap](https://www.npmjs.com/package/@leapwallet/metamask-cosmos-snap) with cosmos js client.
The **`cosmos-snap-provider`** is specifically designed for seamless integration of the Leap Cosmos Snap with the [CosmJS](https://github.com/cosmos/cosmjs) client.

## Methods
### **Methods**

### getSnap
This method helps to identify whether leap cosmos snap is installed or not in the metamask instance installed in user browser
### 1. **getSnap**

This method is used to detect if the Leap Cosmos Snap is installed within the user's browser instance of Metamask.

```typescript
import { getSnap, connectSnap, getKey } from '@leapwallet/cosmos-snap-provider'
const snapInstalled = await getSnap() // return true if already installed
**Usage:**

```js

import { getSnap } from '@leapwallet/cosmos-snap-provider';

const snapInstalled = await getSnap(); // Returns true if the snap is already installed
```

### 2. **connectSnap**

**`connectSnap`** facilitates the connection to the Leap Cosmos Snap. If the Snap isn't installed, this function triggers its installation and establishes a connection.

**Usage:**

```js

### connectSnap
Connect snap lets you connect to leap cosmos snap if installed else it will trigger the installation and connects to the snap.

```typescript
import { getSnap, connectSnap, getKey } from '@leapwallet/cosmos-snap-provider'
import { getSnap, connectSnap } from '@leapwallet/cosmos-snap-provider';

// check if snap is installed
const snapInstalled = await getSnap()
if(!snapInstalled) {
// Install snap if not already installed
connectSnap()
const snapInstalled = await getSnap();
if (!snapInstalled) {
connectSnap(); // Initiates installation if not already present
}

```

### getKey
GetKey helps in getting the chain address for the particular chainId. This should be called once the snap is been connected with the dapp.
### 3. **getKey**

**`getKey`** fetches the chain address corresponding to a specific chainId. Ensure the Snap is connected with the dapp before invoking this function.

```typescript
const key = await getKey(chainId)
```js
const key = await getKey(chainId);
```

### cosmjsOfflineSigner
### 4. **cosmjsOfflineSigner**

If you're already employing cosmjs libraries for transaction signing, **`cosmjsOfflineSigner`** is recommended. It functions as an offline signer with existing cosmwasm clients. Before utilizing it as an offline signer, verify that the dapp is connected to the Snap.

The best way to use the provider if you already using the cosmjs libraries for signing is by using it as an offline signer with existing cosmwasm clients.
Make sure the dapp connected to snap before using it as an offline signer.
**Usage:**

```typescript
import { SigningStargateClient } from '@cosmjs/cosmwasm-stargate'
import { GasPrice } from '@cosmjs/stargate'
import { cosmjsOfflineSigner } from '@leapwallet/cosmos-snap-provider'
```js

import { SigningStargateClient } from '@cosmjs/cosmwasm-stargate';
import { GasPrice } from '@cosmjs/stargate';
import { cosmjsOfflineSigner } from '@leapwallet/cosmos-snap-provider';

const offlineSigner = new cosmjsOfflineSigner(chainId);
const accounts = await offlineSigner.getAccounts();
const rpcUrl = "" // Replace with an RPC URL for the given chainId
const rpcUrl = ""; // Populate with an RPC URL corresponding to the given chainId

const stargateClient = await SigningStargateClient.connectWithSigner(
rpcUrl,
offlineSigner,
{
gasPrice: GasPrice.fromString("0.0025ujuno"),
}
)
```
);

```
7 changes: 7 additions & 0 deletions packages/cosmos-snap-provider/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,12 @@
"build": "npx tsc",
"start": "npx tsc watch",
"prepublish": "yarn build"
},
"dependencies": {
"@cosmjs/amino": "^0.31.0",
"@cosmjs/proto-signing": "^0.31.0"
},
"devDependencies": {
"cosmjs-types": "^0.8.0"
}
}
1 change: 1 addition & 0 deletions packages/cosmos-snap-provider/src/app-env.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export {};

declare global {
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
interface Window {
ethereum: any;
}
Expand Down
8 changes: 6 additions & 2 deletions packages/cosmos-snap-provider/src/cosmjs-offline-signer.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { SignDoc } from 'cosmjs-types/cosmos/tx/v1beta1/tx';
import { AccountData, AminoSignResponse } from '@cosmjs/amino';
import { getKey, requestSignature } from './snap';
import { DirectSignResponse, OfflineDirectSigner } from '@cosmjs/proto-signing';
import { getKey, requestSignature } from './snap';

export class cosmjsOfflineSigner implements OfflineDirectSigner {
constructor(private chainId: string) {}
Expand Down Expand Up @@ -37,7 +37,7 @@ export class cosmjsOfflineSigner implements OfflineDirectSigner {
) as Promise<DirectSignResponse>;
}

//This has been added as a placeholder.
// This has been added as a placeholder.
async signAmino(
signerAddress: string,
signDoc: SignDoc,
Expand All @@ -49,6 +49,10 @@ export class cosmjsOfflineSigner implements OfflineDirectSigner {
}
}

/**
*
* @param chainId
*/
export function getOfflineSigner(chainId: string) {
return new cosmjsOfflineSigner(chainId);
}
18 changes: 10 additions & 8 deletions packages/cosmos-snap-provider/src/snap.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { AccountData } from '@cosmjs/amino';
import Long from 'long';
import { defaultSnapOrigin } from './config';
import { GetSnapsResponse, Snap } from './types';
import Long from 'long';

/**
* Get the installed snaps in MetaMask.
Expand Down Expand Up @@ -78,28 +78,28 @@ export const requestSignature = async (
},
});

const accountNumber = signDoc.accountNumber;
//@ts-ignore
const { accountNumber } = signDoc;
// @ts-ignore
const modifiedAccountNumber = new Long(
accountNumber!.low,
accountNumber!.high,
accountNumber!.unsigned,
);

const modifiedSignature = {
//@ts-ignore
// @ts-ignore
signature: signature.signature,
signed: {
// @ts-ignore
...signature.signed,
accountNumber: `${modifiedAccountNumber.toString()}`,
authInfoBytes: new Uint8Array(
//@ts-ignore
// @ts-ignore
Object.values(signature.signed.authInfoBytes),
),

bodyBytes: new Uint8Array(
//@ts-ignore
// @ts-ignore
Object.values(signature.signed.bodyBytes),
),
},
Expand All @@ -123,8 +123,10 @@ export const getKey = async (chainId: string): Promise<AccountData> => {
},
});

if (!accountData) throw new Error('No account data found');
//@ts-ignore
if (!accountData) {
throw new Error('No account data found');
}
// @ts-ignore
accountData.pubkey = Uint8Array.from(Object.values(accountData.pubkey));

return accountData as AccountData;
Expand Down
81 changes: 43 additions & 38 deletions packages/snap/README.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
# LeapWallet - Metamask Cosmos Snap
### **`@leapwallet/metamask-cosmos-snap`**

```
@leapwallet/metamask-cosmos-snap
```

This Snap helps you to sign cosmos transactions for the chains of coin type 118

> Note:
If you are already using Cosmos-js and are familiar with OfflineSigner, we recommend using our [cosmos-snap-provider](https://github.com/leapwallet/cosmos-metamask-snap/blob/main/packages/cosmos-snap-provider/README.md) which does all necessary with lesser code changes.
This Snap facilitates signing of Cosmos transactions for chains associated with coin type 118.

> Recommendation: If you're accustomed to using [CosmJS](https://github.com/cosmos/cosmjs) and the OfflineSigner, consider leveraging our cosmos-snap-provider. It streamlines the necessary tasks with minimal code alterations.
>
## Installation
### **Installation**

To connect or to install and connect to leapwallet's metamask-cosmos-snap. Use the below command
To either establish a connection or initiate an installation followed by a connection to the **`leapwallet's metamask-cosmos-snap`**, execute the following code:

```javascript

try {
const result = await window.ethereum.request({
method: 'wallet_requestSnaps',
Expand All @@ -28,46 +24,55 @@ try {
} catch (error) {
console.log(error);
}

```

for more information about installing/connecting to a metamask snap check [here](https://docs.metamask.io/snaps/reference/rpc-api/#wallet_requestsnaps)
For comprehensive details on connecting or installing a Metamask snap, refer **[here](https://docs.metamask.io/snaps/reference/rpc-api/#wallet_requestsnaps)**.

### **Methods**

### 1. **Get Keys**

## Get Keys
The **`getKey`** method retrieves the wallet's public address corresponding to a specific chain ID. Currently, we support chains of coin type 118.

The get Key method gets the wallet's public address for a particular chain id. We are now supporting chains of coin type 118.
**Usage:**

```javascript
const accountData = await window.ethereum.request({
method: 'wallet_invokeSnap',
params: {
snapId: "npm:@leapwallet-metamask-snap",
request: {
method: 'getKey',
params: {
chainId,
},
const accountData = await window.ethereum.request({
method: 'wallet_invokeSnap',
params: {
snapId: "npm:@leapwallet-metamask-snap",
request: {
method: 'getKey',
params: {
chainId,
},
},
});
},
});

```

## Sign Direct
### 2. **Sign Direct**

Utilize the **`signDirect`** method to sign transactions or **`signDoc`** using the connected wallet.

Sign direct would be used to sign any transactions / signDoc using the wallet which got connected.
**Usage:**

```javascript
await window.ethereum.request({
method: 'wallet_invokeSnap',
params: {
snapId: "npm:@leapwallet-metamask-snap",
request: {
method: 'signDirect',
params: {
chainId,
signerAddress,
signDoc,
},
method: 'wallet_invokeSnap',
params: {
snapId: "npm:@leapwallet-metamask-snap",
request: {
method: 'signDirect',
params: {
chainId,
signerAddress,
signDoc,
},
},
});
```
},
});

```
20 changes: 9 additions & 11 deletions packages/snap/jest.config.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
module.exports = {
"roots": [
"<rootDir>/src"
],
"testMatch": [
"**/tests/**/*.+(ts|tsx|js)",
"**/?(*.)+(spec|test).+(ts|tsx|js)"
],
"transform": {
"^.+\\.(ts|tsx)$": "ts-jest"
},
}
roots: ['<rootDir>/src'],
testMatch: [
'**/tests/**/*.+(ts|tsx|js)',
'**/?(*.)+(spec|test).+(ts|tsx|js)',
],
transform: {
'^.+\\.(ts|tsx)$': 'ts-jest',
},
};
1 change: 1 addition & 0 deletions packages/snap/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"test-coverage": "jest --coverage"
},
"dependencies": {
"@cosmjs/amino": "^0.31.0",
"@cosmjs/stargate": "^0.30.1",
"@leapwallet/buffer-boba": "^0.1.4",
"@leapwallet/parser-parfait": "^0.6.2",
Expand Down
2 changes: 1 addition & 1 deletion packages/snap/snap.manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/leapwallet/cosmos-metamask-snap.git"
},
"source": {
"shasum": "p3wrc8CLf1od4lZg6DMCgHO54EAJgbfF618aRSuldPg=",
"shasum": "Yw58GUzZwP1Ub9MNP2yj+X38T/81NfxMO7YJcBaVj6s=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down
Loading

0 comments on commit 990cbda

Please sign in to comment.