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

Feat: support scdo #216

Merged
merged 4 commits into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
1 change: 1 addition & 0 deletions packages/providers/inpage-providers-hub/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"@onekeyfe/cross-inpage-provider-types": "2.0.6",
"@onekeyfe/onekey-algo-provider": "2.0.6",
"@onekeyfe/onekey-aptos-provider": "2.0.6",
"@onekeyfe/onekey-scdo-provider": "2.0.6",
"@onekeyfe/onekey-btc-provider": "2.0.6",
"@onekeyfe/onekey-cardano-provider": "2.0.6",
"@onekeyfe/onekey-conflux-provider": "2.0.6",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
} from '@onekeyfe/cross-inpage-provider-core';
import { ProviderSui, registerSuiWallet } from '@onekeyfe/onekey-sui-provider';
import { ProviderWebln } from '@onekeyfe/onekey-webln-provider';
import { ProviderScdo } from '@onekeyfe/onekey-scdo-provider';
import { ProviderNostr } from '@onekeyfe/onekey-nostr-provider';
import { ProviderBtc, ProviderBtcWallet } from '@onekeyfe/onekey-btc-provider';
import { ProviderAlgo } from '@onekeyfe/onekey-algo-provider';
Expand All @@ -43,6 +44,7 @@ export type IWindowOneKeyHub = {
nostr?: ProviderNostr;
unisat?: ProviderBtc;
btcwallet?: ProviderBtcWallet;
scdo?: ProviderScdo;
$private?: ProviderPrivate;
$walletInfo?: {
buildNumber: string;
Expand Down Expand Up @@ -122,6 +124,8 @@ function injectWeb3Provider(): unknown {

const algorand = new ProviderAlgo({ bridge });

const scdo = new ProviderScdo({ bridge });

// const $privateExternalAccount = new ProviderPrivateExternalAccount({ bridge });

// providerHub
Expand All @@ -140,6 +144,7 @@ function injectWeb3Provider(): unknown {
sui,
cardano,
cosmos,
scdo,
webln,
nostr,
btc,
Expand Down Expand Up @@ -185,6 +190,7 @@ function injectWeb3Provider(): unknown {
defineWindowProperty('tronLink', tron);
defineWindowProperty('suiWallet', sui);
defineWindowProperty('unisat', btc);
defineWindowProperty('scdo', scdo);
defineWindowProperty('algorand', algorand);
defineWindowProperty('exodus', {
algorand,
Expand Down
1 change: 1 addition & 0 deletions packages/providers/onekey-scdo-provider/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dist/
1 change: 1 addition & 0 deletions packages/providers/onekey-scdo-provider/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# cross-inpage-provider
36 changes: 36 additions & 0 deletions packages/providers/onekey-scdo-provider/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"name": "@onekeyfe/onekey-scdo-provider",
"version": "2.0.6",
"keywords": [
"cross-inpage-provider"
],
"author": "[email protected]",
"repository": "https://github.com/OneKeyHQ/cross-inpage-provider",
"license": "Apache-2.0",
"publishConfig": {
"access": "public"
},
"type": "module",
"files": [
"dist/*"
],
"exports": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"require": "./dist/cjs/index.js"
},
"types": "./dist/index.d.ts",
"module": "./dist/index.js",
"main": "./dist/cjs/index.js",
"scripts": {
"prebuild": "rm -rf dist",
"build": "tsc && tsc --project tsconfig.cjs.json",
"start": "tsc --watch"
},
"dependencies": {
"@onekeyfe/cross-inpage-provider-core": "2.0.6",
"@onekeyfe/cross-inpage-provider-errors": "2.0.6",
"@onekeyfe/cross-inpage-provider-types": "2.0.6",
"@onekeyfe/extension-bridge-injected": "2.0.6"
}
}
224 changes: 224 additions & 0 deletions packages/providers/onekey-scdo-provider/src/OnekeyScdoProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
import type { IInpageProviderConfig } from '@onekeyfe/cross-inpage-provider-core';
import { getOrCreateExtInjectedJsBridge } from '@onekeyfe/extension-bridge-injected';
import { ProviderScdoBase } from './ProviderScdoBase';
import type { IJsonRpcRequest } from '@onekeyfe/cross-inpage-provider-types';
import type * as TypeUtils from './type-utils';

export enum PROVIDER_EVENTS {
accountsChanged = 'accountsChanged',
disconnect = 'disconnect',
message_low_level = 'message_low_level',
}

type ScdoProviderEventsMap = {
[PROVIDER_EVENTS.accountsChanged]: (accounts: string[]) => void;
[PROVIDER_EVENTS.disconnect]: () => void;
[PROVIDER_EVENTS.message_low_level]: (payload: IJsonRpcRequest) => void;
};

export enum ScdoRequestMethods {
scdo_requestAccounts = 'scdo_requestAccounts',
scdo_disconnect = 'scdo_disconnect',
scdo_getAccounts = 'scdo_getAccounts',
scdo_getBalance = 'scdo_getBalance',
scdo_signTransaction = 'scdo_signTransaction',
scdo_estimateGas = 'scdo_estimateGas',
scdo_sendTransaction = 'scdo_sendTransaction',
}

export interface Tx {
from: string;
to: string;
amount?: number;
accountNonce?: number;
gasPrice?: number;
gasLimit?: number;
timestamp?: number;
payload?: string;
hash?: string;
signature?: {
Sig: string;
}
}

export interface RawTransaction {
Type: number;
From: string;
To: string;
Amount: number;
AccountNonce: number;
GasPrice: number;
GasLimit: number;
Timestamp: number;
Payload: string;
}

export interface SignedTx {
Data: RawTransaction;
Hash: string;
Signature: {
Sig: string;
};
}

type ScdoRequest = {
[ScdoRequestMethods.scdo_requestAccounts]: () => string[];
[ScdoRequestMethods.scdo_disconnect]: () => void;
[ScdoRequestMethods.scdo_getAccounts]: () => string[];
[ScdoRequestMethods.scdo_getBalance]: (address: string, blockHash?: string, blockHeight?: number) => string;
[ScdoRequestMethods.scdo_signTransaction]: (tx: Tx) => SignedTx;
[ScdoRequestMethods.scdo_estimateGas]: (tx: Tx) => string;
[ScdoRequestMethods.scdo_sendTransaction]: (tx: Tx) => SignedTx;
}

type ScdoRequestParams = Parameters<ScdoRequest[ScdoRequestMethods]>;
type ScdoRequestResponse = ReturnType<ScdoRequest[ScdoRequestMethods]>;

interface ScdoRequestProps {
method: ScdoRequestMethods;
params: ScdoRequestParams;
}

export type IProviderScdo = {
on: <E extends keyof ScdoProviderEventsMap>(event: E, cb: ScdoProviderEventsMap[E]) => void;
removeListener: <E extends keyof ScdoProviderEventsMap>(event: E, cb: ScdoProviderEventsMap[E]) => void;
request: (props: ScdoRequestProps) => Promise<ScdoRequestResponse>;
};

type JsBridgeRequest = {
[K in keyof ScdoRequest]: (
...params: [void|string|RawTransaction|undefined|SignedTx]
) => Promise<TypeUtils.WireStringified<TypeUtils.ResolvePromise<ReturnType<ScdoRequest[K]>>>>;
};

type JsBridgeRequestResponse<T extends keyof JsBridgeRequest> = ReturnType<JsBridgeRequest[T]>;

export type OneKeyScdoProviderProps = IInpageProviderConfig & {
timeout?: number;
};

function isWalletEventMethodMatch({ method, name }: { method: string; name: string }) {
return method === `wallet_events_${name}`;
}

export class ProviderScdo extends ProviderScdoBase implements IProviderScdo {
private _account?: string;
public accounts: string[] = [];

constructor(props: OneKeyScdoProviderProps) {
super({
...props,
bridge: props.bridge || getOrCreateExtInjectedJsBridge({ timeout: props.timeout }),
});

this._registerEvents();
}

private _registerEvents() {
window.addEventListener('onekey_bridge_disconnect', () => {
this._handleDisconnected();
});

this.on(PROVIDER_EVENTS.message_low_level, (payload) => {
if (!payload) return;
const { method, params } = payload;

if (isWalletEventMethodMatch({ method, name: PROVIDER_EVENTS.accountsChanged })) {
this._handleAccountChange(params as string | undefined);
}
});
}

private _callBridge<T extends keyof JsBridgeRequest>(params: {
method: T;
params: (void|string|RawTransaction|undefined|SignedTx)[];
}): JsBridgeRequestResponse<T> {
return this.bridgeRequest(params) as JsBridgeRequestResponse<T>;
}

private _handleDisconnected(options: { emit: boolean } = { emit: true }) {
this._account = undefined;

if (options.emit && this.isConnectionStatusChanged('disconnected')) {
this.connectionStatus = 'disconnected';
this.emit(PROVIDER_EVENTS.disconnect);
}
}

isAccountsChanged(account: string | undefined) {
if (!account) return false;
if (!this._account) return true;

return account !== this._account;
}

// trigger by bridge account change event
private _handleAccountChange(payload: string | undefined) {
const account = payload;
if (this.isAccountsChanged(account) && account) {
this.emit(PROVIDER_EVENTS.accountsChanged, [account]);
}
if (!account) {
this._handleDisconnected();
return;
}
}

on<E extends keyof ScdoProviderEventsMap>(
event: E,
listener: ScdoProviderEventsMap[E],
): this {
return super.on(event, listener);
}

emit<E extends keyof ScdoProviderEventsMap>(
event: E,
...args: Parameters<ScdoProviderEventsMap[E]>
): boolean {
return super.emit(event, ...args);
}

removeListener<E extends keyof ScdoProviderEventsMap>(eventName: E, listener: ScdoProviderEventsMap[E]): this {
return super.removeListener(eventName, listener);
}

private _transformTx(tx: Tx): RawTransaction {
return {
Type: 0,
From: tx.from,
To: tx.to,
Amount: tx.amount ?? 0,
AccountNonce: tx.accountNonce ?? 0,
GasPrice: tx.gasPrice ?? 1,
GasLimit: tx.gasLimit ?? 0,
Timestamp: tx.timestamp ?? 0,
Payload: tx.payload ?? '',
};
}

async request(props: ScdoRequestProps) {
const reqParams = props.params as (void|string|undefined|Tx)[];
let params;
if (props.method === ScdoRequestMethods.scdo_estimateGas) {
const tx = reqParams[0] as Tx;
params = [{
Data: this._transformTx(tx),
Hash: tx.hash ?? '',
Signature: tx.signature ?? { Sig: '' },
}] as [SignedTx];
} else if (props.method === ScdoRequestMethods.scdo_signTransaction || props.method === ScdoRequestMethods.scdo_sendTransaction) {
params = [this._transformTx(props.params[0] as Tx)];
} else {
params = reqParams as [string];
}
const res = await this._callBridge({
method: props.method,
params,
});
if (props.method === ScdoRequestMethods.scdo_getAccounts) {
this.accounts.length = 0;
this.accounts.push(...res as string[]);
}
return res;
}
}
17 changes: 17 additions & 0 deletions packages/providers/onekey-scdo-provider/src/ProviderScdoBase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { IInjectedProviderNames } from '@onekeyfe/cross-inpage-provider-types';

import { ProviderBase, IInpageProviderConfig } from '@onekeyfe/cross-inpage-provider-core';

class ProviderScdoBase extends ProviderBase {
constructor(props: IInpageProviderConfig) {
super(props);
}

protected providerName = IInjectedProviderNames.scdo;

request(data: unknown) {
return this.bridgeRequest(data);
}
}

export { ProviderScdoBase };
1 change: 1 addition & 0 deletions packages/providers/onekey-scdo-provider/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './OnekeyScdoProvider';
7 changes: 7 additions & 0 deletions packages/providers/onekey-scdo-provider/src/type-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export type WireStringified<T> = T extends Array<infer P>
? Array<WireStringified<P>>
: T extends object
? { [K in keyof T]: WireStringified<T[K]> }
: T;

export type ResolvePromise<T> = T extends Promise<infer P> ? P : T;
7 changes: 7 additions & 0 deletions packages/providers/onekey-scdo-provider/tsconfig.cjs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "../../../tsconfig.cjs.json",
"include": ["./src"],
"compilerOptions": {
"outDir": "./dist/cjs"
}
}
7 changes: 7 additions & 0 deletions packages/providers/onekey-scdo-provider/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "../../../tsconfig.json",
"include": ["./src"],
"compilerOptions": {
"outDir": "./dist"
}
}
Loading