Skip to content

Commit

Permalink
Merge pull request #25 from gnosis/development
Browse files Browse the repository at this point in the history
v0.2.0
  • Loading branch information
mmv08 authored Jul 15, 2020
2 parents 01b792b + 9baf7e0 commit f2475f8
Show file tree
Hide file tree
Showing 7 changed files with 1,442 additions and 963 deletions.
13 changes: 13 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module.exports = {
parser: '@typescript-eslint/parser',
extends: ['plugin:@typescript-eslint/recommended', 'prettier/@typescript-eslint', 'plugin:prettier/recommended'],
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
},
rules: {
'@typescript-eslint/camelcase': 'off',
'@typescript-eslint/no-var-requires': 'off',
'@typescript-eslint/no-unused-vars': ['error', { ignoreRestSiblings: true }],
},
};
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ before_install:
cache:
yarn: true
script: |
echo "Skip tests" # no test cases for the project
yarn test
if [ -n "$TRAVIS_TAG" ]
then
Expand Down
26 changes: 15 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@gnosis.pm/safe-apps-sdk",
"version": "0.1.1",
"version": "0.2.0",
"description": "SDK developed to integrate third-party apps with Safe-Multisig app.",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
Expand All @@ -23,17 +23,22 @@
"author": "Gnosis (https://gnosis.pm)",
"license": "MIT",
"devDependencies": {
"@types/jest": "^25.2.1",
"@types/node": "^13.11.1",
"@types/jest": "^26.0.4",
"@types/node": "^14.0.22",
"@typescript-eslint/eslint-plugin": "^3.6.0",
"@typescript-eslint/parser": "^3.6.0",
"eslint": "^7.4.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-prettier": "^3.1.4",
"husky": "^4.2.5",
"jest": "^25.3.0",
"lint-staged": "^10.1.4",
"prettier": "^2.0.4",
"jest": "^26.1.0",
"lint-staged": "^10.2.11",
"prettier": "^2.0.5",
"rimraf": "^3.0.2",
"ts-jest": "^25.4.0",
"tslint": "^6.1.1",
"ts-jest": "^26.1.2",
"tslint": "^6.1.2",
"tslint-config-prettier": "^1.18.0",
"typescript": "^3.8.3"
"typescript": "^3.9.6"
},
"husky": {
"hooks": {
Expand All @@ -43,8 +48,7 @@
"lint-staged": {
"src/**/!(*test).ts": [
"yarn lint",
"prettier --write",
"git add"
"prettier --write"
]
},
"repository": {
Expand Down
10 changes: 5 additions & 5 deletions src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import initSdk, { SdkInstance, ToSafeMessages } from './index';
import initSdk, { SdkInstance, TO_SAFE_MESSAGES } from './index';

describe('safe app sdk', () => {
let sdkInstance: SdkInstance;
Expand All @@ -16,17 +16,17 @@ describe('safe app sdk', () => {
});

describe('sendTransaction', () => {
test('Should do nothing when passing empty array', () => {
test('Should do nothing when passing an empty array', () => {
const spy = jest.spyOn(window.parent, 'postMessage');
sdkInstance.sendTransactions([]);
expect(spy).not.toHaveBeenCalled();
});

test('Should call windows..parent.postMessage when passing array of TXs', () => {
test('Should call window.parent.postMessage when passing array of TXs', () => {
const spy = jest.spyOn(window.parent, 'postMessage');
const txs = [{}];
const txs = [{ to: 'address', value: '0' }];
sdkInstance.sendTransactions(txs);
expect(spy).toHaveBeenCalledWith({ messageId: ToSafeMessages.SEND_TRANSACTIONS, data: txs }, '*');
expect(spy).toHaveBeenCalledWith({ messageId: TO_SAFE_MESSAGES.SEND_TRANSACTIONS, data: txs }, '*');
});
});
});
62 changes: 44 additions & 18 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
export type Networks = 'rinkeby' | 'mainnet';

type ValueOf<T> = T[keyof T];

export interface Transaction {
to: string;
value: string;
data: string;
}
export interface SdkInstance {
addListeners: (listeners: SafeListeners) => void;
removeListeners: () => void;
sendTransactions: (txs: any[]) => void;
sendTransactions: (txs: Transaction[]) => void;
}

export interface SafeInfo {
Expand All @@ -13,27 +20,46 @@ export interface SafeInfo {
}

export interface SafeListeners {
onSafeInfo: (info: SafeInfo) => any;
onSafeInfo: (info: SafeInfo) => void;
}

export enum FromSafeMessages {
ON_SAFE_INFO = 'ON_SAFE_INFO',
interface CustomMessageEvent extends MessageEvent {
data: {
messageId: keyof FromSafeMessages;
data: FromMessageToPayload[keyof FromSafeMessages];
};
}

export const TO_SAFE_MESSAGES = {
SEND_TRANSACTIONS: 'SEND_TRANSACTIONS' as const,
};

export interface ToMessageToPayload {
[TO_SAFE_MESSAGES.SEND_TRANSACTIONS]: Transaction[];
}

export enum ToSafeMessages {
SEND_TRANSACTIONS = 'SEND_TRANSACTIONS',
export type ToSafeMessages = typeof TO_SAFE_MESSAGES;

const FROM_SAFE_MESSAGES = {
ON_SAFE_INFO: 'ON_SAFE_INFO' as const,
};

export interface FromMessageToPayload {
[FROM_SAFE_MESSAGES.ON_SAFE_INFO]: SafeInfo;
}

export type FromSafeMessages = typeof FROM_SAFE_MESSAGES;

const config: {
safeAppUrlsRegExp?: RegExp[];
listeners?: SafeListeners;
} = {};

const _logMessageFromSafe = (origin: string, message: FromSafeMessages) => {
console.info(`SafeConnector: A message with id ${message} was received from origin ${origin}.`);
const _logMessageFromSafe = (origin: string, messageId: ValueOf<FromSafeMessages>): void => {
console.info(`SafeConnector: A message with id ${messageId} was received from origin ${origin}.`);
};

const _onParentMessage = async ({ origin, data }: MessageEvent) => {
const _onParentMessage = async ({ origin, data }: CustomMessageEvent): Promise<void> => {
if (origin === window.origin) {
return;
}
Expand All @@ -54,13 +80,13 @@ const _onParentMessage = async ({ origin, data }: MessageEvent) => {
}

switch (data.messageId) {
case FromSafeMessages.ON_SAFE_INFO: {
_logMessageFromSafe(origin, FromSafeMessages.ON_SAFE_INFO);
case FROM_SAFE_MESSAGES.ON_SAFE_INFO: {
_logMessageFromSafe(origin, FROM_SAFE_MESSAGES.ON_SAFE_INFO);
console.log(data.data);

config.listeners.onSafeInfo({
safeAddress: data.data.safeAddress,
network: data.data.network.toLowerCase(),
network: data.data.network.toLowerCase() as Networks,
ethBalance: data.data.ethBalance,
});

Expand All @@ -76,7 +102,7 @@ const _onParentMessage = async ({ origin, data }: MessageEvent) => {
}
};

const _sendMessageToParent = (messageId: string, data: any) => {
const _sendMessageToParent = <T extends keyof ToSafeMessages>(messageId: T, data: ToMessageToPayload[T]): void => {
window.parent.postMessage({ messageId, data }, '*');
};

Expand All @@ -85,34 +111,34 @@ const _sendMessageToParent = (messageId: string, data: any) => {
* depending on the messageId, the corresponding listener will be called
* @param listeners
*/
function addListeners({ ...allListeners }: SafeListeners) {
function addListeners({ ...allListeners }: SafeListeners): void {
config.listeners = { ...allListeners };
window.addEventListener('message', _onParentMessage);
}

/**
* Unregister all the listeners previously set by addListeners.
*/
function removeListeners() {
function removeListeners(): void {
window.removeEventListener('message', _onParentMessage);
}

/**
* Request Safe app to send transactions
* @param txs
*/
function sendTransactions(txs: any[]) {
function sendTransactions(txs: Transaction[]): void {
if (!txs || !txs.length) {
return;
}
_sendMessageToParent(ToSafeMessages.SEND_TRANSACTIONS, txs);
_sendMessageToParent(TO_SAFE_MESSAGES.SEND_TRANSACTIONS, txs);
}

/**
* Sets Safe-app url that will render the third-party app.
* @param parentUrl
*/
function initSdk(safeAppUrlsRegExp: RegExp[] = []) {
function initSdk(safeAppUrlsRegExp: RegExp[] = []): SdkInstance {
config.safeAppUrlsRegExp = [
/https:\/\/.*(gnosis-safe\.io|gnosisdev.com)/, // Safe Multisig
/https?:\/\/localhost:\d+/, // Safe Multisig desktop app.
Expand Down
82 changes: 17 additions & 65 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,69 +1,21 @@
{
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"lib": [
"dom",
"ES2015"
], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
"strictNullChecks": true, /* Enable strict null checks. */
"strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
"noUnusedParameters": true, /* Report errors on unused parameters. */
"noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
"noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
//"allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
//"allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
"experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
"lib": ["dom", "ES2015"],
"allowJs": false /* Allow javascript files to be compiled. */,
"declaration": true /* Generates corresponding '.d.ts' file. */,
"sourceMap": true /* Generates corresponding '.map' file. */,
"outDir": "./dist" /* Redirect output structure to the directory. */,
"strict": true /* Enable all strict type-checking options. */,
"noUnusedParameters": true /* Report errors on unused parameters. */,
"noImplicitReturns": true /* Report error when not all code paths in function return a value. */,
"noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */,
"moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
"experimentalDecorators": true /* Enables experimental support for ES7 decorators. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"include": [
"src"
],
"exclude": [
"**/*.test.ts",
]
}
"include": ["src"],
"exclude": ["**/*.test.ts"]
}
Loading

0 comments on commit f2475f8

Please sign in to comment.