Skip to content

Commit

Permalink
feat: Tezos Provider
Browse files Browse the repository at this point in the history
  • Loading branch information
dianasavvatina committed Nov 14, 2024
1 parent f205f2a commit 1b40b6f
Show file tree
Hide file tree
Showing 16 changed files with 8,261 additions and 2 deletions.
44 changes: 44 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

.DS_Store

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# next.js
/.next/
/out/

# production
/build
/dist

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env
.env.local
.env.development.local
.env.test.local
.env.production.local

# vercel
.vercel

# webstorm ide
.idea

# vscode
.vscode/settings.json
4 changes: 4 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"arrowParens": "avoid",
"trailingComma": "es5"
}
3 changes: 3 additions & 0 deletions .swcrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"sourceMaps": false
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Trilitech

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
157 changes: 155 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,155 @@
# tezos-provider
Tezos Provider for dApps using WalletConnect SDK
# TezosProvider

The `TezosProvider` is a class that allows you to interact with the Tezos blockchain via the WalletConnect protocol.
This provider manages the connection to the Tezos network, facilitates transactions, and handles account management.

## Installation

```
npm i @walletconnect/tezos-provider @walletconnect/modal
```

## Initialization

To use `TezosProvider`, you first need to initialize it with the necessary options:

```typescript
import TezosProvider from 'path-to-tezos-provider';

const provider = await TezosProvider.init({
projectId: 'your-project-id', // REQUIRED WalletConnect project ID
metadata: {
name: 'Your DApp Name',
description: 'Your DApp Description',
url: 'https://your-dapp-url.com',
icons: ['https://your-dapp-url.com/icon.png'],
},
relayUrl: 'wss://relay.walletconnect.com', // OPTIONAL WalletConnect relay URL
storageOptions: {}, // OPTIONAL key-value storage settings
disableProviderPing: false, // OPTIONAL set to true to disable provider ping
logger: 'info', // OPTIONAL log level, default is 'info'
});
```

Default relay URL is defined in `RelayUrl`.

### Options (TezosProviderOpts)

- `projectId`: Your WalletConnect project ID.
- `metadata`: Metadata for your DApp, including name, description, url, and icons.
- `relayUrl`: URL of the WalletConnect relay server.
- `storageOptions`: Optional settings for key-value storage.
- `disableProviderPing`: If set to true, disables provider ping.
- `logger`: Sets the log level, default is 'info'.

## Display WalletConnectModal with QR code / Connecting to the Tezos Network

After initializing the provider, you can connect it to the Tezos network:

```typescript
await provider.connect({
chains: [
{
id: 'tezos:mainnet',
rpc: ['https://mainnet-tezos.giganode.io'],
},
],
methods: ['tezos_getAccounts', 'tezos_send', 'tezos_sign'],
events: [], // OPTIONAL Tezos events
});
```

Connection Options (TezosConnectOpts):

- `chains`: An array of chain data, each with an id and rpc endpoint(s). Default chain data is defined in `TezosChainMap`.
- `methods`: An array of methods that the provider should support. Default methods are defined in `DefaultTezosMethods`.
- `events`: An array of event names that the provider should listen for.

If you are not using a modal for QR code display, you can subscribe to the `display_uri` event to handle the connection URI yourself:

```typescript
provider.on("display_uri", (uri: string) => {
// Handle the connection URI
console.log('Connection URI:', uri);
});

await provider.connect();
```

## Sending requests

### Get Accounts

To send a request to the Tezos network:

```typescript
const accounts = await provider.request({ method: "tezos_getAccounts" });

// OR

provider.sendAsync({ method: "tezos_getAccounts" }, callbackFunction);
```

### Send Transactions

To send a transaction:

```typescript
const transactionResponse = await provider.tezosSendTransaction({
kind: 'transaction',
destination: 'tz1...',
amount: '1000000', // Amount in mutez
});

console.log('Transaction hash:', transactionResponse.hash);
```

### Sign Messages

To sign a message, encode it to hex first:

```typescript
const textEncoder = new TextEncoder();
const bytes = textEncoder.encode('Your string here');
const hexBytes = Buffer.from(bytes).toString('hex');

const signResponse = await provider.tezosSign({
payload: hexBytes,
});

console.log('Signature:', signResponse.signature);
```

## Events

Listen to various events from the TezosProvider:

```typescript
// chain changed
provider.on("chainChanged", handler);
// accounts changed
provider.on("accountsChanged", handler);
// session established
provider.on("connect", handler);
// session event - chainChanged/accountsChanged/custom events
provider.on("session_event", handler);
// connection uri
provider.on("display_uri", handler);
// session disconnect
provider.on("disconnect", handler);
```

## Error Handling
The provider will throw errors if:

- `TezosInitializationError`: If the provider is not initialized correctly.
- `TezosProviderError`: If there are issues with the connection or account retrieval.

## Supported WalletConnectModal options (qrModalOptions)

Please reference the [up-to-date WalletConnect documentation](https://docs.walletconnect.com) for any additional `qrModalOptions`.

## References

- [Tezos documentation for WalletConnect](https://docs.walletconnect.com/advanced/multichain/rpc-reference/tezos-rpc)
- [dApp examples](https://github.com/WalletConnect/web-examples/tree/main/dapps)
54 changes: 54 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@

import tsParser from "@typescript-eslint/parser"; // Import the TypeScript parser
import tsPlugin from "@typescript-eslint/eslint-plugin"; // Import the TypeScript plugin
import prettierPlugin from "eslint-plugin-prettier"; // Import the Prettier plugin
import importPlugin from 'eslint-plugin-import';

export default {
languageOptions: {
globals: {
NodeJS: true,
},
parser: tsParser,
parserOptions: {
ecmaVersion: 2020,
sourceType: "module",
},
},
files: ["**/*.ts"],
rules: {
"comma-dangle": ["error", "always-multiline"],
"require-await": "error",
"no-undef": ["error"],
"no-var": ["error"],
"object-curly-spacing": ["error", "always"],
"quotes": ["error", "double", { "allowTemplateLiterals": true }],
"semi": ["error", "always"],
"no-console": ["error", { allow: ["warn"] }],
"import/no-extraneous-dependencies": ["error"],
"import/order": [
"warn",
{
groups: [
"builtin", // Built-in imports (come from NodeJS native) go first
"external", // <- External imports
"internal", // <- Absolute imports
["sibling", "parent"], // <- Relative imports, the sibling and parent types they can be mingled together
"index", // <- index imports
"unknown", // <- unknown
],
"newlines-between": "always",
alphabetize: {
order: "asc",
caseInsensitive: true,
},
},
],
},
ignores: ["dist", "node_modules/*"],
plugins: {
"@typescript-eslint": tsPlugin,
prettier: prettierPlugin,
import: importPlugin,
},
};
4 changes: 4 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export default {
preset: 'ts-jest',
testEnvironment: 'node',
};
89 changes: 89 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
{
"name": "@trili/tezos-provider",
"description": "Tezos Provider for WalletConnect Protocol",
"version": "1.0.3",
"author": "Trilitech TriliTech <[email protected]> (https://trili.tech)",
"homepage": "https://trili.tech",
"repository": {
"type": "git",
"url": "https://github.com/trilitech/tezos-connect",
"directory": "."
},
"license": "MIT",
"type": "module",
"main": "dist/index.cjs.js",
"module": "dist/index.es.js",
"unpkg": "dist/index.umd.js",
"types": "dist/types/index.d.ts",
"sideEffects": false,
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"require": "./dist/index.cjs"
}
},
"files": [
"dist"
],
"keywords": [
"wallet",
"walletconnect"
],
"scripts": {
"clean": "rm -rf dist",
"build": "tsup-node",
"test:pre": "rm -rf ./test/test.db",
"test:run": "jest",
"test": "yarn test:pre; yarn test:run",
"prettier": "prettier --check '{src,test}/**/*.{js,ts,jsx,tsx}' --write",
"lint": "eslint -c 'eslint.config.mjs' --fix './src/**/*.ts'",
"lint:ci": "eslint 'src/**/*.ts' -f json -o lintReport.json || true"
},
"tsup": {
"dts": true,
"entry": [
"src/index.ts"
],
"clean": true,
"format": [
"cjs",
"esm"
]
},
"dependencies": {
"@airgap/beacon-types": "^4.2.2",
"@taquito/rpc": "~20.0.1",
"@taquito/taquito": "~20.0.1",
"@trili/tezos-provider": "^1.0.2",
"@walletconnect/keyvaluestorage": "^1.1.1",
"@walletconnect/logger": "^2.1.2",
"@walletconnect/types": "2.13.3",
"@walletconnect/universal-provider": "^2.17.1",
"axios": "^1.7.7",
"micromatch": "^4.0.8",
"package.json": "^2.0.1",
"rollup": "^4.24.0",
"typescript": "^5.6.3",
"yarn.lock": "^0.0.1-security"
},
"devDependencies": {
"@jest/globals": "^29.7.0",
"@types/jest": "^29.5.13",
"@types/micromatch": "^4",
"@typescript-eslint/eslint-plugin": "^8.8.1",
"@typescript-eslint/parser": "^8.8.1",
"depcheck": "^1.4.7",
"eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-import": "^2.31.0",
"eslint-plugin-prettier": "^5.2.1",
"jest": "^29.7.0",
"prettier": "^3.3.3",
"ts-jest": "^29.2.5",
"tsup": "^8.2.4"
},
"engines": {
"node": ">=18"
}
}
Loading

0 comments on commit 1b40b6f

Please sign in to comment.