fix: add support for browser modules to @solana/spl-token (#1337)

* fix: add support for browser modules

* chore: format and lint

* chore: fix flow
This commit is contained in:
Justin Starry 2021-02-25 14:56:09 +08:00 committed by GitHub
parent a7f16f7b20
commit 6eac7bc331
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 2117 additions and 100 deletions

View File

@ -1 +1,2 @@
/lib
/test/dist

View File

@ -5,6 +5,7 @@ module.exports = {
browser: true,
es6: true,
node: true,
mocha: true,
},
extends: [
'eslint:recommended',

6
token/js/.mocharc.js Normal file
View File

@ -0,0 +1,6 @@
'use strict';
// Configure Node.js tests
module.exports = {
require: ['@babel/register', 'esm'],
};

View File

@ -1,17 +1,9 @@
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "10"
}
}
],
"@babel/preset-flow"
["@babel/preset-env"],
["@babel/preset-flow"]
],
"plugins": [
"@babel/plugin-transform-runtime",
"@babel/plugin-proposal-class-properties"
]
}

View File

@ -1,7 +1,6 @@
// @flow
import * as BufferLayout from 'buffer-layout';
import {Buffer} from 'buffer';
/**
* Layout for a public key
@ -16,33 +15,3 @@ export const publicKey = (property: string = 'publicKey'): Object => {
export const uint64 = (property: string = 'uint64'): Object => {
return BufferLayout.blob(8, property);
};
/**
* Layout for a Rust String type
*/
export const rustString = (property: string = 'string'): Object => {
const rsl = BufferLayout.struct(
[
BufferLayout.u32('length'),
BufferLayout.u32('lengthPadding'),
BufferLayout.blob(BufferLayout.offset(BufferLayout.u32(), -8), 'chars'),
],
property,
);
const _decode = rsl.decode.bind(rsl);
const _encode = rsl.encode.bind(rsl);
rsl.decode = (buffer, offset) => {
const data = _decode(buffer, offset);
return data.chars.toString('utf8');
};
rsl.encode = (str, buffer, offset) => {
const data = {
chars: Buffer.from(str, 'utf8'),
};
return _encode(data, buffer, offset);
};
return rsl;
};

View File

@ -27,6 +27,15 @@ export const TOKEN_PROGRAM_ID: PublicKey = new PublicKey(
'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',
);
/**
* Unfortunately, BufferLayout.encode uses an `instanceof` check for `Buffer`
* which fails when using `publicKey.toBuffer()` directly because the bundled `Buffer`
* class in `@solana/web3.js` is different from the bundled `Buffer` class in this package
*/
function pubkeyToBuffer(publicKey: PublicKey): typeof Buffer {
return Buffer.from(publicKey.toBuffer());
}
/**
* 64-bit value
*/
@ -1300,9 +1309,9 @@ export class Token {
{
instruction: 0, // InitializeMint instruction
decimals,
mintAuthority: mintAuthority.toBuffer(),
mintAuthority: pubkeyToBuffer(mintAuthority),
option: freezeAuthority === null ? 0 : 1,
freezeAuthority: (freezeAuthority || new PublicKey()).toBuffer(),
freezeAuthority: pubkeyToBuffer(freezeAuthority || new PublicKey()),
},
data,
);
@ -1544,7 +1553,7 @@ export class Token {
instruction: 6, // SetAuthority instruction
authorityType: AuthorityTypeCodes[authorityType],
option: newAuthority === null ? 0 : 1,
newAuthority: (newAuthority || new PublicKey()).toBuffer(),
newAuthority: pubkeyToBuffer(newAuthority || new PublicKey()),
},
data,
);

304
token/js/flow-typed/npm/chai_v4.x.x.js vendored Normal file
View File

@ -0,0 +1,304 @@
// flow-typed signature: 055d97c4302b7989c7221251421dca7c
// flow-typed version: 673c7738c2/chai_v4.x.x/flow_>=v0.104.x
declare module 'chai' {
declare type ExpectChain<T> = {
and: ExpectChain<T>,
at: ExpectChain<T>,
be: ExpectChain<T>,
been: ExpectChain<T>,
have: ExpectChain<T>,
has: ExpectChain<T>,
is: ExpectChain<T>,
of: ExpectChain<T>,
same: ExpectChain<T>,
that: ExpectChain<T>,
to: ExpectChain<T>,
which: ExpectChain<T>,
with: ExpectChain<T>,
not: ExpectChain<T>,
deep: ExpectChain<T>,
any: ExpectChain<T>,
all: ExpectChain<T>,
own: ExpectChain<T>,
a: ExpectChain<T> & ((type: string, message?: string) => ExpectChain<T>),
an: ExpectChain<T> & ((type: string, message?: string) => ExpectChain<T>),
include: ExpectChain<T> & ((value: mixed, message?: string) => ExpectChain<T>),
includes: ExpectChain<T> & ((value: mixed, message?: string) => ExpectChain<T>),
contain: ExpectChain<T> & ((value: mixed, message?: string) => ExpectChain<T>),
contains: ExpectChain<T> & ((value: mixed, message?: string) => ExpectChain<T>),
eq: (value: T, message?: string) => ExpectChain<T>,
eql: (value: T, message?: string) => ExpectChain<T>,
equal: (value: T, message?: string) => ExpectChain<T>,
equals: (value: T, message?: string) => ExpectChain<T>,
above: (value: T & number, message?: string) => ExpectChain<T>,
gt: (value: T & number, message?: string) => ExpectChain<T>,
greaterThan: (value: T & number, message?: string) => ExpectChain<T>,
least: (value: T & number, message?: string) => ExpectChain<T>,
below: (value: T & number, message?: string) => ExpectChain<T>,
lessThan: (value: T & number, message?: string) => ExpectChain<T>,
lt: (value: T & number, message?: string) => ExpectChain<T>,
most: (value: T & number, message?: string) => ExpectChain<T>,
within: (start: T & number, finish: T & number, message?: string) => ExpectChain<T>,
instanceof: (constructor: mixed, message?: string) => ExpectChain<T>,
instanceOf: (constructor: mixed, message?: string) => ExpectChain<T>,
nested: ExpectChain<T>,
property: <P>(
name: string,
value?: P,
message?: string
) => ExpectChain<P> & ((name: string) => ExpectChain<mixed>),
length: ExpectChain<number> & ((value: number, message?: string) => ExpectChain<T>),
lengthOf: (value: number, message?: string) => ExpectChain<T>,
match: (regex: RegExp, message?: string) => ExpectChain<T>,
matches: (regex: RegExp, message?: string) => ExpectChain<T>,
string: (string: string, message?: string) => ExpectChain<T>,
key: (key: string) => ExpectChain<T>,
keys: (
key: string | Array<string>,
...keys: Array<string>
) => ExpectChain<T>,
throw: <E>(
err?: Class<E> | Error | RegExp | string,
errMsgMatcher?: RegExp | string,
msg?: string
) => ExpectChain<T>,
respondTo: (method: string, message?: string) => ExpectChain<T>,
itself: ExpectChain<T>,
satisfy: (method: (value: T) => boolean, message?: string) => ExpectChain<T>,
closeTo: (expected: T & number, delta: number, message?: string) => ExpectChain<T>,
members: (set: mixed, message?: string) => ExpectChain<T>,
oneOf: (list: Array<T>, message?: string) => ExpectChain<T>,
change: (obj: mixed, key: string, message?: string) => ExpectChain<T>,
increase: (obj: mixed, key: string, message?: string) => ExpectChain<T>,
decrease: (obj: mixed, key: string, message?: string) => ExpectChain<T>,
by: (delta: number, message?: string) => ExpectChain<T>,
ordered: ExpectChain<T>,
// dirty-chai
ok: () => ExpectChain<T>,
true: () => ExpectChain<T>,
false: () => ExpectChain<T>,
null: () => ExpectChain<T>,
undefined: () => ExpectChain<T>,
exist: () => ExpectChain<T>,
empty: () => ExpectChain<T>,
extensible: () => ExpectChain<T>,
sealed: () => ExpectChain<T>,
frozen: () => ExpectChain<T>,
NaN: () => ExpectChain<T>,
// chai-immutable
size: (n: number) => ExpectChain<T>,
// sinon-chai
called: () => ExpectChain<T>,
callCount: (n: number) => ExpectChain<T>,
calledOnce: () => ExpectChain<T>,
calledTwice: () => ExpectChain<T>,
calledThrice: () => ExpectChain<T>,
calledBefore: (spy: mixed) => ExpectChain<T>,
calledAfter: (spy: mixed) => ExpectChain<T>,
calledImmediatelyBefore: (spy: mixed) => ExpectChain<T>,
calledImmediatelyAfter: (spy: mixed) => ExpectChain<T>,
calledWith: (...args: Array<mixed>) => ExpectChain<T>,
calledOnceWith: (...args: Array<mixed>) => ExpectChain<T>,
calledWithMatch: (...args: Array<mixed>) => ExpectChain<T>,
calledWithExactly: (...args: Array<mixed>) => ExpectChain<T>,
calledOnceWithExactly: (...args: Array<mixed>) => ExpectChain<T>,
returned: (returnVal: mixed) => ExpectChain<T>,
alwaysReturned: (returnVal: mixed) => ExpectChain<T>,
// chai-as-promised
eventually: ExpectChain<T>,
resolvedWith: (value: mixed) => Promise<mixed> & ExpectChain<T>,
resolved: () => Promise<mixed> & ExpectChain<T>,
rejectedWith: (
value: mixed,
errMsgMatcher?: RegExp | string,
msg?: string
) => Promise<mixed> & ExpectChain<T>,
rejected: () => Promise<mixed> & ExpectChain<T>,
notify: (callback: () => mixed) => ExpectChain<T>,
fulfilled: () => Promise<mixed> & ExpectChain<T>,
// chai-subset
containSubset: (obj: {...} | Array< {...} >) => ExpectChain<T>,
// chai-redux-mock-store
dispatchedActions: (
actions: Array<{...} | ((action: {...}) => any)>
) => ExpectChain<T>,
dispatchedTypes: (actions: Array<string>) => ExpectChain<T>,
// chai-enzyme
attr: (key: string, val?: any) => ExpectChain<T>,
data: (key: string, val?: any) => ExpectChain<T>,
prop: (key: string, val?: any) => ExpectChain<T>,
state: (key: string, val?: any) => ExpectChain<T>,
value: (val: string) => ExpectChain<T>,
className: (val: string) => ExpectChain<T>,
text: (val: string) => ExpectChain<T>,
// chai-karma-snapshot
matchSnapshot: (lang?: any, update?: boolean, msg?: any) => ExpectChain<T>,
...
};
declare var expect: {
<T>(actual: T, message?: string): ExpectChain<T>,
fail: ((message?: string) => void) & ((actual: any, expected: any, message?: string, operator?: string) => void),
...
};
declare function use(plugin: (chai: Object, utils: Object) => void): void;
declare class assert {
static (expression: mixed, message?: string): void;
static fail(
actual: mixed,
expected: mixed,
message?: string,
operator?: string
): void;
static isOk(object: mixed, message?: string): void;
static isNotOk(object: mixed, message?: string): void;
static empty(object: mixed, message?: string): void;
static isEmpty(object: mixed, message?: string): void;
static notEmpty(object: mixed, message?: string): void;
static isNotEmpty(object: mixed, message?: string): void;
static equal(actual: mixed, expected: mixed, message?: string): void;
static notEqual(actual: mixed, expected: mixed, message?: string): void;
static strictEqual(act: mixed, exp: mixed, msg?: string): void;
static notStrictEqual(act: mixed, exp: mixed, msg?: string): void;
static deepEqual(act: mixed, exp: mixed, msg?: string): void;
static notDeepEqual(act: mixed, exp: mixed, msg?: string): void;
static ok(val: mixed, msg?: string): void;
static isTrue(val: mixed, msg?: string): void;
static isNotTrue(val: mixed, msg?: string): void;
static isFalse(val: mixed, msg?: string): void;
static isNotFalse(val: mixed, msg?: string): void;
static isNull(val: mixed, msg?: string): void;
static isNotNull(val: mixed, msg?: string): void;
static isUndefined(val: mixed, msg?: string): void;
static isDefined(val: mixed, msg?: string): void;
static isNaN(val: mixed, msg?: string): void;
static isNotNaN(val: mixed, msg?: string): void;
static isAbove(val: number, abv: number, msg?: string): void;
static isBelow(val: number, blw: number, msg?: string): void;
static exists(val: mixed, msg?: string) : void;
static notExists(val: mixed, msg?: string) : void;
static isAtMost(val: number, atmst: number, msg?: string): void;
static isAtLeast(val: number, atlst: number, msg?: string): void;
static isFunction(val: mixed, msg?: string): void;
static isNotFunction(val: mixed, msg?: string): void;
static isObject(val: mixed, msg?: string): void;
static isNotObject(val: mixed, msg?: string): void;
static isArray(val: mixed, msg?: string): void;
static isNotArray(val: mixed, msg?: string): void;
static isString(val: mixed, msg?: string): void;
static isNotString(val: mixed, msg?: string): void;
static isNumber(val: mixed, msg?: string): void;
static isNotNumber(val: mixed, msg?: string): void;
static isBoolean(val: mixed, msg?: string): void;
static isNotBoolean(val: mixed, msg?: string): void;
static typeOf(val: mixed, type: string, msg?: string): void;
static notTypeOf(val: mixed, type: string, msg?: string): void;
static instanceOf(val: mixed, constructor: Class< * >, msg?: string): void;
static notInstanceOf(val: mixed, constructor: Class< * >, msg?: string): void;
static include(exp: string, inc: mixed, msg?: string): void;
static include<T>(exp: Array<T>, inc: T, msg?: string): void;
static notInclude(exp: string, inc: mixed, msg?: string): void;
static notInclude<T>(exp: Array<T>, inc: T, msg?: string): void;
static deepInclude<T>(haystack: T[] | string, needle: $Shape<T>, msg?: string) : void;
static notDeepInclude<T>(haystack: T[] | string, needle: $Shape<T>, msg?: string) : void;
static match(exp: mixed, re: RegExp, msg?: string): void;
static notMatch(exp: mixed, re: RegExp, msg?: string): void;
static property(obj: Object, prop: string, msg?: string): void;
static notProperty(obj: Object, prop: string, msg?: string): void;
static deepProperty(obj: Object, prop: string, msg?: string): void;
static notDeepProperty(obj: Object, prop: string, msg?: string): void;
static propertyVal(
obj: Object,
prop: string,
val: mixed,
msg?: string
): void;
static propertyNotVal(
obj: Object,
prop: string,
val: mixed,
msg?: string
): void;
static deepPropertyVal(
obj: Object,
prop: string,
val: mixed,
msg?: string
): void;
static deepPropertyNotVal(
obj: Object,
prop: string,
val: mixed,
msg?: string
): void;
static lengthOf(exp: mixed, len: number, msg?: string): void;
static throws<E>(
func: () => any,
err?: Class<E> | Error | RegExp | string,
errorMsgMatcher?: string | RegExp,
msg?: string
): void;
static doesNotThrow<E>(
func: () => any,
err?: Class<E> | Error | RegExp | string,
errorMsgMatcher?: string | RegExp,
msg?: string
): void;
static closeTo(
actual: number,
expected: number,
delta: number,
msg?: string
): void;
static approximately(
actual: number,
expected: number,
delta: number,
msg?: string
): void;
// chai-immutable
static sizeOf(val: mixed, length: number): void;
}
declare var config: {
includeStack: boolean,
showDiff: boolean,
truncateThreshold: number,
...
};
}

238
token/js/flow-typed/npm/mocha_v8.x.x.js vendored Normal file
View File

@ -0,0 +1,238 @@
// flow-typed signature: 195cec6dc98ab7533f0eb927ee493f99
// flow-typed version: 1a6d5d1968/mocha_v8.x.x/flow_>=v0.104.x
declare interface $npm$mocha$SetupOptions {
slow?: number;
timeout?: number;
ui?: string;
globals?: Array<any>;
reporter?: any;
bail?: boolean;
ignoreLeaks?: boolean;
grep?: any;
}
declare type $npm$mocha$done = (error?: any) => any;
// declare interface $npm$mocha$SuiteCallbackContext {
// timeout(ms: number): void;
// retries(n: number): void;
// slow(ms: number): void;
// }
// declare interface $npm$mocha$TestCallbackContext {
// skip(): void;
// timeout(ms: number): void;
// retries(n: number): void;
// slow(ms: number): void;
// [index: string]: any;
// }
declare interface $npm$mocha$Suite {
parent: $npm$mocha$Suite;
title: string;
fullTitle(): string;
}
declare type $npm$mocha$ContextDefinition = {|
(description: string, callback: (/* this: $npm$mocha$SuiteCallbackContext */) => void): $npm$mocha$Suite;
only(description: string, callback: (/* this: $npm$mocha$SuiteCallbackContext */) => void): $npm$mocha$Suite;
skip(description: string, callback: (/* this: $npm$mocha$SuiteCallbackContext */) => void): void;
timeout(ms: number): void;
|}
declare type $npm$mocha$TestDefinition = {|
(expectation: string, callback?: (/* this: $npm$mocha$TestCallbackContext, */ done: $npm$mocha$done) => mixed): $npm$mocha$Test;
only(expectation: string, callback?: (/* this: $npm$mocha$TestCallbackContext, */ done: $npm$mocha$done) => mixed): $npm$mocha$Test;
skip(expectation: string, callback?: (/* this: $npm$mocha$TestCallbackContext, */ done: $npm$mocha$done) => mixed): void;
timeout(ms: number): void;
state: 'failed' | 'passed';
|}
declare interface $npm$mocha$Runner {}
declare class $npm$mocha$BaseReporter {
stats: {
suites: number,
tests: number,
passes: number,
pending: number,
failures: number,
...
};
constructor(runner: $npm$mocha$Runner): $npm$mocha$BaseReporter;
}
declare class $npm$mocha$DocReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$DotReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$HTMLReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$HTMLCovReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$JSONReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$JSONCovReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$JSONStreamReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$LandingReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$ListReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$MarkdownReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$MinReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$NyanReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$ProgressReporter extends $npm$mocha$BaseReporter {
constructor(runner: $npm$mocha$Runner, options?: {
open?: string,
complete?: string,
incomplete?: string,
close?: string,
...
}): $npm$mocha$ProgressReporter;
}
declare class $npm$mocha$SpecReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$TAPReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$XUnitReporter extends $npm$mocha$BaseReporter {
constructor(runner: $npm$mocha$Runner, options?: any): $npm$mocha$XUnitReporter;
}
declare class $npm$mocha$Mocha {
currentTest: $npm$mocha$TestDefinition;
constructor(options?: {
grep?: RegExp,
ui?: string,
reporter?: string,
timeout?: number,
reporterOptions?: any,
slow?: number,
bail?: boolean,
...
}): $npm$mocha$Mocha;
setup(options: $npm$mocha$SetupOptions): this;
bail(value?: boolean): this;
addFile(file: string): this;
reporter(name: string): this;
reporter(reporter: (runner: $npm$mocha$Runner, options: any) => any): this;
ui(value: string): this;
grep(value: string): this;
grep(value: RegExp): this;
invert(): this;
ignoreLeaks(value: boolean): this;
checkLeaks(): this;
throwError(error: Error): void;
growl(): this;
globals(value: string): this;
globals(values: Array<string>): this;
useColors(value: boolean): this;
useInlineDiffs(value: boolean): this;
timeout(value: number): this;
slow(value: number): this;
enableTimeouts(value: boolean): this;
asyncOnly(value: boolean): this;
noHighlighting(value: boolean): this;
run(onComplete?: (failures: number) => void): $npm$mocha$Runner;
static reporters: {
Doc: $npm$mocha$DocReporter,
Dot: $npm$mocha$DotReporter,
HTML: $npm$mocha$HTMLReporter,
HTMLCov: $npm$mocha$HTMLCovReporter,
JSON: $npm$mocha$JSONReporter,
JSONCov: $npm$mocha$JSONCovReporter,
JSONStream: $npm$mocha$JSONStreamReporter,
Landing: $npm$mocha$LandingReporter,
List: $npm$mocha$ListReporter,
Markdown: $npm$mocha$MarkdownReporter,
Min: $npm$mocha$MinReporter,
Nyan: $npm$mocha$NyanReporter,
Progress: $npm$mocha$ProgressReporter,
...
};
}
// declare interface $npm$mocha$HookCallbackContext {
// skip(): void;
// timeout(ms: number): void;
// [index: string]: any;
// }
declare interface $npm$mocha$Runnable {
title: string;
fn: Function;
async: boolean;
sync: boolean;
timedOut: boolean;
}
declare interface $npm$mocha$Test extends $npm$mocha$Runnable {
parent: $npm$mocha$Suite;
pending: boolean;
state: 'failed' | 'passed' | void;
fullTitle(): string;
timeout(ms: number): void;
}
// declare interface $npm$mocha$BeforeAndAfterContext extends $npm$mocha$HookCallbackContext {
// currentTest: $npm$mocha$Test;
// }
declare var mocha: $npm$mocha$Mocha;
declare var describe: $npm$mocha$ContextDefinition;
declare var xdescribe: $npm$mocha$ContextDefinition;
declare var context: $npm$mocha$ContextDefinition;
declare var suite: $npm$mocha$ContextDefinition;
declare var it: $npm$mocha$TestDefinition;
declare var xit: $npm$mocha$TestDefinition;
declare var test: $npm$mocha$TestDefinition;
declare var specify: $npm$mocha$TestDefinition;
type Run = () => void;
declare var run: Run;
type Setup = (callback: (/* this: $npm$mocha$BeforeAndAfterContext, */ done: $npm$mocha$done) => mixed) => void;
type Teardown = (callback: (/* this: $npm$mocha$BeforeAndAfterContext, */ done: $npm$mocha$done) => mixed) => void;
type SuiteSetup = (callback: (/* this: $npm$mocha$HookCallbackContext, */ done: $npm$mocha$done) => mixed) => void;
type SuiteTeardown = (callback: (/* this: $npm$mocha$HookCallbackContext, */ done: $npm$mocha$done) => mixed) => void;
type Before =
| (callback: (/* this: $npm$mocha$HookCallbackContext, */ done: $npm$mocha$done) => mixed) => void
| (description: string, callback: (/* this: $npm$mocha$HookCallbackContext, */ done: $npm$mocha$done) => mixed) => void;
type After =
| (callback: (/* this: $npm$mocha$HookCallbackContext, */ done: $npm$mocha$done) => mixed) => void
| (description: string, callback: (/* this: $npm$mocha$HookCallbackContext, */ done: $npm$mocha$done) => mixed) => void;
type BeforeEach =
| (callback: (/* this: $npm$mocha$BeforeAndAfterContext, */ done: $npm$mocha$done) => mixed) => void
| (description: string, callback: (/* this: $npm$mocha$BeforeAndAfterContext, */ done: $npm$mocha$done) => mixed) => void;
type AfterEach =
| (callback: (/* this: $npm$mocha$BeforeAndAfterContext, */ done: $npm$mocha$done) => mixed) => void
| (description: string, callback: (/* this: $npm$mocha$BeforeAndAfterContext, */ done: $npm$mocha$done) => mixed) => void;
declare var setup: Setup;
declare var teardown: Teardown;
declare var suiteSetup: SuiteSetup;
declare var suiteTeardown;
declare var before: Before
declare var after: After;
declare var beforeEach: BeforeEach;
declare var afterEach: AfterEach;
declare module 'mocha' {
declare export var mocha: $npm$mocha$TestDefinition;
declare export var describe: $npm$mocha$ContextDefinition;
declare export var xdescribe: $npm$mocha$ContextDefinition;
declare export var context: $npm$mocha$ContextDefinition;
declare export var suite: $npm$mocha$ContextDefinition;
declare export var it: $npm$mocha$TestDefinition;
declare export var xit: $npm$mocha$TestDefinition;
declare export var test: $npm$mocha$TestDefinition;
declare export var specify: $npm$mocha$TestDefinition;
declare export var run: Run;
declare export var setup: Setup;
declare export var teardown: Teardown;
declare export var suiteSetup: SuiteSetup;
declare export var suiteTeardown: SuiteTeardown;
declare export var before: Before;
declare export var after: After;
declare export var beforeEach: BeforeEach;
declare export var afterEach: AfterEach;
declare export default $npm$mocha$Mocha;
}

21
token/js/mocha.html Normal file
View File

@ -0,0 +1,21 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Mocha Tests</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="./node_modules/mocha/mocha.css" />
</head>
<body>
<div id="mocha"></div>
<script src="./node_modules/mocha/mocha.js"></script>
<script class="mocha-init">
mocha.setup('bdd');
mocha.checkLeaks();
</script>
<script type="module" src="./test/dist/bundle.js"></script>
<script type="module" class="mocha-exec">
mocha.run();
</script>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@ -15,9 +15,18 @@
"publishConfig": {
"access": "public"
},
"browser": {
"./lib/index.cjs.js": "./lib/index.browser.esm.js",
"./lib/index.esm.js": "./lib/index.browser.esm.js"
},
"main": "lib/index.cjs.js",
"module": "lib/index.esm.js",
"types": "lib/index.d.ts",
"browserslist": [
"defaults",
"not IE 11",
"maintained node versions"
],
"files": [
"/lib",
"/module.flow.js"
@ -25,6 +34,7 @@
"testnetDefaultChannel": "v1.3.17",
"scripts": {
"build": "rollup -c",
"build:browser-test": "rollup -c test/rollup.config.js",
"start": "babel-node cli/main.js",
"start-with-test-validator": "start-server-and-test 'solana-test-validator --reset --quiet' http://localhost:8899/health start",
"lint": "npm run pretty && eslint .",
@ -39,7 +49,10 @@
"cluster:mainnet-beta": "cp cluster-mainnet-beta.env .env",
"defs": "set -ex; flow check-contents < module.flow.js; tsc --esModuleInterop module.d.ts",
"pretty": "prettier --check '{,cli*/**/}*.[jt]s'",
"pretty:fix": "prettier --write '{,cli*/**/}*.[jt]s'"
"pretty:fix": "prettier --write '{,cli*/**/}*.[jt]s'",
"test": "mocha './test/**/*.test.js'",
"test:browser": "npm run build:browser-test && mocha-headless-chrome -f http://localhost:8080/mocha.html --timeout 180000",
"test:browser-with-server": "start-server-and-test 'http-server -p 8080' 8080 test:browser"
},
"dependencies": {
"@babel/runtime": "^7.10.5",
@ -57,22 +70,36 @@
"@babel/plugin-transform-runtime": "^7.10.5",
"@babel/preset-env": "^7.10.4",
"@babel/preset-flow": "^7.10.4",
"@babel/register": "^7.13.0",
"@rollup/plugin-alias": "^3.1.2",
"@rollup/plugin-babel": "^5.1.0",
"@rollup/plugin-commonjs": "^17.0.0",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-multi-entry": "^4.0.0",
"@rollup/plugin-node-resolve": "^11.2.0",
"@types/bn.js": "^5.1.0",
"@typescript-eslint/eslint-plugin": "^4.14.2",
"@typescript-eslint/parser": "^4.14.2",
"babel-eslint": "^10.1.0",
"chai": "^4.3.0",
"eslint": "^7.4.0",
"eslint-plugin-flowtype": "^5.2.0",
"eslint-plugin-flowtype": "^5.3.1",
"eslint-plugin-import": "^2.22.0",
"flow-bin": "0.145.0",
"flow-typed": "^3.2.0",
"eslint-plugin-mocha": "^8.0.0",
"esm": "^3.2.25",
"flow-bin": "^0.145.0",
"flow-remove-types": "^2.145.0",
"flow-typed": "^3.3.1",
"http-server": "^0.12.3",
"mkdirp": "^1.0.4",
"mocha": "^8.3.0",
"mocha-headless-chrome": "^3.1.0",
"mz": "^2.7.0",
"prettier": "^2.0.5",
"rollup": "^2.23.0",
"rollup-plugin-copy": "^3.3.0",
"rollup-plugin-node-polyfills": "^0.2.1",
"rollup-plugin-terser": "^7.0.2",
"start-server-and-test": "^1.11.6",
"typescript": "^4.1.3",
"watch": "^1.0.2"

View File

@ -1,26 +1,93 @@
import babel from '@rollup/plugin-babel';
import commonjs from '@rollup/plugin-commonjs';
import copy from 'rollup-plugin-copy';
import flowRemoveTypes from 'flow-remove-types';
import json from '@rollup/plugin-json';
import nodeResolve from '@rollup/plugin-node-resolve';
import nodePolyfills from 'rollup-plugin-node-polyfills';
import {terser} from 'rollup-plugin-terser';
function generateConfig(configType, format) {
const browser = configType === 'browser';
const bundle = format === 'iife';
function generateConfig(configType) {
const config = {
input: 'client/token.js',
plugins: [
babel({
configFile: './babel.rollup.config.json',
exclude: 'node_modules/**',
babelHelpers: 'runtime',
}),
flow(),
commonjs(),
nodeResolve({
browser,
preferBuiltins: !browser,
dedupe: ['bn.js', 'buffer'],
}),
babel({
exclude: '**/node_modules/**',
babelHelpers: bundle ? 'bundled' : 'runtime',
plugins: bundle ? [] : ['@babel/plugin-transform-runtime'],
}),
copy({
targets: [{src: 'module.d.ts', dest: 'lib', rename: 'index.d.ts'}],
}),
],
treeshake: {
moduleSideEffects: false,
},
};
switch (configType) {
case 'browser':
// TODO: Add support
switch (format) {
case 'esm': {
config.output = [
{
file: 'lib/index.browser.esm.js',
format: 'es',
sourcemap: true,
},
];
// Prevent dependencies from being bundled
config.external = [
/@babel\/runtime/,
'bn.js',
// Bundled for `Buffer` consistency
// 'bs58',
// 'buffer',
// 'buffer-layout',
'@solana/web3.js',
];
break;
}
case 'iife': {
config.output = [
{
file: 'lib/index.iife.js',
format: 'iife',
name: 'splToken',
sourcemap: true,
},
{
file: 'lib/index.iife.min.js',
format: 'iife',
name: 'splToken',
sourcemap: true,
plugins: [terser({mangle: false, compress: false})],
},
];
break;
}
default:
throw new Error(`Unknown format: ${format}`);
}
// TODO: Find a workaround to avoid resolving the following JSON file:
// `node_modules/secp256k1/node_modules/elliptic/package.json`
config.plugins.push(json());
config.plugins.push(nodePolyfills());
break;
case 'node':
config.output = [
@ -40,25 +107,8 @@ function generateConfig(configType) {
// package.json "dependencies" section. Unfortunately this list is manually
// maintained.
config.external = [
/@babel\/runtime/,
'assert',
'@babel/runtime/core-js/get-iterator',
'@babel/runtime/core-js/json/stringify',
'@babel/runtime/core-js/object/assign',
'@babel/runtime/core-js/object/get-prototype-of',
'@babel/runtime/core-js/object/keys',
'@babel/runtime/core-js/promise',
'@babel/runtime/helpers/asyncToGenerator',
'@babel/runtime/helpers/classCallCheck',
'@babel/runtime/helpers/createClass',
'@babel/runtime/helpers/defineProperty',
'@babel/runtime/helpers/get',
'@babel/runtime/helpers/getPrototypeOf',
'@babel/runtime/helpers/inherits',
'@babel/runtime/helpers/possibleConstructorReturn',
'@babel/runtime/helpers/slicedToArray',
'@babel/runtime/helpers/toConsumableArray',
'@babel/runtime/helpers/typeof',
'@babel/runtime/regenerator',
'bn.js',
'buffer-layout',
'@solana/web3.js',
@ -71,4 +121,20 @@ function generateConfig(configType) {
return config;
}
export default [generateConfig('node')];
export default [
generateConfig('node'),
generateConfig('browser', 'esm'),
generateConfig('browser', 'iife'),
];
// Using this instead of rollup-plugin-flow due to
// https://github.com/leebyron/rollup-plugin-flow/issues/5
function flow() {
return {
name: 'flow-remove-types',
transform: code => ({
code: flowRemoveTypes(code).toString(),
map: null,
}),
};
}

1
token/js/test/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
dist

View File

@ -0,0 +1,65 @@
import alias from '@rollup/plugin-alias';
import babel from '@rollup/plugin-babel';
import commonjs from '@rollup/plugin-commonjs';
import flowRemoveTypes from 'flow-remove-types';
import json from '@rollup/plugin-json';
import multi from '@rollup/plugin-multi-entry';
import nodeResolve from '@rollup/plugin-node-resolve';
import nodePolyfills from 'rollup-plugin-node-polyfills';
export default {
input: {
include: ['test/**/*.test.js'],
},
external: ['node-forge', 'http2', '_stream_wrap'],
output: {
file: 'test/dist/bundle.js',
format: 'es',
sourcemap: true,
},
plugins: [
flow(),
multi(),
commonjs(),
nodeResolve({
browser: true,
preferBuiltins: false,
dedupe: ['bn.js', 'buffer'],
}),
babel({
exclude: '**/node_modules/**',
babelHelpers: 'runtime',
plugins: ['@babel/plugin-transform-runtime'],
}),
nodePolyfills(),
alias({
entries: [
{
find: /^\.\.\/src\/.*\.js$/,
replacement: './lib/index.browser.esm.js',
},
],
}),
json(),
],
onwarn: function (warning, rollupWarn) {
if (warning.code !== 'CIRCULAR_DEPENDENCY' && warning.code !== 'EVAL') {
rollupWarn(warning);
}
},
treeshake: {
moduleSideEffects: path => path.endsWith('test.js'),
},
};
// Using this instead of rollup-plugin-flow due to
// https://github.com/leebyron/rollup-plugin-flow/issues/5
function flow() {
return {
name: 'flow-remove-types',
transform: code => ({
code: flowRemoveTypes(code).toString(),
map: null,
}),
};
}

View File

@ -0,0 +1,34 @@
// @flow
import {expect} from 'chai';
import {Account} from '@solana/web3.js';
import {Token, TOKEN_PROGRAM_ID} from '../client/token';
describe('Token', () => {
it('createTransfer', () => {
const ix = Token.createTransferCheckedInstruction(
TOKEN_PROGRAM_ID,
new Account().publicKey,
new Account().publicKey,
new Account().publicKey,
new Account().publicKey,
[],
1,
9,
);
expect(ix.programId).to.eql(TOKEN_PROGRAM_ID);
expect(ix.keys).to.have.length(4);
});
it('createInitMint', () => {
const ix = Token.createInitMintInstruction(
TOKEN_PROGRAM_ID,
new Account().publicKey,
9,
new Account().publicKey,
null,
);
expect(ix.programId).to.eql(TOKEN_PROGRAM_ID);
expect(ix.keys).to.have.length(2);
});
});