@1inch/solidity-utils 1.3.0 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,7 @@
1
+ Copyright (c) 2019-2021 1inch
2
+
3
+ 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:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ 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.
@@ -0,0 +1,3 @@
1
+ import BN from "bn.js";
2
+ export declare function toBNExtended(value: string | number | BN): BN;
3
+ export declare function assertRoughlyEqualValues(expected: string | number | BN, actual: string | number | BN, relativeDiff: number): void;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assertRoughlyEqualValues = exports.toBNExtended = void 0;
4
+ const prelude_1 = require("./prelude");
5
+ function toBNExtended(value) {
6
+ if (typeof value === 'string' || typeof value === 'number') {
7
+ return (0, prelude_1.toBN)(value);
8
+ }
9
+ return value;
10
+ }
11
+ exports.toBNExtended = toBNExtended;
12
+ function assertRoughlyEqualValues(expected, actual, relativeDiff) {
13
+ const expectedBN = toBNExtended(expected);
14
+ const actualBN = toBNExtended(actual);
15
+ let multiplerNumerator = relativeDiff;
16
+ let multiplerDenominator = (0, prelude_1.toBN)('1');
17
+ while (!Number.isInteger(multiplerNumerator)) {
18
+ multiplerDenominator = multiplerDenominator.mul((0, prelude_1.toBN)('10'));
19
+ multiplerNumerator *= 10;
20
+ }
21
+ const diff = expectedBN.sub(actualBN).abs();
22
+ const treshold = expectedBN.mul((0, prelude_1.toBN)(multiplerNumerator.toString())).div(multiplerDenominator);
23
+ if (!diff.lte(treshold)) {
24
+ (0, prelude_1.expect)(actualBN).to.be.bignumber.equal(expectedBN, `${actualBN} != ${expectedBN} with ${relativeDiff} precision`);
25
+ }
26
+ }
27
+ exports.assertRoughlyEqualValues = assertRoughlyEqualValues;
28
+ //# sourceMappingURL=asserts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"asserts.js","sourceRoot":"","sources":["../../src/asserts.ts"],"names":[],"mappings":";;;AAAA,uCAAyC;AAGzC,SAAgB,YAAY,CAAE,KAA2B;IACrD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QACxD,OAAO,IAAA,cAAI,EAAC,KAAK,CAAC,CAAC;KACtB;IACD,OAAO,KAAK,CAAC;AACjB,CAAC;AALD,oCAKC;AAED,SAAgB,wBAAwB,CAAE,QAA8B,EAAE,MAA4B,EAAE,YAAoB;IACxH,MAAM,UAAU,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC;IAC1C,MAAM,QAAQ,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC;IAEtC,IAAI,kBAAkB,GAAG,YAAY,CAAC;IACtC,IAAI,oBAAoB,GAAG,IAAA,cAAI,EAAC,GAAG,CAAC,CAAC;IACrC,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,kBAAkB,CAAC,EAAE;QAC1C,oBAAoB,GAAG,oBAAoB,CAAC,GAAG,CAAC,IAAA,cAAI,EAAC,IAAI,CAAC,CAAC,CAAC;QAC5D,kBAAkB,IAAI,EAAE,CAAC;KAC5B;IACD,MAAM,IAAI,GAAG,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,GAAG,EAAE,CAAC;IAC5C,MAAM,QAAQ,GAAG,UAAU,CAAC,GAAG,CAAC,IAAA,cAAI,EAAC,kBAAkB,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;IAC/F,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE;QACrB,IAAA,gBAAM,EAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,UAAU,EAAE,GAAG,QAAQ,OAAO,UAAU,SAAS,YAAY,YAAY,CAAC,CAAC;KACrH;AACL,CAAC;AAfD,4DAeC"}
@@ -0,0 +1,5 @@
1
+ export * from './asserts';
2
+ export * from './permit';
3
+ export * from './prelude';
4
+ export * from './profileEVM';
5
+ export * from './utils';
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ // created from 'create-ts-index'
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const tslib_1 = require("tslib");
5
+ (0, tslib_1.__exportStar)(require("./asserts"), exports);
6
+ (0, tslib_1.__exportStar)(require("./permit"), exports);
7
+ (0, tslib_1.__exportStar)(require("./prelude"), exports);
8
+ (0, tslib_1.__exportStar)(require("./profileEVM"), exports);
9
+ (0, tslib_1.__exportStar)(require("./utils"), exports);
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA,iCAAiC;;;AAEjC,yDAA0B;AAC1B,wDAAyB;AACzB,yDAA0B;AAC1B,4DAA6B;AAC7B,uDAAwB"}
@@ -0,0 +1,79 @@
1
+ import { MessageTypes, SignTypedDataVersion, TypedMessage } from '@metamask/eth-sig-util';
2
+ import { Token } from './utils';
3
+ export declare const TypedDataVersion = SignTypedDataVersion.V3;
4
+ export declare const defaultDeadline: string;
5
+ export declare const EIP712Domain: {
6
+ name: string;
7
+ type: string;
8
+ }[];
9
+ export declare const Permit: {
10
+ name: string;
11
+ type: string;
12
+ }[];
13
+ export declare const DaiLikePermit: {
14
+ name: string;
15
+ type: string;
16
+ }[];
17
+ export declare function trim0x(bigNumber: BN | string): string;
18
+ export declare function cutSelector(data: string): string;
19
+ export declare function domainSeparator(name: string, version: string, chainId: string, verifyingContract: string): string;
20
+ export declare function buildData(name: string, version: string, chainId: number, verifyingContract: string, owner: string, spender: string, value: string, nonce: string, deadline?: string): {
21
+ readonly primaryType: "Permit";
22
+ readonly types: {
23
+ readonly EIP712Domain: {
24
+ name: string;
25
+ type: string;
26
+ }[];
27
+ readonly Permit: {
28
+ name: string;
29
+ type: string;
30
+ }[];
31
+ };
32
+ readonly domain: {
33
+ readonly name: string;
34
+ readonly version: string;
35
+ readonly chainId: number;
36
+ readonly verifyingContract: string;
37
+ };
38
+ readonly message: {
39
+ readonly owner: string;
40
+ readonly spender: string;
41
+ readonly value: string;
42
+ readonly nonce: string;
43
+ readonly deadline: string;
44
+ };
45
+ };
46
+ export declare function buildDataLikeDai(name: string, version: string, chainId: number, verifyingContract: string, holder: string, spender: string, nonce: string, allowed: boolean, expiry?: string): {
47
+ readonly primaryType: "Permit";
48
+ readonly types: {
49
+ readonly EIP712Domain: {
50
+ name: string;
51
+ type: string;
52
+ }[];
53
+ readonly Permit: {
54
+ name: string;
55
+ type: string;
56
+ }[];
57
+ };
58
+ readonly domain: {
59
+ readonly name: string;
60
+ readonly version: string;
61
+ readonly chainId: number;
62
+ readonly verifyingContract: string;
63
+ };
64
+ readonly message: {
65
+ readonly holder: string;
66
+ readonly spender: string;
67
+ readonly nonce: string;
68
+ readonly expiry: string;
69
+ readonly allowed: boolean;
70
+ };
71
+ };
72
+ export interface PermittableToken extends Token {
73
+ nonces(owner: string, txDetails?: Truffle.TransactionDetails): Promise<BN>;
74
+ name(txDetails?: Truffle.TransactionDetails): Promise<string>;
75
+ }
76
+ export declare function signWithPk<T extends MessageTypes>(privateKey: string, data: TypedMessage<T>): string;
77
+ export declare function getPermit(owner: string, ownerPrivateKey: string, permitContract: PermittableToken, tokenVersion: string, chainId: number, spender: string, value: string, deadline?: string): Promise<string>;
78
+ export declare function getPermitLikeDai(holder: string, holderPrivateKey: string, permitContract: PermittableToken, tokenVersion: string, chainId: number, spender: string, allowed: boolean, expiry?: string): Promise<string>;
79
+ export declare function withTarget(target: BN | string, data: BN | string): string;
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.withTarget = exports.getPermitLikeDai = exports.getPermit = exports.signWithPk = exports.buildDataLikeDai = exports.buildData = exports.domainSeparator = exports.cutSelector = exports.trim0x = exports.DaiLikePermit = exports.Permit = exports.EIP712Domain = exports.defaultDeadline = exports.TypedDataVersion = void 0;
4
+ const eth_sig_util_1 = require("@metamask/eth-sig-util");
5
+ const ethereumjs_util_1 = require("ethereumjs-util");
6
+ const prelude_1 = require("./prelude");
7
+ exports.TypedDataVersion = eth_sig_util_1.SignTypedDataVersion.V3;
8
+ exports.defaultDeadline = prelude_1.constants.MAX_UINT256;
9
+ exports.EIP712Domain = [
10
+ { name: 'name', type: 'string' },
11
+ { name: 'version', type: 'string' },
12
+ { name: 'chainId', type: 'uint256' },
13
+ { name: 'verifyingContract', type: 'address' },
14
+ ];
15
+ exports.Permit = [
16
+ { name: 'owner', type: 'address' },
17
+ { name: 'spender', type: 'address' },
18
+ { name: 'value', type: 'uint256' },
19
+ { name: 'nonce', type: 'uint256' },
20
+ { name: 'deadline', type: 'uint256' },
21
+ ];
22
+ exports.DaiLikePermit = [
23
+ { name: 'holder', type: 'address' },
24
+ { name: 'spender', type: 'address' },
25
+ { name: 'nonce', type: 'uint256' },
26
+ { name: 'expiry', type: 'uint256' },
27
+ { name: 'allowed', type: 'bool' },
28
+ ];
29
+ function trim0x(bigNumber) {
30
+ const s = bigNumber.toString();
31
+ if (s.startsWith('0x')) {
32
+ return s.substring(2);
33
+ }
34
+ return s;
35
+ }
36
+ exports.trim0x = trim0x;
37
+ function cutSelector(data) {
38
+ const hexPrefix = '0x';
39
+ return hexPrefix + data.substr(hexPrefix.length + 8);
40
+ }
41
+ exports.cutSelector = cutSelector;
42
+ function domainSeparator(name, version, chainId, verifyingContract) {
43
+ return '0x' + eth_sig_util_1.TypedDataUtils.hashStruct('EIP712Domain', { name, version, chainId, verifyingContract }, { EIP712Domain: exports.EIP712Domain }, exports.TypedDataVersion).toString('hex');
44
+ }
45
+ exports.domainSeparator = domainSeparator;
46
+ function buildData(name, version, chainId, verifyingContract, owner, spender, value, nonce, deadline = exports.defaultDeadline) {
47
+ return {
48
+ primaryType: 'Permit',
49
+ types: { EIP712Domain: exports.EIP712Domain, Permit: exports.Permit },
50
+ domain: { name, version, chainId, verifyingContract },
51
+ message: { owner, spender, value, nonce, deadline },
52
+ };
53
+ }
54
+ exports.buildData = buildData;
55
+ function buildDataLikeDai(name, version, chainId, verifyingContract, holder, spender, nonce, allowed, expiry = exports.defaultDeadline) {
56
+ return {
57
+ primaryType: 'Permit',
58
+ types: { EIP712Domain: exports.EIP712Domain, Permit: exports.DaiLikePermit },
59
+ domain: { name, version, chainId, verifyingContract },
60
+ message: { holder, spender, nonce, expiry, allowed },
61
+ };
62
+ }
63
+ exports.buildDataLikeDai = buildDataLikeDai;
64
+ function signWithPk(privateKey, data) {
65
+ return (0, eth_sig_util_1.signTypedData)({ privateKey: Buffer.from(trim0x(privateKey), 'hex'), data, version: exports.TypedDataVersion });
66
+ }
67
+ exports.signWithPk = signWithPk;
68
+ /*
69
+ * @param permitContract The contract object with ERC20Permit type and token address for which the permit creating.
70
+ */
71
+ async function getPermit(owner, ownerPrivateKey, permitContract, tokenVersion, chainId, spender, value, deadline = exports.defaultDeadline) {
72
+ const nonce = await permitContract.nonces(owner);
73
+ const name = await permitContract.name();
74
+ const data = buildData(name, tokenVersion, chainId, permitContract.address, owner, spender, value, nonce.toString(), deadline);
75
+ const signature = signWithPk(ownerPrivateKey, data);
76
+ const { v, r, s } = (0, ethereumjs_util_1.fromRpcSig)(signature);
77
+ const permitCall = permitContract.contract.methods.permit(owner, spender, value, deadline, v, r, s).encodeABI();
78
+ return cutSelector(permitCall);
79
+ }
80
+ exports.getPermit = getPermit;
81
+ /*
82
+ * @param permitContract The contract object with ERC20PermitLikeDai type and token address for which the permit creating.
83
+ */
84
+ async function getPermitLikeDai(holder, holderPrivateKey, permitContract, tokenVersion, chainId, spender, allowed, expiry = exports.defaultDeadline) {
85
+ const nonce = await permitContract.nonces(holder);
86
+ const name = await permitContract.name();
87
+ const data = buildDataLikeDai(name, tokenVersion, chainId, permitContract.address, holder, spender, nonce.toString(), allowed, expiry);
88
+ const signature = signWithPk(holderPrivateKey, data);
89
+ const { v, r, s } = (0, ethereumjs_util_1.fromRpcSig)(signature);
90
+ const permitCall = permitContract.contract.methods.permit(holder, spender, nonce, expiry, allowed, v, r, s).encodeABI();
91
+ return cutSelector(permitCall);
92
+ }
93
+ exports.getPermitLikeDai = getPermitLikeDai;
94
+ function withTarget(target, data) {
95
+ return target.toString() + trim0x(data);
96
+ }
97
+ exports.withTarget = withTarget;
98
+ //# sourceMappingURL=permit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"permit.js","sourceRoot":"","sources":["../../src/permit.ts"],"names":[],"mappings":";;;AAAA,yDAAyH;AACzH,qDAA6C;AAE7C,uCAAsC;AAGzB,QAAA,gBAAgB,GAAG,mCAAoB,CAAC,EAAE,CAAC;AAC3C,QAAA,eAAe,GAAG,mBAAS,CAAC,WAAW,CAAC;AAExC,QAAA,YAAY,GAAG;IACxB,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE;IAChC,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,QAAQ,EAAE;IACnC,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,SA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c,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAClD,MAAM,IAAI,GAAG,MAAM,cAAc,CAAC,IAAI,EAAE,CAAC;IACzC,MAAM,IAAI,GAAG,gBAAgB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,QAAQ,EAAE,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;IACvI,MAAM,SAAS,GAAG,UAAU,CAAC,gBAAgB,EAAE,IAAI,CAAC,CAAC;IACrD,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,IAAA,4BAAU,EAAC,SAAS,CAAC,CAAC;IAC1C,MAAM,UAAU,GAAG,cAAc,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC;IACxH,OAAO,WAAW,CAAC,UAAU,CAAC,CAAC;AACnC,CAAC;AAfD,4CAeC;AAED,SAAgB,UAAU,CAAE,MAAmB,EAAE,IAAiB;IAC9D,OAAO,MAAM,CAAC,QAAQ,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;AAC5C,CAAC;AAFD,gCAEC"}
@@ -0,0 +1,19 @@
1
+ import { Assertion, AssertionError, assert, expect, config, should } from 'chai';
2
+ import 'chai-bn';
3
+ import { toBN } from 'web3-utils';
4
+ import BN from "bn.js";
5
+ export declare const constants: {
6
+ readonly ZERO_ADDRESS: "0x0000000000000000000000000000000000000000";
7
+ readonly ZERO_BYTES32: "0x0000000000000000000000000000000000000000000000000000000000000000";
8
+ readonly MAX_UINT256: string;
9
+ readonly MAX_INT256: string;
10
+ readonly MIN_INT256: string;
11
+ };
12
+ export { toBN, };
13
+ export declare type Time = {
14
+ increaseTo: (target: string | number | BN) => Promise<BN>;
15
+ latest: () => Promise<BN>;
16
+ };
17
+ export declare const time: Time;
18
+ export declare function ether(n: string): BN;
19
+ export { Assertion, AssertionError, assert, expect, config, should, };
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.should = exports.config = exports.expect = exports.assert = exports.AssertionError = exports.Assertion = exports.ether = exports.time = exports.toBN = exports.constants = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const chai_1 = (0, tslib_1.__importStar)(require("chai"));
6
+ Object.defineProperty(exports, "Assertion", { enumerable: true, get: function () { return chai_1.Assertion; } });
7
+ Object.defineProperty(exports, "AssertionError", { enumerable: true, get: function () { return chai_1.AssertionError; } });
8
+ Object.defineProperty(exports, "assert", { enumerable: true, get: function () { return chai_1.assert; } });
9
+ Object.defineProperty(exports, "expect", { enumerable: true, get: function () { return chai_1.expect; } });
10
+ Object.defineProperty(exports, "config", { enumerable: true, get: function () { return chai_1.config; } });
11
+ Object.defineProperty(exports, "should", { enumerable: true, get: function () { return chai_1.should; } });
12
+ require("chai-bn");
13
+ const chai_as_promised_1 = (0, tslib_1.__importDefault)(require("chai-as-promised"));
14
+ const web3_utils_1 = require("web3-utils");
15
+ Object.defineProperty(exports, "toBN", { enumerable: true, get: function () { return web3_utils_1.toBN; } });
16
+ chai_1.default.use(chai_as_promised_1.default);
17
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
18
+ const { time: timeImpl } = require('@openzeppelin/test-helpers');
19
+ exports.constants = {
20
+ ZERO_ADDRESS: '0x0000000000000000000000000000000000000000',
21
+ ZERO_BYTES32: '0x0000000000000000000000000000000000000000000000000000000000000000',
22
+ MAX_UINT256: (0, web3_utils_1.toBN)('2').pow((0, web3_utils_1.toBN)('256')).sub((0, web3_utils_1.toBN)('1')).toString(),
23
+ MAX_INT256: (0, web3_utils_1.toBN)('2').pow((0, web3_utils_1.toBN)('255')).sub((0, web3_utils_1.toBN)('1')).toString(),
24
+ MIN_INT256: (0, web3_utils_1.toBN)('2').pow((0, web3_utils_1.toBN)('255')).mul((0, web3_utils_1.toBN)('-1')).toString(),
25
+ };
26
+ exports.time = timeImpl;
27
+ function ether(n) {
28
+ return (0, web3_utils_1.toBN)((0, web3_utils_1.toWei)(n, 'ether'));
29
+ }
30
+ exports.ether = ether;
31
+ //# sourceMappingURL=prelude.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prelude.js","sourceRoot":"","sources":["../../src/prelude.ts"],"names":[],"mappings":";;;;AAAA,0DAAuF;AAoCnF,0FApCW,gBAAS,OAoCX;AACT,+FArCsB,qBAAc,OAqCtB;AACd,uFAtCsC,aAAM,OAsCtC;AACN,uFAvC8C,aAAM,OAuC9C;AACN,uFAxCsD,aAAM,OAwCtD;AACN,uFAzC8D,aAAM,OAyC9D;AAxCV,mBAAiB;AACjB,qFAA8C;AAC9C,2CAAyC;AAgBrC,qFAhBK,iBAAI,OAgBL;AAdR,cAAI,CAAC,GAAG,CAAC,0BAAc,CAAC,CAAC;AACzB,8DAA8D;AAC9D,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC,4BAA4B,CAAC,CAAC;AAEpD,QAAA,SAAS,GAAG;IACrB,YAAY,EAAE,4CAA4C;IAC1D,YAAY,EAAE,oEAAoE;IAClF,WAAW,EAAE,IAAA,iBAAI,EAAC,GAAG,CAAC,CAAC,GAAG,CAAC,IAAA,iBAAI,EAAC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,IAAA,iBAAI,EAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,EAAE;IACjE,UAAU,EAAE,IAAA,iBAAI,EAAC,GAAG,CAAC,CAAC,GAAG,CAAC,IAAA,iBAAI,EAAC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,IAAA,iBAAI,EAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,EAAE;IAChE,UAAU,EAAE,IAAA,iBAAI,EAAC,GAAG,CAAC,CAAC,GAAG,CAAC,IAAA,iBAAI,EAAC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,IAAA,iBAAI,EAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,EAAE;CAC3D,CAAC;AAaE,QAAA,IAAI,GAAS,QAAQ,CAAC;AAEnC,SAAgB,KAAK,CAAE,CAAS;IAC5B,OAAO,IAAA,iBAAI,EAAC,IAAA,kBAAK,EAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;AACnC,CAAC;AAFD,sBAEC"}
@@ -0,0 +1,9 @@
1
+ /// <reference types="node" />
2
+ import { PathLike, promises as fs } from 'fs';
3
+ export declare const gasspectOptionsDefault: {
4
+ minOpGasCost: number;
5
+ args: boolean;
6
+ res: boolean;
7
+ };
8
+ export declare function profileEVM(txHash: string, instruction: string[], optionalTraceFile?: PathLike | fs.FileHandle): Promise<number[]>;
9
+ export declare function gasspectEVM(txHash: string, gasspectOptions?: Record<string, unknown>, optionalTraceFile?: PathLike | fs.FileHandle): Promise<string[]>;
@@ -1,27 +1,27 @@
1
- const { promisify } = require('util');
2
- const fs = require('fs').promises;
3
-
4
- const gasspectOptionsDefault = {
5
- minOpGasCost: 300, // minimal gas cost of returned operations
6
- args: false, // return operations arguments
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.gasspectEVM = exports.profileEVM = exports.gasspectOptionsDefault = void 0;
4
+ const util_1 = require("util");
5
+ const fs_1 = require("fs");
6
+ const prelude_1 = require("./prelude");
7
+ exports.gasspectOptionsDefault = {
8
+ minOpGasCost: 300,
9
+ args: false,
7
10
  res: false, // return operations results
8
11
  };
9
-
10
- function _normalizeOp (ops, i) {
12
+ function _normalizeOp(ops, i) {
11
13
  if (ops[i].op === 'STATICCALL') {
12
14
  ops[i].gasCost = ops[i].gasCost - ops[i + 1].gas;
13
-
14
15
  if (ops[i].stack.length > 8 && ops[i].stack[ops[i].stack.length - 8] === '0000000000000000000000000000000000000000000000000000000000000001') {
15
16
  ops[i].op = 'STATICCALL-ECRECOVER';
16
- } else if (ops[i].stack.length > 8 && ops[i].stack[ops[i].stack.length - 8] <= '00000000000000000000000000000000000000000000000000000000000000FF') {
17
+ }
18
+ else if (ops[i].stack.length > 8 && ops[i].stack[ops[i].stack.length - 8] <= '00000000000000000000000000000000000000000000000000000000000000FF') {
17
19
  ops[i].op = 'STATICCALL-' + ops[i].stack[ops[i].stack.length - 8].substr(62, 2);
18
- } else {
20
+ }
21
+ else {
19
22
  ops[i].args = [
20
23
  '0x' + ops[i].stack[ops[i].stack.length - 2].substr(24),
21
- '0x' + (ops[i].memory || []).join('').substr(
22
- 2 * web3.utils.toBN(ops[i].stack[ops[i].stack.length - 3]).toNumber(),
23
- 2 * web3.utils.toBN(ops[i].stack[ops[i].stack.length - 4]).toNumber(),
24
- ),
24
+ '0x' + (ops[i].memory || []).join('').substr(2 * (0, prelude_1.toBN)(ops[i].stack[ops[i].stack.length - 3]).toNumber(), 2 * (0, prelude_1.toBN)(ops[i].stack[ops[i].stack.length - 4]).toNumber()),
25
25
  ];
26
26
  if (ops[i].gasCost === 100) {
27
27
  ops[i].op += '_R';
@@ -31,14 +31,10 @@ function _normalizeOp (ops, i) {
31
31
  if (['CALL', 'DELEGATECALL', 'CALLCODE'].indexOf(ops[i].op) !== -1) {
32
32
  ops[i].args = [
33
33
  '0x' + ops[i].stack[ops[i].stack.length - 2].substr(24),
34
- '0x' + (ops[i].memory || []).join('').substr(
35
- 2 * web3.utils.toBN(ops[i].stack[ops[i].stack.length - 4]).toNumber(),
36
- 2 * web3.utils.toBN(ops[i].stack[ops[i].stack.length - 5]).toNumber(),
37
- ),
34
+ '0x' + (ops[i].memory || []).join('').substr(2 * (0, prelude_1.toBN)(ops[i].stack[ops[i].stack.length - 4]).toNumber(), 2 * (0, prelude_1.toBN)(ops[i].stack[ops[i].stack.length - 5]).toNumber()),
38
35
  ];
39
36
  ops[i].gasCost = ops[i].gasCost - ops[i + 1].gas;
40
37
  ops[i].res = ops[i + 1].stack[ops[i + 1].stack.length - 1];
41
-
42
38
  if (ops[i].gasCost === 100) {
43
39
  ops[i].op += '_R';
44
40
  }
@@ -59,7 +55,6 @@ function _normalizeOp (ops, i) {
59
55
  if (ops[i].gasCost === 20000) {
60
56
  ops[i].op += '_I';
61
57
  }
62
-
63
58
  if (ops[i].op.startsWith('SLOAD')) {
64
59
  ops[i].res = ops[i + 1].stack[ops[i + 1].stack.length - 1];
65
60
  }
@@ -71,70 +66,60 @@ function _normalizeOp (ops, i) {
71
66
  ops[i].res = ops[i + 1].stack[ops[i + 1].stack.length - 1];
72
67
  }
73
68
  }
74
-
75
- async function profileEVM (txHash, instruction, optionalTraceFile) {
76
- const trace = await promisify(web3.currentProvider.send.bind(web3.currentProvider))({
69
+ async function profileEVM(txHash, instruction, optionalTraceFile) {
70
+ if (!web3.currentProvider || typeof web3.currentProvider === 'string' || !web3.currentProvider.send) {
71
+ throw new Error('Unsupported provider');
72
+ }
73
+ const trace = await (0, util_1.promisify)(web3.currentProvider.send.bind(web3.currentProvider))({
77
74
  jsonrpc: '2.0',
78
75
  method: 'debug_traceTransaction',
79
76
  params: [txHash, {}],
80
77
  id: new Date().getTime(),
81
78
  });
82
-
83
79
  const str = JSON.stringify(trace);
84
-
85
80
  if (optionalTraceFile) {
86
- await fs.writeFile(optionalTraceFile, str);
87
- }
88
-
89
- if (Array.isArray(instruction)) {
90
- return instruction.map(instr => {
91
- return str.split('"' + instr.toUpperCase() + '"').length - 1;
92
- });
81
+ await fs_1.promises.writeFile(optionalTraceFile, str);
93
82
  }
94
-
95
- return str.split('"' + instruction.toUpperCase() + '"').length - 1;
83
+ return instruction.map(instr => {
84
+ return str.split('"' + instr.toUpperCase() + '"').length - 1;
85
+ });
96
86
  }
97
-
98
- async function gasspectEVM (txHash, options = gasspectOptionsDefault, optionalTraceFile) {
99
- options = { ...gasspectOptionsDefault, ...options };
100
-
101
- const trace = await promisify(web3.currentProvider.send.bind(web3.currentProvider))({
87
+ exports.profileEVM = profileEVM;
88
+ async function gasspectEVM(txHash, gasspectOptions = {}, optionalTraceFile) {
89
+ const options = { ...exports.gasspectOptionsDefault, ...gasspectOptions };
90
+ if (!web3.currentProvider) {
91
+ throw new Error('Provider not set');
92
+ }
93
+ if (!web3.currentProvider || typeof web3.currentProvider === 'string' || !web3.currentProvider.send) {
94
+ throw new Error('Unsupported provider');
95
+ }
96
+ const trace = await (0, util_1.promisify)(web3.currentProvider.send.bind(web3.currentProvider))({
102
97
  jsonrpc: '2.0',
103
98
  method: 'debug_traceTransaction',
104
99
  params: [txHash, {}],
105
100
  id: new Date().getTime(),
106
101
  });
107
-
108
- const ops = trace.result.structLogs;
109
-
102
+ const ops = trace === null || trace === void 0 ? void 0 : trace.result.structLogs;
110
103
  const traceAddress = [0, -1];
111
104
  for (const [i, op] of ops.entries()) {
112
105
  op.traceAddress = traceAddress.slice(0, traceAddress.length - 1);
113
106
  _normalizeOp(ops, i);
114
-
115
107
  if (op.depth + 2 > traceAddress.length) {
116
108
  traceAddress[traceAddress.length - 1] += 1;
117
109
  traceAddress.push(-1);
118
110
  }
119
-
120
111
  if (op.depth + 2 < traceAddress.length) {
121
112
  traceAddress.pop();
122
113
  }
123
114
  }
124
-
125
115
  const result = ops.filter(op => op.gasCost > options.minOpGasCost).map(op => op.traceAddress.join('-') + '-' + op.op +
126
- (options.args ? '(' + (op.args || []).join(',') + ')' : '') +
127
- (options.res ? (op.res ? ':0x' + op.res : '') : '') +
128
- ' = ' + op.gasCost);
129
-
116
+ (options.args ? '(' + (op.args || []).join(',') + ')' : '') +
117
+ (options.res ? (op.res ? ':0x' + op.res : '') : '') +
118
+ ' = ' + op.gasCost);
130
119
  if (optionalTraceFile) {
131
- await fs.writeFile(optionalTraceFile, JSON.stringify(result));
120
+ await fs_1.promises.writeFile(optionalTraceFile, JSON.stringify(result));
132
121
  }
133
-
134
122
  return result;
135
123
  }
136
-
137
- module.exports = {
138
- profileEVM,
139
- gasspectEVM,
140
- };
124
+ exports.gasspectEVM = gasspectEVM;
125
+ //# sourceM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AC,CAAC;YAC3C,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;SACzB;QAED,IAAI,EAAE,CAAC,KAAK,GAAG,CAAC,GAAG,YAAY,CAAC,MAAM,EAAE;YACpC,YAAY,CAAC,GAAG,EAAE,CAAC;SACtB;KACJ;IAED,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,OAAO,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG,GAAG,EAAE,CAAC,EAAE;QAChG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;QAC3D,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QACnD,KAAK,GAAG,EAAE,CAAC,OAAO,CAAC,CAAC;IAExC,IAAI,iBAAiB,EAAE;QACnB,MAAM,aAAE,CAAC,SAAS,CAAC,iBAAiB,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;KACjE;IAED,OAAO,MAAM,CAAC;AAClB,CAAC;AA7CD,kCA6CC"}
@@ -0,0 +1,9 @@
1
+ /// <reference types="bn.js" />
2
+ export declare function timeIncreaseTo(seconds: number | string | BN): Promise<void>;
3
+ export interface Token extends Truffle.ContractInstance {
4
+ balanceOf(account: string, txDetails?: Truffle.TransactionDetails): Promise<BN>;
5
+ }
6
+ export declare function trackReceivedTokenAndTx<T extends unknown[], U extends Truffle.AnyEvent>(token: Token, wallet: string, txPromise: (...args: T) => Promise<Truffle.TransactionResponse<U>>, ...args: T): Promise<readonly [import("bn.js"), Truffle.TransactionResponse<U>]>;
7
+ export declare function fixSignature(signature: string): string;
8
+ export declare function signMessage(signer: string, messageHex?: string): Promise<string>;
9
+ export declare function countInstructions(txHash: string, instructions: string[]): Promise<number[]>;
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.countInstructions = exports.signMessage = exports.fixSignature = exports.trackReceivedTokenAndTx = exports.timeIncreaseTo = void 0;
4
+ const util_1 = require("util");
5
+ const prelude_1 = require("./prelude");
6
+ async function timeIncreaseTo(seconds) {
7
+ const delay = 1000 - new Date().getMilliseconds();
8
+ await new Promise(resolve => setTimeout(resolve, delay));
9
+ await prelude_1.time.increaseTo(seconds);
10
+ }
11
+ exports.timeIncreaseTo = timeIncreaseTo;
12
+ async function trackReceivedTokenAndTx(token, wallet, txPromise, ...args) {
13
+ const isETH = token.address === prelude_1.constants.ZERO_ADDRESS || token.address === '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE';
14
+ const preBalance = isETH ? (0, prelude_1.toBN)(await web3.eth.getBalance(wallet)) : await token.balanceOf(wallet);
15
+ const txResult = await txPromise(...args);
16
+ const txFees = (wallet.toLowerCase() === txResult.receipt.from.toLowerCase() && isETH)
17
+ ? (0, prelude_1.toBN)(txResult.receipt.gasUsed).mul((0, prelude_1.toBN)(txResult.receipt.effectiveGasPrice))
18
+ : (0, prelude_1.toBN)('0');
19
+ const postBalance = isETH ? (0, prelude_1.toBN)(await web3.eth.getBalance(wallet)) : await token.balanceOf(wallet);
20
+ return [postBalance.sub(preBalance).add(txFees), txResult];
21
+ }
22
+ exports.trackReceivedTokenAndTx = trackReceivedTokenAndTx;
23
+ function fixSignature(signature) {
24
+ // in geth its always 27/28, in ganache its 0/1. Change to 27/28 to prevent
25
+ // signature malleability if version is 0/1
26
+ // see https://github.com/ethereum/go-ethereum/blob/v1.8.23/internal/ethapi/api.go#L465
27
+ let v = parseInt(signature.slice(130, 132), 16);
28
+ if (v < 27) {
29
+ v += 27;
30
+ }
31
+ const vHex = v.toString(16);
32
+ return signature.slice(0, 130) + vHex;
33
+ }
34
+ exports.fixSignature = fixSignature;
35
+ // signs message in node (ganache auto-applies "Ethereum Signed Message" prefix)
36
+ async function signMessage(signer, messageHex = '0x') {
37
+ return fixSignature(await web3.eth.sign(messageHex, signer));
38
+ }
39
+ exports.signMessage = signMessage;
40
+ async function countInstructions(txHash, instructions) {
41
+ if (!web3.currentProvider || typeof web3.currentProvider === 'string' || !web3.currentProvider.send) {
42
+ throw new Error('Unsupported provider');
43
+ }
44
+ const trace = await (0, util_1.promisify)(web3.currentProvider.send.bind(web3.currentProvider))({
45
+ jsonrpc: '2.0',
46
+ method: 'debug_traceTransaction',
47
+ params: [txHash, {}],
48
+ id: new Date().getTime(),
49
+ });
50
+ const str = JSON.stringify(trace);
51
+ return instructions.map(instr => {
52
+ return str.split('"' + instr.toUpperCase() + '"').length - 1;
53
+ });
54
+ }
55
+ exports.countInstructions = countInstructions;
56
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";;;AAAA,+BAAiC;AACjC,uCAAkD;AAE3C,KAAK,UAAU,cAAc,CAAE,OAA6B;IAC/D,MAAM,KAAK,GAAG,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC,eAAe,EAAE,CAAC;IAClD,MAAM,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC;IACzD,MAAM,cAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;AACnC,CAAC;AAJD,wCAIC;AASM,KAAK,UAAU,uBAAuB,CACzC,KAAY,EACZ,MAAc,EACd,SAAkE,EAClE,GAAG,I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AC,CAAC,CAAC;AACP,CAAC;AAhBD,8CAgBC"}
package/package.json CHANGED
@@ -1,60 +1,87 @@
1
1
  {
2
2
  "name": "@1inch/solidity-utils",
3
- "version": "1.3.0",
4
- "main": "index.js",
3
+ "version": "2.0.3",
4
+ "main": "dist/src/index.js",
5
+ "types": "dist/src/index.d.ts",
5
6
  "repository": {
6
7
  "type": "git",
7
8
  "url": "git+ssh://git@github.com/1inch/solidity-utils.git"
8
9
  },
9
10
  "license": "MIT",
11
+ "scripts": {
12
+ "prebuild": "rimraf ./dist && cti src -b",
13
+ "build": "tsc -p tsconfig.publish.json",
14
+ "postbuild": "echo done",
15
+ "publishPackage": "yarn build && yarn publish",
16
+ "coverage": "hardhat coverage",
17
+ "lint": "yarn run lint:ts && yarn run lint:sol",
18
+ "lint:fix": "yarn run lint:ts:fix && yarn run lint:sol:fix",
19
+ "lint:ts": "eslint . --ext .ts",
20
+ "lint:ts:fix": "eslint . --fix --ext .ts",
21
+ "lint:sol": "solhint --max-warnings 0 \"contracts/**/*.sol\"",
22
+ "lint:sol:fix": "solhint --max-warnings 0 \"contracts/**/*.sol\" --fix",
23
+ "test": "hardhat test",
24
+ "typecheck": "tsc --noEmit --skipLibCheck",
25
+ "typechain": "hardhat typechain"
26
+ },
10
27
  "dependencies": {
11
- "@openzeppelin/contracts": "^4.4.0",
12
- "ethereumjs-wallet": "^1.0.2"
28
+ "@metamask/eth-sig-util": "^4.0.0",
29
+ "@openzeppelin/contracts": "4.5.0",
30
+ "@openzeppelin/test-helpers": "0.5.15",
31
+ "chai": "4.3.6",
32
+ "chai-as-promised": "7.1.1",
33
+ "ethereumjs-wallet": "1.0.2",
34
+ "hardhat": "2.8.4",
35
+ "web3-utils": "1.7.0"
13
36
  },
14
37
  "devDependencies": {
15
- "@nomiclabs/hardhat-etherscan": "^2.1.8",
16
- "@nomiclabs/hardhat-truffle5": "^2.0.0",
17
- "@nomiclabs/hardhat-web3": "^2.0.0",
18
- "@openzeppelin/test-helpers": "^0.5.15",
19
- "chai": "^4.3.4",
20
- "cross-spawn": "^7.0.3",
21
- "dotenv": "^10.0.0",
22
- "eslint": "^8.3.0",
23
- "eslint-config-standard": "^16.0.3",
24
- "eslint-plugin-import": "^2.25.3",
25
- "eslint-plugin-node": "^11.1.0",
26
- "eslint-plugin-promise": "^5.1.1",
27
- "eslint-plugin-standard": "^5.0.0",
28
- "hardhat": "^2.7.0",
29
- "hardhat-deploy": "^0.9.14",
30
- "hardhat-gas-reporter": "^1.0.6",
31
- "rimraf": "^3.0.2",
32
- "shx": "^0.3.3",
33
- "solc": "^0.8.10",
34
- "solhint": "^3.3.6",
35
- "solidity-coverage": "^0.7.17"
38
+ "@nomiclabs/hardhat-etherscan": "3.0.1",
39
+ "@nomiclabs/hardhat-truffle5": "2.0.4",
40
+ "@nomiclabs/hardhat-web3": "2.0.0",
41
+ "@typechain/hardhat": "4.0.0",
42
+ "@typechain/truffle-v5": "7.0.0",
43
+ "@types/chai": "4.3.0",
44
+ "@types/chai-as-promised": "7.1.5",
45
+ "@types/mocha": "9.1.0",
46
+ "@types/node": "17.0.18",
47
+ "@typescript-eslint/eslint-plugin": "5.12.0",
48
+ "@typescript-eslint/parser": "5.12.0",
49
+ "chai-bn": "0.3.1",
50
+ "create-ts-index": "^1.14.0",
51
+ "cross-spawn": "7.0.3",
52
+ "dotenv": "16.0.0",
53
+ "eslint": "8.9.0",
54
+ "eslint-config-standard": "16.0.3",
55
+ "eslint-plugin-import": "2.25.4",
56
+ "eslint-plugin-node": "11.1.0",
57
+ "eslint-plugin-promise": "6.0.0",
58
+ "eslint-plugin-standard": "5.0.0",
59
+ "eslint-plugin-typescript": "0.14.0",
60
+ "hardhat-deploy": "0.10.5",
61
+ "hardhat-gas-reporter": "1.0.8",
62
+ "rimraf": "3.0.2",
63
+ "shx": "0.3.4",
64
+ "solc": "0.8.11",
65
+ "solhint": "3.3.7",
66
+ "solidity-coverage": "0.7.20",
67
+ "ts-node": "10.5.0",
68
+ "typechain": "7.0.0",
69
+ "typescript": "4.5.5"
36
70
  },
37
71
  "bin": {
38
72
  "solidity-utils-docify": "utils/docify.utils.js"
39
73
  },
40
- "scripts": {
41
- "build": "rimraf ./dist && mkdir dist && shx cp -R js ./dist/js && shx cp -R utils ./dist/utils && shx cp package.json ./dist && shx cp README.md ./dist && shx cp -R ./contracts ./dist/contracts && shx rm -rf dist/contracts/mocks dist/contracts/tests",
42
- "coverage": "hardhat coverage",
43
- "lint": "yarn run lint:js && yarn run lint:sol",
44
- "lint:fix": "yarn run lint:js:fix && yarn run lint:sol:fix",
45
- "lint:js": "eslint .",
46
- "lint:js:fix": "eslint . --fix",
47
- "lint:sol": "solhint --max-warnings 0 \"contracts/**/*.sol\"",
48
- "lint:sol:fix": "solhint --max-warnings 0 \"contracts/**/*.sol\" --fix",
49
- "test": "hardhat test"
50
- },
51
74
  "bugs": {
52
75
  "url": "https://github.com/1inch/solidity-utils/issues"
53
76
  },
54
77
  "homepage": "https://github.com/1inch/solidity-utils#readme",
55
- "directories": {
56
- "test": "test"
57
- },
58
78
  "author": "1inch",
59
- "description": "Solidity and JS utils"
79
+ "description": "Solidity and TS utils",
80
+ "files": [
81
+ "./dist",
82
+ "./*.MD",
83
+ "contracts/*.sol",
84
+ "contracts/interfaces",
85
+ "contracts/libraries"
86
+ ]
60
87
  }
package/js/asserts.js DELETED
@@ -1,34 +0,0 @@
1
- const { expect } = require('chai');
2
- const { BN } = require('@openzeppelin/test-helpers');
3
-
4
- async function assertThrowsAsync (action, msg) {
5
- try {
6
- await action();
7
- } catch (e) {
8
- expect(e.message).to.contain(msg);
9
- return;
10
- }
11
- throw new Error('Should have thrown an error but didn\'t');
12
- }
13
-
14
- function assertRoughlyEqualValues (expected, actual, relativeDiff) {
15
- const expectedBN = new BN(expected);
16
- const actualBN = new BN(actual);
17
-
18
- let multiplerNumerator = relativeDiff;
19
- let multiplerDenominator = new BN('1');
20
- while (!Number.isInteger(multiplerNumerator)) {
21
- multiplerDenominator = multiplerDenominator.mul(new BN('10'));
22
- multiplerNumerator *= 10;
23
- }
24
- const diff = expectedBN.sub(actualBN).abs();
25
- const treshold = expectedBN.mul(new BN(multiplerNumerator.toString())).div(multiplerDenominator);
26
- if (!diff.lte(treshold)) {
27
- expect(actualBN).to.be.bignumber.equal(expectedBN, `${actualBN} != ${expectedBN} with ${relativeDiff} precision`);
28
- }
29
- }
30
-
31
- module.exports = {
32
- assertThrowsAsync,
33
- assertRoughlyEqualValues,
34
- };
package/js/permit.js DELETED
@@ -1,111 +0,0 @@
1
- const { constants } = require('@openzeppelin/test-helpers');
2
- const ethSigUtil = require('eth-sig-util');
3
- const { fromRpcSig } = require('ethereumjs-util');
4
-
5
- const defaultDeadline = constants.MAX_UINT256;
6
-
7
- const EIP712Domain = [
8
- { name: 'name', type: 'string' },
9
- { name: 'version', type: 'string' },
10
- { name: 'chainId', type: 'uint256' },
11
- { name: 'verifyingContract', type: 'address' },
12
- ];
13
-
14
- const Permit = [
15
- { name: 'owner', type: 'address' },
16
- { name: 'spender', type: 'address' },
17
- { name: 'value', type: 'uint256' },
18
- { name: 'nonce', type: 'uint256' },
19
- { name: 'deadline', type: 'uint256' },
20
- ];
21
-
22
- const DaiLikePermit = [
23
- { name: 'holder', type: 'address' },
24
- { name: 'spender', type: 'address' },
25
- { name: 'nonce', type: 'uint256' },
26
- { name: 'expiry', type: 'uint256' },
27
- { name: 'allowed', type: 'bool' },
28
- ];
29
-
30
- function trim0x (bigNumber) {
31
- const s = bigNumber.toString();
32
- if (s.startsWith('0x')) {
33
- return s.substring(2);
34
- }
35
- return s;
36
- }
37
-
38
- function cutSelector (data) {
39
- const hexPrefix = '0x';
40
- return hexPrefix + data.substr(hexPrefix.length + 8);
41
- }
42
-
43
- function domainSeparator (name, version, chainId, verifyingContract) {
44
- return '0x' + ethSigUtil.TypedDataUtils.hashStruct(
45
- 'EIP712Domain',
46
- { name, version, chainId, verifyingContract },
47
- { EIP712Domain },
48
- ).toString('hex');
49
- }
50
-
51
- function buildData (name, version, chainId, verifyingContract, owner, spender, value, nonce, deadline = defaultDeadline) {
52
- return {
53
- primaryType: 'Permit',
54
- types: { EIP712Domain, Permit },
55
- domain: { name, version, chainId, verifyingContract },
56
- message: { owner, spender, value, nonce, deadline },
57
- };
58
- }
59
-
60
- function buildDataLikeDai (name, version, chainId, verifyingContract, holder, spender, nonce, allowed, expiry = defaultDeadline) {
61
- return {
62
- primaryType: 'Permit',
63
- types: { EIP712Domain, Permit: DaiLikePermit },
64
- domain: { name, version, chainId, verifyingContract },
65
- message: { holder, spender, nonce, expiry, allowed },
66
- };
67
- }
68
-
69
- /*
70
- * @param permitContract The contract object with ERC20Permit type and token address for which the permit creating.
71
- */
72
- async function getPermit (owner, ownerPrivateKey, permitContract, tokenVersion, chainId, spender, value, deadline = defaultDeadline) {
73
- const nonce = await permitContract.nonces(owner);
74
- const name = await permitContract.name();
75
- const data = buildData(name, tokenVersion, chainId, permitContract.address, owner, spender, value, nonce, deadline);
76
- const signature = ethSigUtil.signTypedMessage(Buffer.from(trim0x(ownerPrivateKey), 'hex'), { data });
77
- const { v, r, s } = fromRpcSig(signature);
78
- const permitCall = permitContract.contract.methods.permit(owner, spender, value, deadline, v, r, s).encodeABI();
79
- return cutSelector(permitCall);
80
- }
81
-
82
- /*
83
- * @param permitContract The contract object with ERC20PermitLikeDai type and token address for which the permit creating.
84
- */
85
- async function getPermitLikeDai (holder, holderPrivateKey, permitContract, tokenVersion, chainId, spender, allowed, expiry = defaultDeadline) {
86
- const nonce = await permitContract.nonces(holder);
87
- const name = await permitContract.name();
88
- const data = buildDataLikeDai(name, tokenVersion, chainId, permitContract.address, holder, spender, nonce, allowed, expiry);
89
- const signature = ethSigUtil.signTypedMessage(Buffer.from(trim0x(holderPrivateKey), 'hex'), { data });
90
- const { v, r, s } = fromRpcSig(signature);
91
- const permitCall = permitContract.contract.methods.permit(holder, spender, nonce, expiry, allowed, v, r, s).encodeABI();
92
- return cutSelector(permitCall);
93
- }
94
-
95
- function withTarget (target, data) {
96
- return target.toString() + trim0x(data);
97
- }
98
-
99
- module.exports = {
100
- defaultDeadline,
101
- EIP712Domain,
102
- Permit,
103
- DaiLikePermit,
104
- trim0x,
105
- domainSeparator,
106
- buildData,
107
- buildDataLikeDai,
108
- getPermit,
109
- getPermitLikeDai,
110
- withTarget,
111
- };
package/js/utils.js DELETED
@@ -1,68 +0,0 @@
1
- const { constants, time } = require('@openzeppelin/test-helpers');
2
- const { promisify } = require('util');
3
-
4
- async function timeIncreaseTo (seconds) {
5
- const delay = 1000 - new Date().getMilliseconds();
6
- await new Promise(resolve => setTimeout(resolve, delay));
7
- await time.increaseTo(seconds);
8
- }
9
-
10
- async function trackReceivedToken (token, wallet, txPromise, ...args) {
11
- return (await trackReceivedTokenAndTx(token, wallet, txPromise, ...args))[0];
12
- }
13
-
14
- async function trackReceivedTokenAndTx (token, wallet, txPromise, ...args) {
15
- const isETH = token.address === constants.ZERO_ADDRESS || token.address === '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE';
16
- const preBalance = web3.utils.toBN(isETH ? await web3.eth.getBalance(wallet) : await token.balanceOf(wallet));
17
- const txResult = await txPromise(...args);
18
- const txFees = (wallet.toLowerCase() === txResult.receipt.from.toLowerCase() && isETH)
19
- ? web3.utils.toBN(txResult.receipt.gasUsed).mul(web3.utils.toBN(txResult.receipt.effectiveGasPrice))
20
- : web3.utils.toBN('0');
21
- const postBalance = web3.utils.toBN(isETH ? await web3.eth.getBalance(wallet) : await token.balanceOf(wallet));
22
- return [postBalance.sub(preBalance).add(txFees), txResult];
23
- }
24
-
25
- function fixSignature (signature) {
26
- // in geth its always 27/28, in ganache its 0/1. Change to 27/28 to prevent
27
- // signature malleability if version is 0/1
28
- // see https://github.com/ethereum/go-ethereum/blob/v1.8.23/internal/ethapi/api.go#L465
29
- let v = parseInt(signature.slice(130, 132), 16);
30
- if (v < 27) {
31
- v += 27;
32
- }
33
- const vHex = v.toString(16);
34
- return signature.slice(0, 130) + vHex;
35
- }
36
-
37
- // signs message in node (ganache auto-applies "Ethereum Signed Message" prefix)
38
- async function signMessage (signer, messageHex = '0x') {
39
- return fixSignature(await web3.eth.sign(messageHex, signer));
40
- }
41
-
42
- async function countInstructions (txHash, instruction) {
43
- const trace = await promisify(web3.currentProvider.send.bind(web3.currentProvider))({
44
- jsonrpc: '2.0',
45
- method: 'debug_traceTransaction',
46
- params: [txHash, {}],
47
- id: new Date().getTime(),
48
- });
49
-
50
- const str = JSON.stringify(trace);
51
-
52
- if (Array.isArray(instruction)) {
53
- return instruction.map(instr => {
54
- return str.split('"' + instr.toUpperCase() + '"').length - 1;
55
- });
56
- }
57
-
58
- return str.split('"' + instruction.toUpperCase() + '"').length - 1;
59
- }
60
-
61
- module.exports = {
62
- timeIncreaseTo,
63
- trackReceivedToken,
64
- trackReceivedTokenAndTx,
65
- fixSignature,
66
- signMessage,
67
- countInstructions,
68
- };
@@ -1,69 +0,0 @@
1
- # {{{name}}}
2
-
3
-
4
- {{{natspec.title}}}
5
- {{{natspec.userdoc}}}
6
- {{{natspec.devdoc}}}
7
-
8
- {{#if (withoutFirstElement inheritance)}}
9
- ## Derives
10
- {{/if}}
11
- {{#each (withoutFirstElement inheritance)}}
12
- {{#if (getRelativeDocPath name source.contractsDir source.solcOutput.sources)}}
13
- - [{{name}}]({{getRelativeDocPath name source.contractsDir source.solcOutput.sources}})
14
- {{else}}
15
- - {{name}}
16
- {{/if}}
17
- {{/each}}
18
-
19
- {{#if ownFunctions}}
20
- ## Functions
21
- {{/if}}
22
- {{#ownFunctions}}
23
- ### {{name}}
24
- ```solidity
25
- function {{name}}(
26
- {{#args}}
27
- {{type}} {{name}}{{#if @last}}{{else}},{{/if}}
28
- {{/args}}
29
- ) {{visibility}}{{#if outputs}} returns ({{outputs}}){{/if}}
30
- ```
31
- {{#if natspec.userdoc}}{{natspec.userdoc}}{{/if}}
32
- {{#if natspec.devdoc}}{{natspec.devdoc}}{{/if}}
33
- {{#if args}}
34
- #### Parameters:
35
- | Name | Type | Description |
36
- | :--- | :--- | :------------------------------------------------------------------- |
37
- {{#args}}
38
- |`{{name}}` | {{type}} | {{#with (lookup ../natspec.params @index)~}} {{ removeNewlines description }} {{/with}}
39
- {{/args}}{{/if}}
40
- {{#if natspec.returns}}
41
- #### Return Values:
42
- | Name | Type | Description |
43
- | :----------------------------- | :------------ | :--------------------------------------------------------------------------- |
44
- {{#natspec.returns}}
45
- |`{{param}}`| {{#lookup ../outputs.types @index}}{{/lookup}} | {{{removeNewlines description}}}
46
- {{/natspec.returns}}{{/if}}
47
- {{/ownFunctions}}
48
- {{#if ownEvents}}
49
- ## Events
50
- {{/if}}
51
- {{#ownEvents}}
52
- ### {{name}}
53
- ```solidity
54
- event {{name}}(
55
- {{#args}}
56
- {{type}} {{name}}{{#if @last}}{{else}},{{/if}}
57
- {{/args}}
58
- )
59
- ```
60
- {{#if natspec.userdoc}}{{natspec.userdoc}}{{/if}}
61
- {{#if natspec.devdoc}}{{natspec.devdoc}}{{/if}}
62
- {{#if args}}
63
- #### Parameters:
64
- | Name | Type | Description |
65
- | :--- | :--- | :------------------------------------------------------------------- |
66
- {{#args}}
67
- |`{{name}}` | {{type}} | {{#with (lookup ../natspec.params @index)~}} {{ removeNewlines description }} {{/with}}
68
- {{/args}}{{/if}}
69
- {{/ownEvents}}
@@ -1,127 +0,0 @@
1
- #!/usr/bin/env node
2
- const SOLC_NPM_NAME = 'solc';
3
- const BASE_DIR = 'docgen';
4
- const SCRIPT_DIR = __dirname;
5
- const INPUT_DIR = 'contracts';
6
- const OUTPUT_DIR = `${BASE_DIR}/docs`;
7
- const HELPERS_PATH = `${SCRIPT_DIR}/solidity-docgen-helpers.js`;
8
-
9
- const fs = require('fs');
10
- const path = require('path');
11
- const spawn = require('cross-spawn');
12
-
13
- function getFileNameWithoutExtension (fileName) {
14
- return fileName.substr(0, fileName.lastIndexOf('.'));
15
- }
16
-
17
- function runProcess (name, args) {
18
- console.log(`running ${name} with args ${JSON.stringify(args)}`);
19
- const result = spawn.sync(name, args, { stdio: ['inherit', 'inherit', 'pipe'] });
20
- if (result.stderr.length > 0) {
21
- throw new Error(result.stderr);
22
- }
23
- }
24
-
25
- function getReadmes (targetPath) {
26
- let result = [];
27
- const readmePath = path.join(targetPath, 'README.md');
28
- if (!fs.existsSync(readmePath)) {
29
- const content = `# ${path.basename(targetPath)}\n`;
30
- result.push({ path: readmePath, content });
31
- }
32
- const childDirs = fs.readdirSync(targetPath, { withFileTypes: true }).filter(item => item.isDirectory());
33
- for (const dir of childDirs) {
34
- result = result.concat(getReadmes(path.join(targetPath, dir.name)));
35
- }
36
- return result;
37
- }
38
-
39
- function generateReadmes (readmes) {
40
- for (const readme of readmes) {
41
- fs.writeFileSync(readme.path, readme.content);
42
- }
43
- }
44
-
45
- function getSummary (targetPath) {
46
- function getSummaryRoot (summaryTargetPath, indentation) {
47
- function specialCaseRoot (item) {
48
- if (item.indentation >= 0) {
49
- return item;
50
- }
51
- return ({
52
- name: 'Main Readme',
53
- path: item.path,
54
- indentation: 0,
55
- });
56
- }
57
-
58
- const items = fs.readdirSync(summaryTargetPath, { withFileTypes: true });
59
- let result = [specialCaseRoot({
60
- name: path.basename(summaryTargetPath),
61
- path: path.relative(targetPath, path.join(summaryTargetPath, 'README.md')).replaceAll('\\', '/'),
62
- indentation: indentation - 1,
63
- })];
64
- for (const dir of items.filter(item => item.isDirectory())) {
65
- result = result.concat(getSummaryRoot(path.join(summaryTargetPath, dir.name), indentation + 1));
66
- }
67
- result = result
68
- .concat(items
69
- .filter(item => !item.isDirectory() &&
70
- !item.name.endsWith('README.md') &&
71
- !item.name.endsWith('SUMMARY.md'))
72
- .map(file => ({
73
- name: getFileNameWithoutExtension(file.name),
74
- path: path.relative(targetPath, path.join(summaryTargetPath, file.name)).replaceAll('\\', '/'),
75
- indentation,
76
- })));
77
- return result;
78
- }
79
-
80
- function generateContent (summaryTree) {
81
- const lines = summaryTree.map(x => `${'\t'.repeat(x.indentation)}* [${x.name}](${x.path})`).join('\n');
82
- return `# Table of contents\n\n${lines}`;
83
- }
84
-
85
- return generateContent(getSummaryRoot(targetPath, 0));
86
- }
87
-
88
- function generateSummary (targetPath, summary) {
89
- fs.writeFileSync(path.join(targetPath, 'SUMMARY.md'), summary);
90
- }
91
-
92
- function generateGitbookFiles () {
93
- fs.copyFileSync(path.join(BASE_DIR, 'README.md'), path.join(OUTPUT_DIR, 'README.md'));
94
- const readmesToGenerate = getReadmes(OUTPUT_DIR);
95
- const summary = getSummary(OUTPUT_DIR);
96
-
97
- generateReadmes(readmesToGenerate);
98
- generateSummary(OUTPUT_DIR, summary);
99
- }
100
-
101
- function removeUnwantedDocs () {
102
- const unwantedDirs = ['mocks', 'tests'];
103
- for (const unwantedDir of unwantedDirs) {
104
- fs.rmSync(path.join(OUTPUT_DIR, unwantedDir), { force: true, recursive: true });
105
- }
106
- }
107
-
108
- const solidityDocgenArgs = [
109
- 'solidity-docgen',
110
- '-i',
111
- INPUT_DIR,
112
- '-o',
113
- OUTPUT_DIR,
114
- '--solc-module',
115
- SOLC_NPM_NAME,
116
- '--solc-settings',
117
- JSON.stringify({ optimizer: { enabled: false } }),
118
- '--templates',
119
- SCRIPT_DIR,
120
- '--helpers',
121
- HELPERS_PATH,
122
- ];
123
-
124
- fs.rmSync(OUTPUT_DIR, { force: true, recursive: true });
125
- runProcess('npx', solidityDocgenArgs);
126
- generateGitbookFiles();
127
- removeUnwantedDocs();
@@ -1,24 +0,0 @@
1
- module.exports = {
2
- removeNewlines (str) {
3
- return str.replace(/\r?\n/g, ' ');
4
- },
5
- withoutFirstElement (arr) {
6
- return arr.splice(1);
7
- },
8
- getRelativeDocPath (contractName, contractsDir, sources) {
9
- function getRelativePath (contractPath) {
10
- if (contractPath.startsWith(contractsDir)) {
11
- return contractPath.substr(contractsDir.length + 1).replace('.sol', '.md');
12
- }
13
- if (contractPath.startsWith('@openzeppelin')) {
14
- const regexMatch = contractPath.match(/@openzeppelin\/contracts\/(.+)\/([^/]+)\.sol/);
15
- return `https://docs.openzeppelin.com/contracts/3.x/api/${regexMatch[1]}#${regexMatch[2]}`;
16
- }
17
- return null;
18
- }
19
-
20
- const sourcesKeys = Object.keys(sources);
21
- const contractPath = sourcesKeys.find(x => x.includes(contractName));
22
- return getRelativePath(contractPath);
23
- },
24
- };