Skip to content

Commit

Permalink
add wsc wagmi connector
Browse files Browse the repository at this point in the history
  • Loading branch information
paulclindo committed Jun 2, 2023
0 parents commit a8f1426
Show file tree
Hide file tree
Showing 7 changed files with 308 additions and 0 deletions.
43 changes: 43 additions & 0 deletions .gitignore
@@ -0,0 +1,43 @@
lib-cov
*.seed
*.log
*.csv
*.dat
*.out
*.pid
*.gz
*.swp

pids
logs
results
tmp

# Build
public/css/main.css
build

# Coverage reports
coverage

# API keys and secrets
.env

# Dependency directory
node_modules
bower_components

# Editors
.idea
*.iml

# OS metadata
.DS_Store
Thumbs.db

# Ignore built ts files
dist/**/*

# ignore yarn.lock
yarn.lock
package-lock.json
33 changes: 33 additions & 0 deletions README.md
@@ -0,0 +1,33 @@
# Cardano WSC Wagmi Connector

[WAGMI](https://wagmi.sh/) Connector to connect with Wrapped Smart Contract.

# ⬇️ Install

```bash
npm install @dcspark/cardano-wsc-wagmi
```

or

```bash
yarn add @dcspark/cardano-wsc-wagmi
```

# ⭐ Usage

```javascript
import { CardanoWSCConnector } from "@dcspark/cardano-wsc-wagmi";

const flintWSCConnector = new CardanoWSCConnector({
name: '';
network: MilkomedaNetworkName.C1Devnet; // by default Milkomeda C1 Devnet
oracleUrl: '';
blockfrostKey: '';
jsonRpcProviderUrl: '';
});
```

## **Example repositories:**

- https://github.com/DjedAlliance/Djed-Solidity-WebDashboard
44 changes: 44 additions & 0 deletions package.json
@@ -0,0 +1,44 @@
{
"name": "@dcspark/cardano-wsc-wagmi",
"version": "1.0.2",
"description": "Wagmi Connector to connect with Wrapped Smart Contract.",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"repository": "https://github.com/dcSpark/cardano-wsc-wagmi",
"license": "MIT",
"keywords": [
"wagmi",
"extension",
"cardano-wsc"
],
"scripts": {
"build": "tsc -p tsconfig.json && tsc-esm-fix --target='dist' --ext='.js'",
"format": "rome format . --write",
"lint": "rome check .",
"lint:fix": "yarn lint --apply",
"watch:build": "tsc -p tsconfig.json -w",
"release": "yarn build"
},
"engines": {
"node": ">=10"
},
"dependencies": {
"milkomeda-wsc": "^0.1.8",
"tsc-esm-fix": "^2.20.10",
"wagmi": "^0.12.8"
},
"devDependencies": {
"rome": "12.0.0",
"typescript": "^4.7.4"
},
"files": [
"dist",
"!**/*.test.*",
"!**/*.json",
"README.md"
],
"publishConfig": {
"access": "public"
}
}
43 changes: 43 additions & 0 deletions rome.json
@@ -0,0 +1,43 @@
{
"$schema": "./node_modules/rome/configuration_schema.json",
"organizeImports": {
"enabled": false
},
"files": {
"ignore": ["**/node_modules", "dist", "yarn.lock"]
},
"formatter": {
"enabled": true,
"formatWithErrors": false,
"indentStyle": "space",
"indentSize": 2,
"lineWidth": 80
},
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"correctness": {
"noUnusedVariables": "error"
},
"performance": {
"noDelete": "off"
},
"style": {
"noNonNullAssertion": "off",
"useShorthandArrayType": "error"
},
"suspicious": {
"noArrayIndexKey": "off",
"noExplicitAny": "off"
}
}
},
"javascript": {
"formatter": {
"quoteStyle": "single",
"trailingComma": "all",
"semicolons": "asNeeded"
}
}
}
1 change: 1 addition & 0 deletions src/index.ts
@@ -0,0 +1 @@
export * from "./lib/connectors/cardanoWSCConnector";
125 changes: 125 additions & 0 deletions src/lib/connectors/cardanoWSCConnector.ts
@@ -0,0 +1,125 @@
import type { Chain } from "@wagmi/chains";
import { WSCLib, MilkomedaNetworkName } from "milkomeda-wsc";
import { Connector, ConnectorNotFoundError } from "wagmi";
import { normalizeChainId } from "@wagmi/core";
import { getAddress } from "ethers/lib/utils.js";

type CardanoWSCConnectorOptions = {
name: string;
network?: MilkomedaNetworkName;
oracleUrl?: string;
blockfrostKey: string;
jsonRpcProviderUrl?: string;
};
/**
* Connector for [Cardano WSC]
*/
export abstract class CardanoWSCConnector extends Connector<WSCLib, CardanoWSCConnectorOptions> {
id;
#provider?: any;
#sdk;
#previousProvider;

constructor({ chains, options: options_ }: { chains: Chain[]; options: CardanoWSCConnectorOptions }) {
const options = {
id: options_.name + "-wsc",
...options_,
};
super({ chains, options });
this.id = options.id;
this.#previousProvider = window?.ethereum;

const network = options_.network ?? MilkomedaNetworkName.C1Devnet;
this.#sdk = new WSCLib(network, options_.name, {
oracleUrl: options_.oracleUrl,
blockfrostKey: options_.blockfrostKey,
jsonRpcProviderUrl: options_.jsonRpcProviderUrl,
});
}

async connect(): Promise<any> {
const provider = await this.getProvider();
if (!provider) throw new ConnectorNotFoundError();

if (provider.on) {
provider.on("accountsChanged", this.onAccountsChanged);
provider.on("chainChanged", this.onChainChanged);
provider.on("disconnect", this.onDisconnect);
}

this.emit("message", { type: "connecting" });

const account = await this.getAccount();
const id = await this.getChainId();

return {
account,
chain: { id, unsupported: this.isChainUnsupported(id) },
};
}

async disconnect() {
const provider = await this.getProvider();
// switch back to previous provider
window.ethereum = this.#previousProvider;

if (!provider?.removeListener) return;
provider.removeListener("accountsChanged", this.onAccountsChanged);
provider.removeListener("chainChanged", this.onChainChanged);
provider.removeListener("disconnect", this.onDisconnect);
}

async getAccount() {
const provider = await this.getProvider();
if (!provider) throw new ConnectorNotFoundError();
const account = await this.#provider?.eth_getAccount();
return account as any;
}

async getChainId() {
const provider = await this.getProvider();
if (!provider) throw new ConnectorNotFoundError();
return normalizeChainId(200101);
}

async getProvider() {
if (!this.#provider) {
const wsc = await this.#sdk.inject();
if (!wsc) throw new Error("Could not load WSC information");
this.#provider = wsc;
}
return this.#provider;
}

async getSigner() {
const provider = await this.getProvider();
return (await provider.getEthersProvider()).getSigner();
}

async isAuthorized() {
try {
const account = await this.getAccount();
return !!account;
} catch {
return false;
}
}

onAccountsChanged = (accounts: string[]) => {
if (accounts.length === 0) this.emit("disconnect");
else
this.emit("change", {
account: getAddress(accounts[0]),
});
};

onChainChanged = (chainId: number | string) => {
const id = normalizeChainId(chainId);
const unsupported = this.isChainUnsupported(id);
this.emit("change", { chain: { id, unsupported } });
};

onDisconnect() {
this.emit("disconnect");
}
}
19 changes: 19 additions & 0 deletions tsconfig.json
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"declaration": true,
"declarationDir": "dist",
"esModuleInterop": true,
"importsNotUsedAsValues": "error",
"isolatedModules": true,
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "node",
"outDir": "dist",
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"types": ["node"],
"typeRoots": ["node_modules/@types"]
},
"exclude": ["node_modules", "dist", "src/__test__/**", "**/*.md"]
}

0 comments on commit a8f1426

Please sign in to comment.