From b9bc58ef100b0ef3b762d3c8df77c5abc48a120b Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Mon, 4 Jun 2018 20:53:48 +0100 Subject: Add missing exports to order-utils and add CHANGELOG entry --- packages/order-utils/src/index.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/index.ts b/packages/order-utils/src/index.ts index b844fbfcb..cb859dcb9 100644 --- a/packages/order-utils/src/index.ts +++ b/packages/order-utils/src/index.ts @@ -1,5 +1,13 @@ export { orderHashUtils } from './order_hash'; -export { isValidSignatureAsync, ecSignOrderHashAsync, addSignedMessagePrefix } from './signature_utils'; +export { + isValidSignatureAsync, + isValidPresignedSignatureAsync, + isValidWalletSignatureAsync, + isValidValidatorSignatureAsync, + isValidECSignature, + ecSignOrderHashAsync, + addSignedMessagePrefix, +} from './signature_utils'; export { orderFactory } from './order_factory'; export { constants } from './constants'; export { crypto } from './crypto'; -- cgit v1.2.3 From 321c0a85370089b6a72dc8b83728521cbd0dffe9 Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Mon, 4 Jun 2018 20:54:04 +0100 Subject: Remove unused compact artifacts from order-utils --- .../src/compact_artifacts/DummyToken.json | 22 - .../src/compact_artifacts/EtherToken.json | 287 ---------- .../src/compact_artifacts/Exchange.json | 610 --------------------- .../order-utils/src/compact_artifacts/Token.json | 172 ------ .../src/compact_artifacts/TokenRegistry.json | 547 ------------------ .../src/compact_artifacts/TokenTransferProxy.json | 187 ------- .../order-utils/src/compact_artifacts/ZRX.json | 20 - 7 files changed, 1845 deletions(-) delete mode 100644 packages/order-utils/src/compact_artifacts/DummyToken.json delete mode 100644 packages/order-utils/src/compact_artifacts/EtherToken.json delete mode 100644 packages/order-utils/src/compact_artifacts/Exchange.json delete mode 100644 packages/order-utils/src/compact_artifacts/Token.json delete mode 100644 packages/order-utils/src/compact_artifacts/TokenRegistry.json delete mode 100644 packages/order-utils/src/compact_artifacts/TokenTransferProxy.json delete mode 100644 packages/order-utils/src/compact_artifacts/ZRX.json (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/compact_artifacts/DummyToken.json b/packages/order-utils/src/compact_artifacts/DummyToken.json deleted file mode 100644 index f64a8cd3d..000000000 --- a/packages/order-utils/src/compact_artifacts/DummyToken.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "contract_name": "DummyToken", - "abi": [ - { - "constant": false, - "inputs": [ - { - "name": "_target", - "type": "address" - }, - { - "name": "_value", - "type": "uint256" - } - ], - "name": "setBalance", - "outputs": [], - "payable": false, - "type": "function" - } - ] -} diff --git a/packages/order-utils/src/compact_artifacts/EtherToken.json b/packages/order-utils/src/compact_artifacts/EtherToken.json deleted file mode 100644 index 26cca57cd..000000000 --- a/packages/order-utils/src/compact_artifacts/EtherToken.json +++ /dev/null @@ -1,287 +0,0 @@ -{ - "contract_name": "EtherToken", - "abi": [ - { - "constant": true, - "inputs": [], - "name": "name", - "outputs": [ - { - "name": "", - "type": "string" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "_spender", - "type": "address" - }, - { - "name": "_value", - "type": "uint256" - } - ], - "name": "approve", - "outputs": [ - { - "name": "", - "type": "bool" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "totalSupply", - "outputs": [ - { - "name": "", - "type": "uint256" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "_from", - "type": "address" - }, - { - "name": "_to", - "type": "address" - }, - { - "name": "_value", - "type": "uint256" - } - ], - "name": "transferFrom", - "outputs": [ - { - "name": "", - "type": "bool" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "amount", - "type": "uint256" - } - ], - "name": "withdraw", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "decimals", - "outputs": [ - { - "name": "", - "type": "uint8" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "_owner", - "type": "address" - } - ], - "name": "balanceOf", - "outputs": [ - { - "name": "", - "type": "uint256" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "symbol", - "outputs": [ - { - "name": "", - "type": "string" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "_to", - "type": "address" - }, - { - "name": "_value", - "type": "uint256" - } - ], - "name": "transfer", - "outputs": [ - { - "name": "", - "type": "bool" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [], - "name": "deposit", - "outputs": [], - "payable": true, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "_owner", - "type": "address" - }, - { - "name": "_spender", - "type": "address" - } - ], - "name": "allowance", - "outputs": [ - { - "name": "", - "type": "uint256" - } - ], - "payable": false, - "type": "function" - }, - { - "payable": true, - "type": "fallback" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "_from", - "type": "address" - }, - { - "indexed": true, - "name": "_to", - "type": "address" - }, - { - "indexed": false, - "name": "_value", - "type": "uint256" - } - ], - "name": "Transfer", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "_owner", - "type": "address" - }, - { - "indexed": true, - "name": "_spender", - "type": "address" - }, - { - "indexed": false, - "name": "_value", - "type": "uint256" - } - ], - "name": "Approval", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "_owner", - "type": "address" - }, - { - "indexed": false, - "name": "_value", - "type": "uint256" - } - ], - "name": "Deposit", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "_owner", - "type": "address" - }, - { - "indexed": false, - "name": "_value", - "type": "uint256" - } - ], - "name": "Withdrawal", - "type": "event" - } - ], - "networks": { - "1": { - "address": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" - }, - "3": { - "address": "0xc00fd9820cd2898cc4c054b7bf142de637ad129a" - }, - "4": { - "address": "0xc778417e063141139fce010982780140aa0cd5ab" - }, - "42": { - "address": "0x653e49e301e508a13237c0ddc98ae7d4cd2667a1" - }, - "50": { - "address": "0x871dd7c2b4b25e1aa18728e9d5f2af4c4e431f5c" - } - } -} diff --git a/packages/order-utils/src/compact_artifacts/Exchange.json b/packages/order-utils/src/compact_artifacts/Exchange.json deleted file mode 100644 index af8db7360..000000000 --- a/packages/order-utils/src/compact_artifacts/Exchange.json +++ /dev/null @@ -1,610 +0,0 @@ -{ - "contract_name": "Exchange", - "abi": [ - { - "constant": true, - "inputs": [ - { - "name": "numerator", - "type": "uint256" - }, - { - "name": "denominator", - "type": "uint256" - }, - { - "name": "target", - "type": "uint256" - } - ], - "name": "isRoundingError", - "outputs": [ - { - "name": "", - "type": "bool" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "", - "type": "bytes32" - } - ], - "name": "filled", - "outputs": [ - { - "name": "", - "type": "uint256" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "", - "type": "bytes32" - } - ], - "name": "cancelled", - "outputs": [ - { - "name": "", - "type": "uint256" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "orderAddresses", - "type": "address[5][]" - }, - { - "name": "orderValues", - "type": "uint256[6][]" - }, - { - "name": "fillTakerTokenAmount", - "type": "uint256" - }, - { - "name": "shouldThrowOnInsufficientBalanceOrAllowance", - "type": "bool" - }, - { - "name": "v", - "type": "uint8[]" - }, - { - "name": "r", - "type": "bytes32[]" - }, - { - "name": "s", - "type": "bytes32[]" - } - ], - "name": "fillOrdersUpTo", - "outputs": [ - { - "name": "", - "type": "uint256" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "orderAddresses", - "type": "address[5]" - }, - { - "name": "orderValues", - "type": "uint256[6]" - }, - { - "name": "cancelTakerTokenAmount", - "type": "uint256" - } - ], - "name": "cancelOrder", - "outputs": [ - { - "name": "", - "type": "uint256" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "ZRX_TOKEN_CONTRACT", - "outputs": [ - { - "name": "", - "type": "address" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "orderAddresses", - "type": "address[5][]" - }, - { - "name": "orderValues", - "type": "uint256[6][]" - }, - { - "name": "fillTakerTokenAmounts", - "type": "uint256[]" - }, - { - "name": "v", - "type": "uint8[]" - }, - { - "name": "r", - "type": "bytes32[]" - }, - { - "name": "s", - "type": "bytes32[]" - } - ], - "name": "batchFillOrKillOrders", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "orderAddresses", - "type": "address[5]" - }, - { - "name": "orderValues", - "type": "uint256[6]" - }, - { - "name": "fillTakerTokenAmount", - "type": "uint256" - }, - { - "name": "v", - "type": "uint8" - }, - { - "name": "r", - "type": "bytes32" - }, - { - "name": "s", - "type": "bytes32" - } - ], - "name": "fillOrKillOrder", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "orderHash", - "type": "bytes32" - } - ], - "name": "getUnavailableTakerTokenAmount", - "outputs": [ - { - "name": "", - "type": "uint256" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "signer", - "type": "address" - }, - { - "name": "hash", - "type": "bytes32" - }, - { - "name": "v", - "type": "uint8" - }, - { - "name": "r", - "type": "bytes32" - }, - { - "name": "s", - "type": "bytes32" - } - ], - "name": "isValidSignature", - "outputs": [ - { - "name": "", - "type": "bool" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "numerator", - "type": "uint256" - }, - { - "name": "denominator", - "type": "uint256" - }, - { - "name": "target", - "type": "uint256" - } - ], - "name": "getPartialAmount", - "outputs": [ - { - "name": "", - "type": "uint256" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "TOKEN_TRANSFER_PROXY_CONTRACT", - "outputs": [ - { - "name": "", - "type": "address" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "orderAddresses", - "type": "address[5][]" - }, - { - "name": "orderValues", - "type": "uint256[6][]" - }, - { - "name": "fillTakerTokenAmounts", - "type": "uint256[]" - }, - { - "name": "shouldThrowOnInsufficientBalanceOrAllowance", - "type": "bool" - }, - { - "name": "v", - "type": "uint8[]" - }, - { - "name": "r", - "type": "bytes32[]" - }, - { - "name": "s", - "type": "bytes32[]" - } - ], - "name": "batchFillOrders", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "orderAddresses", - "type": "address[5][]" - }, - { - "name": "orderValues", - "type": "uint256[6][]" - }, - { - "name": "cancelTakerTokenAmounts", - "type": "uint256[]" - } - ], - "name": "batchCancelOrders", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "orderAddresses", - "type": "address[5]" - }, - { - "name": "orderValues", - "type": "uint256[6]" - }, - { - "name": "fillTakerTokenAmount", - "type": "uint256" - }, - { - "name": "shouldThrowOnInsufficientBalanceOrAllowance", - "type": "bool" - }, - { - "name": "v", - "type": "uint8" - }, - { - "name": "r", - "type": "bytes32" - }, - { - "name": "s", - "type": "bytes32" - } - ], - "name": "fillOrder", - "outputs": [ - { - "name": "filledTakerTokenAmount", - "type": "uint256" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "orderAddresses", - "type": "address[5]" - }, - { - "name": "orderValues", - "type": "uint256[6]" - } - ], - "name": "getOrderHash", - "outputs": [ - { - "name": "", - "type": "bytes32" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "EXTERNAL_QUERY_GAS_LIMIT", - "outputs": [ - { - "name": "", - "type": "uint16" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "VERSION", - "outputs": [ - { - "name": "", - "type": "string" - } - ], - "payable": false, - "type": "function" - }, - { - "inputs": [ - { - "name": "_zrxToken", - "type": "address" - }, - { - "name": "_tokenTransferProxy", - "type": "address" - } - ], - "payable": false, - "type": "constructor" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "maker", - "type": "address" - }, - { - "indexed": false, - "name": "taker", - "type": "address" - }, - { - "indexed": true, - "name": "feeRecipient", - "type": "address" - }, - { - "indexed": false, - "name": "makerToken", - "type": "address" - }, - { - "indexed": false, - "name": "takerToken", - "type": "address" - }, - { - "indexed": false, - "name": "filledMakerTokenAmount", - "type": "uint256" - }, - { - "indexed": false, - "name": "filledTakerTokenAmount", - "type": "uint256" - }, - { - "indexed": false, - "name": "paidMakerFee", - "type": "uint256" - }, - { - "indexed": false, - "name": "paidTakerFee", - "type": "uint256" - }, - { - "indexed": true, - "name": "tokens", - "type": "bytes32" - }, - { - "indexed": false, - "name": "orderHash", - "type": "bytes32" - } - ], - "name": "LogFill", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "maker", - "type": "address" - }, - { - "indexed": true, - "name": "feeRecipient", - "type": "address" - }, - { - "indexed": false, - "name": "makerToken", - "type": "address" - }, - { - "indexed": false, - "name": "takerToken", - "type": "address" - }, - { - "indexed": false, - "name": "cancelledMakerTokenAmount", - "type": "uint256" - }, - { - "indexed": false, - "name": "cancelledTakerTokenAmount", - "type": "uint256" - }, - { - "indexed": true, - "name": "tokens", - "type": "bytes32" - }, - { - "indexed": false, - "name": "orderHash", - "type": "bytes32" - } - ], - "name": "LogCancel", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "errorId", - "type": "uint8" - }, - { - "indexed": true, - "name": "orderHash", - "type": "bytes32" - } - ], - "name": "LogError", - "type": "event" - } - ], - "networks": { - "1": { - "address": "0x12459c951127e0c374ff9105dda097662a027093" - }, - "3": { - "address": "0x479cc461fecd078f766ecc58533d6f69580cf3ac" - }, - "4": { - "address": "0x1d16ef40fac01cec8adac2ac49427b9384192c05" - }, - "42": { - "address": "0x90fe2af704b34e0224bf2299c838e04d4dcf1364" - }, - "50": { - "address": "0x48bacb9266a570d521063ef5dd96e61686dbe788" - } - } -} diff --git a/packages/order-utils/src/compact_artifacts/Token.json b/packages/order-utils/src/compact_artifacts/Token.json deleted file mode 100644 index 3b5a86ae0..000000000 --- a/packages/order-utils/src/compact_artifacts/Token.json +++ /dev/null @@ -1,172 +0,0 @@ -{ - "contract_name": "Token", - "abi": [ - { - "constant": false, - "inputs": [ - { - "name": "_spender", - "type": "address" - }, - { - "name": "_value", - "type": "uint256" - } - ], - "name": "approve", - "outputs": [ - { - "name": "success", - "type": "bool" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "totalSupply", - "outputs": [ - { - "name": "supply", - "type": "uint256" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "_from", - "type": "address" - }, - { - "name": "_to", - "type": "address" - }, - { - "name": "_value", - "type": "uint256" - } - ], - "name": "transferFrom", - "outputs": [ - { - "name": "success", - "type": "bool" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "_owner", - "type": "address" - } - ], - "name": "balanceOf", - "outputs": [ - { - "name": "balance", - "type": "uint256" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "_to", - "type": "address" - }, - { - "name": "_value", - "type": "uint256" - } - ], - "name": "transfer", - "outputs": [ - { - "name": "success", - "type": "bool" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "_owner", - "type": "address" - }, - { - "name": "_spender", - "type": "address" - } - ], - "name": "allowance", - "outputs": [ - { - "name": "remaining", - "type": "uint256" - } - ], - "payable": false, - "type": "function" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "_from", - "type": "address" - }, - { - "indexed": true, - "name": "_to", - "type": "address" - }, - { - "indexed": false, - "name": "_value", - "type": "uint256" - } - ], - "name": "Transfer", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "_owner", - "type": "address" - }, - { - "indexed": true, - "name": "_spender", - "type": "address" - }, - { - "indexed": false, - "name": "_value", - "type": "uint256" - } - ], - "name": "Approval", - "type": "event" - } - ] -} diff --git a/packages/order-utils/src/compact_artifacts/TokenRegistry.json b/packages/order-utils/src/compact_artifacts/TokenRegistry.json deleted file mode 100644 index 0f583628c..000000000 --- a/packages/order-utils/src/compact_artifacts/TokenRegistry.json +++ /dev/null @@ -1,547 +0,0 @@ -{ - "contract_name": "TokenRegistry", - "abi": [ - { - "constant": false, - "inputs": [ - { - "name": "_token", - "type": "address" - }, - { - "name": "_index", - "type": "uint256" - } - ], - "name": "removeToken", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "_name", - "type": "string" - } - ], - "name": "getTokenAddressByName", - "outputs": [ - { - "name": "", - "type": "address" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "_symbol", - "type": "string" - } - ], - "name": "getTokenAddressBySymbol", - "outputs": [ - { - "name": "", - "type": "address" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "_token", - "type": "address" - }, - { - "name": "_swarmHash", - "type": "bytes" - } - ], - "name": "setTokenSwarmHash", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "_token", - "type": "address" - } - ], - "name": "getTokenMetaData", - "outputs": [ - { - "name": "", - "type": "address" - }, - { - "name": "", - "type": "string" - }, - { - "name": "", - "type": "string" - }, - { - "name": "", - "type": "uint8" - }, - { - "name": "", - "type": "bytes" - }, - { - "name": "", - "type": "bytes" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "owner", - "outputs": [ - { - "name": "", - "type": "address" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "_token", - "type": "address" - }, - { - "name": "_name", - "type": "string" - }, - { - "name": "_symbol", - "type": "string" - }, - { - "name": "_decimals", - "type": "uint8" - }, - { - "name": "_ipfsHash", - "type": "bytes" - }, - { - "name": "_swarmHash", - "type": "bytes" - } - ], - "name": "addToken", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "_token", - "type": "address" - }, - { - "name": "_name", - "type": "string" - } - ], - "name": "setTokenName", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "", - "type": "address" - } - ], - "name": "tokens", - "outputs": [ - { - "name": "token", - "type": "address" - }, - { - "name": "name", - "type": "string" - }, - { - "name": "symbol", - "type": "string" - }, - { - "name": "decimals", - "type": "uint8" - }, - { - "name": "ipfsHash", - "type": "bytes" - }, - { - "name": "swarmHash", - "type": "bytes" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "", - "type": "uint256" - } - ], - "name": "tokenAddresses", - "outputs": [ - { - "name": "", - "type": "address" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "_name", - "type": "string" - } - ], - "name": "getTokenByName", - "outputs": [ - { - "name": "", - "type": "address" - }, - { - "name": "", - "type": "string" - }, - { - "name": "", - "type": "string" - }, - { - "name": "", - "type": "uint8" - }, - { - "name": "", - "type": "bytes" - }, - { - "name": "", - "type": "bytes" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "getTokenAddresses", - "outputs": [ - { - "name": "", - "type": "address[]" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "_token", - "type": "address" - }, - { - "name": "_ipfsHash", - "type": "bytes" - } - ], - "name": "setTokenIpfsHash", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "_symbol", - "type": "string" - } - ], - "name": "getTokenBySymbol", - "outputs": [ - { - "name": "", - "type": "address" - }, - { - "name": "", - "type": "string" - }, - { - "name": "", - "type": "string" - }, - { - "name": "", - "type": "uint8" - }, - { - "name": "", - "type": "bytes" - }, - { - "name": "", - "type": "bytes" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "_token", - "type": "address" - }, - { - "name": "_symbol", - "type": "string" - } - ], - "name": "setTokenSymbol", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "newOwner", - "type": "address" - } - ], - "name": "transferOwnership", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "token", - "type": "address" - }, - { - "indexed": false, - "name": "name", - "type": "string" - }, - { - "indexed": false, - "name": "symbol", - "type": "string" - }, - { - "indexed": false, - "name": "decimals", - "type": "uint8" - }, - { - "indexed": false, - "name": "ipfsHash", - "type": "bytes" - }, - { - "indexed": false, - "name": "swarmHash", - "type": "bytes" - } - ], - "name": "LogAddToken", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "token", - "type": "address" - }, - { - "indexed": false, - "name": "name", - "type": "string" - }, - { - "indexed": false, - "name": "symbol", - "type": "string" - }, - { - "indexed": false, - "name": "decimals", - "type": "uint8" - }, - { - "indexed": false, - "name": "ipfsHash", - "type": "bytes" - }, - { - "indexed": false, - "name": "swarmHash", - "type": "bytes" - } - ], - "name": "LogRemoveToken", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "token", - "type": "address" - }, - { - "indexed": false, - "name": "oldName", - "type": "string" - }, - { - "indexed": false, - "name": "newName", - "type": "string" - } - ], - "name": "LogTokenNameChange", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "token", - "type": "address" - }, - { - "indexed": false, - "name": "oldSymbol", - "type": "string" - }, - { - "indexed": false, - "name": "newSymbol", - "type": "string" - } - ], - "name": "LogTokenSymbolChange", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "token", - "type": "address" - }, - { - "indexed": false, - "name": "oldIpfsHash", - "type": "bytes" - }, - { - "indexed": false, - "name": "newIpfsHash", - "type": "bytes" - } - ], - "name": "LogTokenIpfsHashChange", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "token", - "type": "address" - }, - { - "indexed": false, - "name": "oldSwarmHash", - "type": "bytes" - }, - { - "indexed": false, - "name": "newSwarmHash", - "type": "bytes" - } - ], - "name": "LogTokenSwarmHashChange", - "type": "event" - } - ], - "networks": { - "1": { - "address": "0x926a74c5c36adf004c87399e65f75628b0f98d2c" - }, - "3": { - "address": "0x6b1a50f0bb5a7995444bd3877b22dc89c62843ed" - }, - "4": { - "address": "0x4e9aad8184de8833365fea970cd9149372fdf1e6" - }, - "42": { - "address": "0xf18e504561f4347bea557f3d4558f559dddbae7f" - }, - "50": { - "address": "0x0b1ba0af832d7c05fd64161e0db78e85978e8082" - } - } -} diff --git a/packages/order-utils/src/compact_artifacts/TokenTransferProxy.json b/packages/order-utils/src/compact_artifacts/TokenTransferProxy.json deleted file mode 100644 index 8cf551ddb..000000000 --- a/packages/order-utils/src/compact_artifacts/TokenTransferProxy.json +++ /dev/null @@ -1,187 +0,0 @@ -{ - "contract_name": "TokenTransferProxy", - "abi": [ - { - "constant": false, - "inputs": [ - { - "name": "token", - "type": "address" - }, - { - "name": "from", - "type": "address" - }, - { - "name": "to", - "type": "address" - }, - { - "name": "value", - "type": "uint256" - } - ], - "name": "transferFrom", - "outputs": [ - { - "name": "", - "type": "bool" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "target", - "type": "address" - } - ], - "name": "addAuthorizedAddress", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "", - "type": "uint256" - } - ], - "name": "authorities", - "outputs": [ - { - "name": "", - "type": "address" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "target", - "type": "address" - } - ], - "name": "removeAuthorizedAddress", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "owner", - "outputs": [ - { - "name": "", - "type": "address" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "", - "type": "address" - } - ], - "name": "authorized", - "outputs": [ - { - "name": "", - "type": "bool" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "getAuthorizedAddresses", - "outputs": [ - { - "name": "", - "type": "address[]" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "newOwner", - "type": "address" - } - ], - "name": "transferOwnership", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "target", - "type": "address" - }, - { - "indexed": true, - "name": "caller", - "type": "address" - } - ], - "name": "LogAuthorizedAddressAdded", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "target", - "type": "address" - }, - { - "indexed": true, - "name": "caller", - "type": "address" - } - ], - "name": "LogAuthorizedAddressRemoved", - "type": "event" - } - ], - "networks": { - "1": { - "address": "0x8da0d80f5007ef1e431dd2127178d224e32c2ef4" - }, - "3": { - "address": "0x4e9aad8184de8833365fea970cd9149372fdf1e6" - }, - "4": { - "address": "0xa8e9fa8f91e5ae138c74648c9c304f1c75003a8d" - }, - "42": { - "address": "0x087eed4bc1ee3de49befbd66c662b434b15d49d4" - }, - "50": { - "address": "0x1dc4c1cefef38a777b15aa20260a54e584b16c48" - } - } -} diff --git a/packages/order-utils/src/compact_artifacts/ZRX.json b/packages/order-utils/src/compact_artifacts/ZRX.json deleted file mode 100644 index e40b8f268..000000000 --- a/packages/order-utils/src/compact_artifacts/ZRX.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "contract_name": "ZRX", - "networks": { - "1": { - "address": "0xe41d2489571d322189246dafa5ebde1f4699f498" - }, - "3": { - "address": "0xa8e9fa8f91e5ae138c74648c9c304f1c75003a8d" - }, - "4": { - "address": "0x00f58d6d585f84b2d7267940cede30ce2fe6eae8" - }, - "42": { - "address": "0x6ff6c0ff1d68b964901f986d4c9fa3ac68346570" - }, - "50": { - "address": "0x1d7022f5b17d2f8b695918fb48fa1089c9f85401" - } - } -} -- cgit v1.2.3 From 9778695b4ad1fd999eb79b01c768a2f2b9938917 Mon Sep 17 00:00:00 2001 From: fragosti Date: Mon, 4 Jun 2018 19:48:21 -0700 Subject: Try enabling no-unused-variable... --- packages/order-utils/src/assert.ts | 1 - packages/order-utils/src/order_hash.ts | 3 --- packages/order-utils/src/order_state_utils.ts | 1 - packages/order-utils/src/signature_utils.ts | 1 - 4 files changed, 6 deletions(-) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/assert.ts b/packages/order-utils/src/assert.ts index a1318b9b8..b4335980f 100644 --- a/packages/order-utils/src/assert.ts +++ b/packages/order-utils/src/assert.ts @@ -4,7 +4,6 @@ import { assert as sharedAssert } from '@0xproject/assert'; import { Schema } from '@0xproject/json-schemas'; // tslint:disable-next-line:no-unused-variable import { ECSignature, SignatureType } from '@0xproject/types'; -import { BigNumber } from '@0xproject/utils'; import { Web3Wrapper } from '@0xproject/web3-wrapper'; import * as _ from 'lodash'; diff --git a/packages/order-utils/src/order_hash.ts b/packages/order-utils/src/order_hash.ts index 2ef746ef8..b9d0b43aa 100644 --- a/packages/order-utils/src/order_hash.ts +++ b/packages/order-utils/src/order_hash.ts @@ -1,9 +1,6 @@ import { schemas, SchemaValidator } from '@0xproject/json-schemas'; import { Order, SignedOrder } from '@0xproject/types'; import { BigNumber } from '@0xproject/utils'; -import BN = require('bn.js'); -import { SolidityTypes } from 'ethereum-types'; -import * as ethABI from 'ethereumjs-abi'; import * as ethUtil from 'ethereumjs-util'; import * as _ from 'lodash'; diff --git a/packages/order-utils/src/order_state_utils.ts b/packages/order-utils/src/order_state_utils.ts index 61050c9d6..da33ea010 100644 --- a/packages/order-utils/src/order_state_utils.ts +++ b/packages/order-utils/src/order_state_utils.ts @@ -7,7 +7,6 @@ import { SignedOrder, } from '@0xproject/types'; import { BigNumber } from '@0xproject/utils'; -import * as _ from 'lodash'; import { AbstractBalanceAndProxyAllowanceFetcher } from './abstract/abstract_balance_and_proxy_allowance_fetcher'; import { AbstractOrderFilledCancelledFetcher } from './abstract/abstract_order_filled_cancelled_fetcher'; diff --git a/packages/order-utils/src/signature_utils.ts b/packages/order-utils/src/signature_utils.ts index c57699af0..c3fa0b6a5 100644 --- a/packages/order-utils/src/signature_utils.ts +++ b/packages/order-utils/src/signature_utils.ts @@ -159,7 +159,6 @@ export function isValidECSignature(data: string, signature: ECSignature, signerA assert.isHexString('data', data); assert.doesConformToSchema('signature', signature, schemas.ecSignatureSchema); assert.isETHAddressHex('signerAddress', signerAddress); - const normalizedSignerAddress = signerAddress.toLowerCase(); const msgHashBuff = ethUtil.toBuffer(data); try { -- cgit v1.2.3 From a97d77064aacda3de74b04894f110b05298c5ca8 Mon Sep 17 00:00:00 2001 From: fragosti Date: Wed, 6 Jun 2018 15:26:40 -0700 Subject: Get build and tests to pass --- packages/order-utils/src/assert.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/assert.ts b/packages/order-utils/src/assert.ts index b4335980f..b4b57d02a 100644 --- a/packages/order-utils/src/assert.ts +++ b/packages/order-utils/src/assert.ts @@ -1,10 +1,11 @@ import { assert as sharedAssert } from '@0xproject/assert'; // We need those two unused imports because they're actually used by sharedAssert which gets injected here -// tslint:disable-next-line:no-unused-variable +// tslint:disable:no-unused-variable import { Schema } from '@0xproject/json-schemas'; -// tslint:disable-next-line:no-unused-variable import { ECSignature, SignatureType } from '@0xproject/types'; +import { BigNumber } from '@0xproject/utils'; import { Web3Wrapper } from '@0xproject/web3-wrapper'; +// tslint:enable:no-unused-variable import * as _ from 'lodash'; import { utils } from './utils'; -- cgit v1.2.3 From 6058a74da54e916e970912d942954d55922cef95 Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Thu, 7 Jun 2018 18:02:48 +0200 Subject: Update naming in orderStateUtils to use asset over token, also removed cancelledAmount since in V2 it's binary. --- .../abstract_order_filled_cancelled_fetcher.ts | 3 +- packages/order-utils/src/order_state_utils.ts | 78 ++++++++++------------ 2 files changed, 37 insertions(+), 44 deletions(-) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/abstract/abstract_order_filled_cancelled_fetcher.ts b/packages/order-utils/src/abstract/abstract_order_filled_cancelled_fetcher.ts index f54bed6f1..ec398a11e 100644 --- a/packages/order-utils/src/abstract/abstract_order_filled_cancelled_fetcher.ts +++ b/packages/order-utils/src/abstract/abstract_order_filled_cancelled_fetcher.ts @@ -2,7 +2,6 @@ import { BigNumber } from '@0xproject/utils'; export abstract class AbstractOrderFilledCancelledFetcher { public abstract async getFilledTakerAmountAsync(orderHash: string): Promise; - public abstract async getCancelledTakerAmountAsync(orderHash: string): Promise; - public abstract async getUnavailableTakerAmountAsync(orderHash: string): Promise; + public abstract async isOrderCancelledAsync(orderHash: string): Promise; public abstract getZRXTokenAddress(): string; } diff --git a/packages/order-utils/src/order_state_utils.ts b/packages/order-utils/src/order_state_utils.ts index da33ea010..7636372f8 100644 --- a/packages/order-utils/src/order_state_utils.ts +++ b/packages/order-utils/src/order_state_utils.ts @@ -20,11 +20,8 @@ export class OrderStateUtils { private _balanceAndProxyAllowanceFetcher: AbstractBalanceAndProxyAllowanceFetcher; private _orderFilledCancelledFetcher: AbstractOrderFilledCancelledFetcher; private static _validateIfOrderIsValid(signedOrder: SignedOrder, orderRelevantState: OrderRelevantState): void { - const unavailableTakerTokenAmount = orderRelevantState.cancelledTakerTokenAmount.add( - orderRelevantState.filledTakerTokenAmount, - ); - const availableTakerTokenAmount = signedOrder.takerAssetAmount.minus(unavailableTakerTokenAmount); - if (availableTakerTokenAmount.eq(0)) { + const availableTakerAssetAmount = signedOrder.takerAssetAmount.minus(orderRelevantState.filledTakerAssetAmount); + if (availableTakerAssetAmount.eq(0)) { throw new Error(ExchangeContractErrs.OrderRemainingFillAmountZero); } @@ -42,12 +39,12 @@ export class OrderStateUtils { throw new Error(ExchangeContractErrs.InsufficientMakerFeeAllowance); } } - const minFillableTakerTokenAmountWithinNoRoundingErrorRange = signedOrder.takerAssetAmount + const minFillableTakerAssetAmountWithinNoRoundingErrorRange = signedOrder.takerAssetAmount .dividedBy(ACCEPTABLE_RELATIVE_ROUNDING_ERROR) .dividedBy(signedOrder.makerAssetAmount); if ( - orderRelevantState.remainingFillableTakerTokenAmount.lessThan( - minFillableTakerTokenAmountWithinNoRoundingErrorRange, + orderRelevantState.remainingFillableTakerAssetAmount.lessThan( + minFillableTakerAssetAmountWithinNoRoundingErrorRange, ) ) { throw new Error(ExchangeContractErrs.OrderFillRoundingError); @@ -72,23 +69,20 @@ export class OrderStateUtils { }; return orderState; } catch (err) { - const orderState: OrderStateInvalid = { - isValid: false, - orderHash, - error: err.message, - }; - return orderState; + throw err; } } public async getOrderRelevantStateAsync(signedOrder: SignedOrder): Promise { const zrxTokenAddress = this._orderFilledCancelledFetcher.getZRXTokenAddress(); + const makerProxyData = assetProxyUtils.decodeERC20ProxyData(signedOrder.makerAssetData); + const makerAssetAddress = makerProxyData.tokenAddress; const orderHash = orderHashUtils.getOrderHashHex(signedOrder); const makerBalance = await this._balanceAndProxyAllowanceFetcher.getBalanceAsync( - signedOrder.makerAssetData, + makerAssetAddress, signedOrder.makerAddress, ); const makerProxyAllowance = await this._balanceAndProxyAllowanceFetcher.getProxyAllowanceAsync( - signedOrder.makerAssetData, + makerAssetAddress, signedOrder.makerAddress, ); const makerFeeBalance = await this._balanceAndProxyAllowanceFetcher.getBalanceAsync( @@ -99,42 +93,42 @@ export class OrderStateUtils { zrxTokenAddress, signedOrder.makerAddress, ); - const filledTakerTokenAmount = await this._orderFilledCancelledFetcher.getFilledTakerAmountAsync(orderHash); - const cancelledTakerTokenAmount = await this._orderFilledCancelledFetcher.getCancelledTakerAmountAsync( - orderHash, - ); - const unavailableTakerTokenAmount = await this._orderFilledCancelledFetcher.getUnavailableTakerAmountAsync( - orderHash, - ); - const totalMakerTokenAmount = signedOrder.makerAssetAmount; - const totalTakerTokenAmount = signedOrder.takerAssetAmount; - const remainingTakerTokenAmount = totalTakerTokenAmount.minus(unavailableTakerTokenAmount); - const remainingMakerTokenAmount = remainingTakerTokenAmount - .times(totalMakerTokenAmount) - .dividedToIntegerBy(totalTakerTokenAmount); - const transferrableMakerTokenAmount = BigNumber.min([makerProxyAllowance, makerBalance]); - const transferrableFeeTokenAmount = BigNumber.min([makerFeeProxyAllowance, makerFeeBalance]); + const filledTakerAssetAmount = await this._orderFilledCancelledFetcher.getFilledTakerAmountAsync(orderHash); + const isOrderCancelled = await this._orderFilledCancelledFetcher.isOrderCancelledAsync(orderHash); + const totalMakerAssetAmount = signedOrder.makerAssetAmount; + const totalTakerAssetAmount = signedOrder.takerAssetAmount; + const remainingTakerAssetAmount = isOrderCancelled + ? new BigNumber(0) + : totalTakerAssetAmount.minus(filledTakerAssetAmount); + const remainingMakerAssetAmount = remainingTakerAssetAmount + .times(totalMakerAssetAmount) + .dividedToIntegerBy(totalTakerAssetAmount); + const transferrableMakerAssetAmount = BigNumber.min([makerProxyAllowance, makerBalance]); + const transferrableFeeAssetAmount = BigNumber.min([makerFeeProxyAllowance, makerFeeBalance]); const zrxAssetData = assetProxyUtils.encodeERC20ProxyData(zrxTokenAddress); - const isMakerTokenZRX = signedOrder.makerAssetData === zrxAssetData; + const isMakerAssetZRX = signedOrder.makerAssetData === zrxAssetData; + const isTraderMaker = true; const remainingFillableCalculator = new RemainingFillableCalculator( + isTraderMaker, signedOrder, - isMakerTokenZRX, - transferrableMakerTokenAmount, - transferrableFeeTokenAmount, - remainingMakerTokenAmount, + isMakerAssetZRX, + transferrableMakerAssetAmount, + transferrableFeeAssetAmount, + remainingMakerAssetAmount, ); - const remainingFillableMakerTokenAmount = remainingFillableCalculator.computeRemainingMakerFillable(); - const remainingFillableTakerTokenAmount = remainingFillableCalculator.computeRemainingTakerFillable(); + const remainingFillableMakerAssetAmount = remainingFillableCalculator.computeRemainingFillable(); + const remainingFillableTakerAssetAmount = remainingFillableMakerAssetAmount + .times(signedOrder.takerAssetAmount) + .dividedToIntegerBy(signedOrder.makerAssetAmount); const orderRelevantState = { makerBalance, makerProxyAllowance, makerFeeBalance, makerFeeProxyAllowance, - filledTakerTokenAmount, - cancelledTakerTokenAmount, - remainingFillableMakerTokenAmount, - remainingFillableTakerTokenAmount, + filledTakerAssetAmount, + remainingFillableMakerAssetAmount, + remainingFillableTakerAssetAmount, }; return orderRelevantState; } -- cgit v1.2.3 From 73cc2a140c778a5396c2766562a3fc648337e18a Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Thu, 7 Jun 2018 18:03:50 +0200 Subject: - Refactor remainingFillableCalculator so it can be used for the maker and taker side - Moved the tests over from order-watcher - Did some token -> asset renaming --- .../src/remaining_fillable_calculator.ts | 115 ++++++++++----------- 1 file changed, 57 insertions(+), 58 deletions(-) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/remaining_fillable_calculator.ts b/packages/order-utils/src/remaining_fillable_calculator.ts index b291d8ea9..acab2f41b 100644 --- a/packages/order-utils/src/remaining_fillable_calculator.ts +++ b/packages/order-utils/src/remaining_fillable_calculator.ts @@ -3,93 +3,92 @@ import { BigNumber } from '@0xproject/utils'; export class RemainingFillableCalculator { private _signedOrder: SignedOrder; - private _isMakerTokenZRX: boolean; + private _isTraderAssetZRX: boolean; // Transferrable Amount is the minimum of Approval and Balance - private _transferrableMakerTokenAmount: BigNumber; - private _transferrableMakerFeeTokenAmount: BigNumber; - private _remainingMakerTokenAmount: BigNumber; - private _remainingMakerFeeAmount: BigNumber; + private _transferrableAssetAmount: BigNumber; + private _transferrableFeeAmount: BigNumber; + private _remainingOrderAssetAmount: BigNumber; + private _remainingOrderFeeAmount: BigNumber; + private _orderFee: BigNumber; + private _orderAssetAmount: BigNumber; constructor( + isTraderMaker: boolean, signedOrder: SignedOrder, - isMakerTokenZRX: boolean, - transferrableMakerTokenAmount: BigNumber, - transferrableMakerFeeTokenAmount: BigNumber, - remainingMakerTokenAmount: BigNumber, + isTraderAssetZRX: boolean, + transferrableAssetAmount: BigNumber, + transferrableFeeAmount: BigNumber, + remainingOrderAssetAmount: BigNumber, ) { + if (isTraderMaker) { + this._orderFee = signedOrder.makerFee; + this._orderAssetAmount = signedOrder.makerAssetAmount; + } else { + this._orderFee = signedOrder.takerFee; + this._orderAssetAmount = signedOrder.takerAssetAmount; + } this._signedOrder = signedOrder; - this._isMakerTokenZRX = isMakerTokenZRX; - this._transferrableMakerTokenAmount = transferrableMakerTokenAmount; - this._transferrableMakerFeeTokenAmount = transferrableMakerFeeTokenAmount; - this._remainingMakerTokenAmount = remainingMakerTokenAmount; - this._remainingMakerFeeAmount = remainingMakerTokenAmount - .times(signedOrder.makerFee) - .dividedToIntegerBy(signedOrder.makerAssetAmount); + this._isTraderAssetZRX = isTraderAssetZRX; + this._transferrableAssetAmount = transferrableAssetAmount; + this._transferrableFeeAmount = transferrableFeeAmount; + this._remainingOrderAssetAmount = remainingOrderAssetAmount; + this._remainingOrderFeeAmount = remainingOrderAssetAmount + .times(this._orderFee) + .dividedToIntegerBy(this._orderAssetAmount); } - public computeRemainingMakerFillable(): BigNumber { + public computeRemainingFillable(): BigNumber { if (this._hasSufficientFundsForFeeAndTransferAmount()) { - return this._remainingMakerTokenAmount; + return this._remainingOrderAssetAmount; } - if (this._signedOrder.makerFee.isZero()) { - return BigNumber.min(this._remainingMakerTokenAmount, this._transferrableMakerTokenAmount); + if (this._orderFee.isZero()) { + return BigNumber.min(this._remainingOrderAssetAmount, this._transferrableAssetAmount); } - return this._calculatePartiallyFillableMakerTokenAmount(); - } - public computeRemainingTakerFillable(): BigNumber { - return this.computeRemainingMakerFillable() - .times(this._signedOrder.takerAssetAmount) - .dividedToIntegerBy(this._signedOrder.makerAssetAmount); + return this._calculatePartiallyFillableAssetAmount(); } private _hasSufficientFundsForFeeAndTransferAmount(): boolean { - if (this._isMakerTokenZRX) { - const totalZRXTransferAmountRequired = this._remainingMakerTokenAmount.plus(this._remainingMakerFeeAmount); - const hasSufficientFunds = this._transferrableMakerTokenAmount.greaterThanOrEqualTo( + if (this._isTraderAssetZRX) { + const totalZRXTransferAmountRequired = this._remainingOrderAssetAmount.plus(this._remainingOrderFeeAmount); + const hasSufficientFunds = this._transferrableAssetAmount.greaterThanOrEqualTo( totalZRXTransferAmountRequired, ); return hasSufficientFunds; } else { - const hasSufficientFundsForTransferAmount = this._transferrableMakerTokenAmount.greaterThanOrEqualTo( - this._remainingMakerTokenAmount, + const hasSufficientFundsForTransferAmount = this._transferrableAssetAmount.greaterThanOrEqualTo( + this._remainingOrderAssetAmount, ); - const hasSufficientFundsForFeeAmount = this._transferrableMakerFeeTokenAmount.greaterThanOrEqualTo( - this._remainingMakerFeeAmount, + const hasSufficientFundsForFeeAmount = this._transferrableFeeAmount.greaterThanOrEqualTo( + this._remainingOrderFeeAmount, ); const hasSufficientFunds = hasSufficientFundsForTransferAmount && hasSufficientFundsForFeeAmount; return hasSufficientFunds; } } - private _calculatePartiallyFillableMakerTokenAmount(): BigNumber { + private _calculatePartiallyFillableAssetAmount(): BigNumber { // Given an order for 200 wei for 2 ZRXwei fee, find 100 wei for 1 ZRXwei. Order ratio is then 100:1 - const orderToFeeRatio = this._signedOrder.makerAssetAmount.dividedBy(this._signedOrder.makerFee); - // The number of times the maker can fill the order, if each fill only required the transfer of a single + const orderToFeeRatio = this._orderAssetAmount.dividedBy(this._orderFee); + // The number of times the trader (maker or taker) can fill the order, if each fill only required the transfer of a single // baseUnit of fee tokens. - // Given 2 ZRXwei, the maximum amount of times Maker can fill this order, in terms of fees, is 2 - const fillableTimesInFeeTokenBaseUnits = BigNumber.min( - this._transferrableMakerFeeTokenAmount, - this._remainingMakerFeeAmount, - ); - // The number of times the Maker can fill the order, given the Maker Token Balance - // Assuming a balance of 150 wei, and an orderToFeeRatio of 100:1, maker can fill this order 1 time. - let fillableTimesInMakerTokenUnits = this._transferrableMakerTokenAmount.dividedBy(orderToFeeRatio); - if (this._isMakerTokenZRX) { - // If ZRX is the maker token, the Fee and the Maker amount need to be removed from the same pool; + // Given 2 ZRXwei, the maximum amount of times trader can fill this order, in terms of fees, is 2 + const fillableTimesInFeeBaseUnits = BigNumber.min(this._transferrableFeeAmount, this._remainingOrderFeeAmount); + // The number of times the trader can fill the order, given the traders asset Balance + // Assuming a balance of 150 wei, and an orderToFeeRatio of 100:1, trader can fill this order 1 time. + let fillableTimesInAssetUnits = this._transferrableAssetAmount.dividedBy(orderToFeeRatio); + if (this._isTraderAssetZRX) { + // If ZRX is the trader asset, the Fee and the trader fill amount need to be removed from the same pool; // 200 ZRXwei for 2ZRXwei fee can only be filled once (need 202 ZRXwei) - const totalZRXTokenPooled = this._transferrableMakerTokenAmount; + const totalZRXTokenPooled = this._transferrableAssetAmount; // The purchasing power here is less as the tokens are taken from the same Pool // For every one number of fills, we have to take an extra ZRX out of the pool - fillableTimesInMakerTokenUnits = totalZRXTokenPooled.dividedBy(orderToFeeRatio.plus(new BigNumber(1))); + fillableTimesInAssetUnits = totalZRXTokenPooled.dividedBy(orderToFeeRatio.plus(new BigNumber(1))); } // When Ratio is not fully divisible there can be remainders which cannot be represented, so they are floored. // This can result in a RoundingError being thrown by the Exchange Contract. - const partiallyFillableMakerTokenAmount = fillableTimesInMakerTokenUnits - .times(this._signedOrder.makerAssetAmount) - .dividedToIntegerBy(this._signedOrder.makerFee); - const partiallyFillableFeeTokenAmount = fillableTimesInFeeTokenBaseUnits - .times(this._signedOrder.makerAssetAmount) - .dividedToIntegerBy(this._signedOrder.makerFee); - const partiallyFillableAmount = BigNumber.min( - partiallyFillableMakerTokenAmount, - partiallyFillableFeeTokenAmount, - ); + const partiallyFillableAssetAmount = fillableTimesInAssetUnits + .times(this._orderAssetAmount) + .dividedToIntegerBy(this._orderFee); + const partiallyFillableFeeAmount = fillableTimesInFeeBaseUnits + .times(this._orderAssetAmount) + .dividedToIntegerBy(this._orderFee); + const partiallyFillableAmount = BigNumber.min(partiallyFillableAssetAmount, partiallyFillableFeeAmount); return partiallyFillableAmount; } } -- cgit v1.2.3 From dee0fec9e9521712d11f1f040ae1264c41badaba Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Thu, 7 Jun 2018 18:10:56 +0200 Subject: Revert to returning orderState on invalid order --- packages/order-utils/src/order_state_utils.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/order_state_utils.ts b/packages/order-utils/src/order_state_utils.ts index 7636372f8..ef868e60f 100644 --- a/packages/order-utils/src/order_state_utils.ts +++ b/packages/order-utils/src/order_state_utils.ts @@ -69,7 +69,12 @@ export class OrderStateUtils { }; return orderState; } catch (err) { - throw err; + const orderState: OrderStateInvalid = { + isValid: false, + orderHash, + error: err.message, + }; + return orderState; } } public async getOrderRelevantStateAsync(signedOrder: SignedOrder): Promise { -- cgit v1.2.3 From f5ad553be35bcc35fdac9620ae3d1e5546fd902c Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Thu, 7 Jun 2018 18:33:42 +0200 Subject: Pass in fee and assetAmount rather then the whole signedOrder --- packages/order-utils/src/order_state_utils.ts | 5 ++--- .../order-utils/src/remaining_fillable_calculator.ts | 16 ++++------------ 2 files changed, 6 insertions(+), 15 deletions(-) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/order_state_utils.ts b/packages/order-utils/src/order_state_utils.ts index ef868e60f..ca18097c9 100644 --- a/packages/order-utils/src/order_state_utils.ts +++ b/packages/order-utils/src/order_state_utils.ts @@ -113,10 +113,9 @@ export class OrderStateUtils { const zrxAssetData = assetProxyUtils.encodeERC20ProxyData(zrxTokenAddress); const isMakerAssetZRX = signedOrder.makerAssetData === zrxAssetData; - const isTraderMaker = true; const remainingFillableCalculator = new RemainingFillableCalculator( - isTraderMaker, - signedOrder, + signedOrder.makerFee, + signedOrder.makerAssetAmount, isMakerAssetZRX, transferrableMakerAssetAmount, transferrableFeeAssetAmount, diff --git a/packages/order-utils/src/remaining_fillable_calculator.ts b/packages/order-utils/src/remaining_fillable_calculator.ts index acab2f41b..bc146e931 100644 --- a/packages/order-utils/src/remaining_fillable_calculator.ts +++ b/packages/order-utils/src/remaining_fillable_calculator.ts @@ -1,8 +1,6 @@ -import { SignedOrder } from '@0xproject/types'; import { BigNumber } from '@0xproject/utils'; export class RemainingFillableCalculator { - private _signedOrder: SignedOrder; private _isTraderAssetZRX: boolean; // Transferrable Amount is the minimum of Approval and Balance private _transferrableAssetAmount: BigNumber; @@ -12,21 +10,15 @@ export class RemainingFillableCalculator { private _orderFee: BigNumber; private _orderAssetAmount: BigNumber; constructor( - isTraderMaker: boolean, - signedOrder: SignedOrder, + orderFee: BigNumber, + orderAssetAmount: BigNumber, isTraderAssetZRX: boolean, transferrableAssetAmount: BigNumber, transferrableFeeAmount: BigNumber, remainingOrderAssetAmount: BigNumber, ) { - if (isTraderMaker) { - this._orderFee = signedOrder.makerFee; - this._orderAssetAmount = signedOrder.makerAssetAmount; - } else { - this._orderFee = signedOrder.takerFee; - this._orderAssetAmount = signedOrder.takerAssetAmount; - } - this._signedOrder = signedOrder; + this._orderFee = orderFee; + this._orderAssetAmount = orderAssetAmount; this._isTraderAssetZRX = isTraderAssetZRX; this._transferrableAssetAmount = transferrableAssetAmount; this._transferrableFeeAmount = transferrableFeeAmount; -- cgit v1.2.3 From 842363200b3b8aded3b03fc8e46a329ff9534e36 Mon Sep 17 00:00:00 2001 From: Greg Hysen Date: Fri, 25 May 2018 00:31:03 -0700 Subject: Tons of tests around nested byte arrays and ERC721 receiver --- packages/order-utils/src/asset_proxy_utils.ts | 30 +++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/asset_proxy_utils.ts b/packages/order-utils/src/asset_proxy_utils.ts index 55f2d56df..8255376a1 100644 --- a/packages/order-utils/src/asset_proxy_utils.ts +++ b/packages/order-utils/src/asset_proxy_utils.ts @@ -2,6 +2,7 @@ import { AssetProxyId, ERC20ProxyData, ERC721ProxyData, ProxyData } from '@0xpro import { BigNumber } from '@0xproject/utils'; import BN = require('bn.js'); import ethUtil = require('ethereumjs-util'); +import * as _ from 'lodash'; const ERC20_PROXY_METADATA_BYTE_LENGTH = 21; const ERC721_PROXY_METADATA_BYTE_LENGTH = 53; @@ -74,19 +75,25 @@ export const assetProxyUtils = { }; return erc20ProxyData; }, - encodeERC721ProxyData(tokenAddress: string, tokenId: BigNumber): string { + encodeERC721ProxyData(tokenAddress: string, tokenId: BigNumber, data?: string): string { const encodedAssetProxyId = assetProxyUtils.encodeAssetProxyId(AssetProxyId.ERC721); const encodedAddress = assetProxyUtils.encodeAddress(tokenAddress); const encodedTokenId = assetProxyUtils.encodeUint256(tokenId); const encodedMetadata = Buffer.concat([encodedAddress, encodedTokenId, encodedAssetProxyId]); + if (!_.isUndefined(data)) { + const encodedData = ethUtil.toBuffer(data); + const dataLength = new BigNumber(encodedData.byteLength); + const encodedDataLength = assetProxyUtils.encodeUint256(dataLength); + encodedMetadata = Buffer.concat([encodedMetadata, encodedDataLength, encodedData]); + } const encodedMetadataHex = ethUtil.bufferToHex(encodedMetadata); return encodedMetadataHex; }, decodeERC721ProxyData(proxyData: string): ERC721ProxyData { const encodedProxyMetadata = ethUtil.toBuffer(proxyData); - if (encodedProxyMetadata.byteLength !== ERC721_PROXY_METADATA_BYTE_LENGTH) { + if (encodedProxyMetadata.byteLength < ERC721_PROXY_METADATA_BYTE_LENGTH) { throw new Error( - `Could not decode ERC20 Proxy Data. Expected length of encoded data to be 53. Got ${ + `Could not decode ERC20 Proxy Data. Expected length of encoded data to be at least 53. Got ${ encodedProxyMetadata.byteLength }`, ); @@ -106,10 +113,25 @@ export const assetProxyUtils = { const tokenIdOffset = ERC721_PROXY_METADATA_BYTE_LENGTH - 1; const encodedTokenId = encodedProxyMetadata.slice(addressOffset, tokenIdOffset); const tokenId = assetProxyUtils.decodeUint256(encodedTokenId); - const erc721ProxyData = { + const nullData = '0x'; + let data = nullData; + if (encodedProxyMetadata.byteLength > 53) { + const encodedDataLength = encodedProxyMetadata.slice(53, 85); + const dataLength = assetProxyUtils.decodeUint256(encodedDataLength); + const expectedDataLength = new BigNumber(encodedProxyMetadata.byteLength - 85); + if (!dataLength.equals(expectedDataLength)) { + throw new Error( + `Data length (${dataLength}) does not match actual length of data (${expectedDataLength})`, + ); + } + const encodedData = encodedProxyMetadata.slice(85); + data = ethUtil.bufferToHex(encodedData); + } + const erc721ProxyData: ERC721ProxyData = { assetProxyId, tokenAddress, tokenId, + data, }; return erc721ProxyData; }, -- cgit v1.2.3 From e042e0ad32cd2ac9e707cb8e52961957f58314ce Mon Sep 17 00:00:00 2001 From: Greg Hysen Date: Thu, 31 May 2018 14:06:47 -0700 Subject: Converged on naming scheme for asset data: renamed all instances of assetMetadata, proxyData, proxyMetadata to assetData --- packages/order-utils/src/asset_proxy_utils.ts | 66 +++++++++++++-------------- 1 file changed, 33 insertions(+), 33 deletions(-) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/asset_proxy_utils.ts b/packages/order-utils/src/asset_proxy_utils.ts index 8255376a1..1f1e49f0f 100644 --- a/packages/order-utils/src/asset_proxy_utils.ts +++ b/packages/order-utils/src/asset_proxy_utils.ts @@ -41,7 +41,7 @@ export const assetProxyUtils = { const value = new BigNumber(formattedValue, 16); return value; }, - encodeERC20ProxyData(tokenAddress: string): string { + encodeERC20AssetData(tokenAddress: string): string { const encodedAssetProxyId = assetProxyUtils.encodeAssetProxyId(AssetProxyId.ERC20); const encodedAddress = assetProxyUtils.encodeAddress(tokenAddress); const encodedMetadata = Buffer.concat([encodedAddress, encodedAssetProxyId]); @@ -53,11 +53,11 @@ export const assetProxyUtils = { if (encodedProxyMetadata.byteLength !== ERC20_PROXY_METADATA_BYTE_LENGTH) { throw new Error( `Could not decode ERC20 Proxy Data. Expected length of encoded data to be 21. Got ${ - encodedProxyMetadata.byteLength + encodedAssetData.byteLength }`, ); } - const encodedAssetProxyId = encodedProxyMetadata.slice(-1); + const encodedAssetProxyId = encodedAssetData.slice(-1); const assetProxyId = assetProxyUtils.decodeAssetProxyId(encodedAssetProxyId); if (assetProxyId !== AssetProxyId.ERC20) { throw new Error( @@ -69,13 +69,13 @@ export const assetProxyUtils = { const addressOffset = ERC20_PROXY_METADATA_BYTE_LENGTH - 1; const encodedTokenAddress = encodedProxyMetadata.slice(0, addressOffset); const tokenAddress = assetProxyUtils.decodeAddress(encodedTokenAddress); - const erc20ProxyData = { + const erc20AssetData = { assetProxyId, tokenAddress, }; - return erc20ProxyData; + return erc20AssetData; }, - encodeERC721ProxyData(tokenAddress: string, tokenId: BigNumber, data?: string): string { + encodeERC721AssetData(tokenAddress: string, tokenId: BigNumber, data?: string): string { const encodedAssetProxyId = assetProxyUtils.encodeAssetProxyId(AssetProxyId.ERC721); const encodedAddress = assetProxyUtils.encodeAddress(tokenAddress); const encodedTokenId = assetProxyUtils.encodeUint256(tokenId); @@ -89,16 +89,16 @@ export const assetProxyUtils = { const encodedMetadataHex = ethUtil.bufferToHex(encodedMetadata); return encodedMetadataHex; }, - decodeERC721ProxyData(proxyData: string): ERC721ProxyData { - const encodedProxyMetadata = ethUtil.toBuffer(proxyData); - if (encodedProxyMetadata.byteLength < ERC721_PROXY_METADATA_BYTE_LENGTH) { + decodeERC721AssetData(assetData: string): ERC721AssetData { + const encodedAssetData = ethUtil.toBuffer(assetData); + if (encodedAssetData.byteLength < ERC721_PROXY_METADATA_BYTE_LENGTH) { throw new Error( `Could not decode ERC20 Proxy Data. Expected length of encoded data to be at least 53. Got ${ - encodedProxyMetadata.byteLength + encodedAssetData.byteLength }`, ); } - const encodedAssetProxyId = encodedProxyMetadata.slice(-1); + const encodedAssetProxyId = encodedAssetData.slice(-1); const assetProxyId = assetProxyUtils.decodeAssetProxyId(encodedAssetProxyId); if (assetProxyId !== AssetProxyId.ERC721) { throw new Error( @@ -115,57 +115,57 @@ export const assetProxyUtils = { const tokenId = assetProxyUtils.decodeUint256(encodedTokenId); const nullData = '0x'; let data = nullData; - if (encodedProxyMetadata.byteLength > 53) { - const encodedDataLength = encodedProxyMetadata.slice(53, 85); + if (encodedAssetData.byteLength > 53) { + const encodedDataLength = encodedAssetData.slice(53, 85); const dataLength = assetProxyUtils.decodeUint256(encodedDataLength); - const expectedDataLength = new BigNumber(encodedProxyMetadata.byteLength - 85); + const expectedDataLength = new BigNumber(encodedAssetData.byteLength - 85); if (!dataLength.equals(expectedDataLength)) { throw new Error( `Data length (${dataLength}) does not match actual length of data (${expectedDataLength})`, ); } - const encodedData = encodedProxyMetadata.slice(85); + const encodedData = encodedAssetData.slice(85); data = ethUtil.bufferToHex(encodedData); } - const erc721ProxyData: ERC721ProxyData = { + const erc721AssetData: ERC721AssetData = { assetProxyId, tokenAddress, tokenId, data, }; - return erc721ProxyData; + return erc721AssetData; }, - decodeProxyDataId(proxyData: string): AssetProxyId { - const encodedProxyMetadata = ethUtil.toBuffer(proxyData); - if (encodedProxyMetadata.byteLength < 1) { + decodeAssetDataId(assetData: string): AssetProxyId { + const encodedAssetData = ethUtil.toBuffer(assetData); + if (encodedAssetData.byteLength < 1) { throw new Error( `Could not decode Proxy Data. Expected length of encoded data to be at least 1. Got ${ - encodedProxyMetadata.byteLength + encodedAssetData.byteLength }`, ); } - const encodedAssetProxyId = encodedProxyMetadata.slice(-1); + const encodedAssetProxyId = encodedAssetData.slice(-1); const assetProxyId = assetProxyUtils.decodeAssetProxyId(encodedAssetProxyId); return assetProxyId; }, - decodeProxyData(proxyData: string): ProxyData { - const assetProxyId = assetProxyUtils.decodeProxyDataId(proxyData); + decodeAssetData(assetData: string): AssetData { + const assetProxyId = assetProxyUtils.decodeAssetDataId(assetData); switch (assetProxyId) { case AssetProxyId.ERC20: - const erc20ProxyData = assetProxyUtils.decodeERC20ProxyData(proxyData); - const generalizedERC20ProxyData = { + const erc20AssetData = assetProxyUtils.decodeERC20AssetData(assetData); + const generalizedERC20AssetData = { assetProxyId, - tokenAddress: erc20ProxyData.tokenAddress, + tokenAddress: erc20AssetData.tokenAddress, }; - return generalizedERC20ProxyData; + return generalizedERC20AssetData; case AssetProxyId.ERC721: - const erc721ProxyData = assetProxyUtils.decodeERC721ProxyData(proxyData); - const generaliedERC721ProxyData = { + const erc721AssetData = assetProxyUtils.decodeERC721AssetData(assetData); + const generaliedERC721AssetData = { assetProxyId, - tokenAddress: erc721ProxyData.tokenAddress, - data: erc721ProxyData.tokenId, + tokenAddress: erc721AssetData.tokenAddress, + data: erc721AssetData.tokenId, }; - return generaliedERC721ProxyData; + return generaliedERC721AssetData; default: throw new Error(`Unrecognized asset proxy id: ${assetProxyId}`); } -- cgit v1.2.3 From e4e36760952287a84f8991df8589c183036383db Mon Sep 17 00:00:00 2001 From: Greg Hysen Date: Fri, 1 Jun 2018 14:17:13 -0700 Subject: Fixed up after rebasing. Contracts build and tests pass --- packages/order-utils/src/asset_proxy_utils.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/asset_proxy_utils.ts b/packages/order-utils/src/asset_proxy_utils.ts index 1f1e49f0f..a12be83a3 100644 --- a/packages/order-utils/src/asset_proxy_utils.ts +++ b/packages/order-utils/src/asset_proxy_utils.ts @@ -79,13 +79,14 @@ export const assetProxyUtils = { const encodedAssetProxyId = assetProxyUtils.encodeAssetProxyId(AssetProxyId.ERC721); const encodedAddress = assetProxyUtils.encodeAddress(tokenAddress); const encodedTokenId = assetProxyUtils.encodeUint256(tokenId); - const encodedMetadata = Buffer.concat([encodedAddress, encodedTokenId, encodedAssetProxyId]); + let encodedMetadata = Buffer.concat([encodedAddress, encodedTokenId]); if (!_.isUndefined(data)) { const encodedData = ethUtil.toBuffer(data); const dataLength = new BigNumber(encodedData.byteLength); const encodedDataLength = assetProxyUtils.encodeUint256(dataLength); encodedMetadata = Buffer.concat([encodedMetadata, encodedDataLength, encodedData]); } + encodedMetadata = Buffer.concat([encodedMetadata, encodedAssetProxyId]); const encodedMetadataHex = ethUtil.bufferToHex(encodedMetadata); return encodedMetadataHex; }, @@ -116,7 +117,7 @@ export const assetProxyUtils = { const nullData = '0x'; let data = nullData; if (encodedAssetData.byteLength > 53) { - const encodedDataLength = encodedAssetData.slice(53, 85); + const encodedDataLength = encodedAssetData.slice(52, 84); const dataLength = assetProxyUtils.decodeUint256(encodedDataLength); const expectedDataLength = new BigNumber(encodedAssetData.byteLength - 85); if (!dataLength.equals(expectedDataLength)) { @@ -124,7 +125,7 @@ export const assetProxyUtils = { `Data length (${dataLength}) does not match actual length of data (${expectedDataLength})`, ); } - const encodedData = encodedAssetData.slice(85); + const encodedData = encodedAssetData.slice(84, expectedDataLength.toNumber() + 84); data = ethUtil.bufferToHex(encodedData); } const erc721AssetData: ERC721AssetData = { -- cgit v1.2.3 From 12e2bfc794831c0008bdbfc27dad9509f2578057 Mon Sep 17 00:00:00 2001 From: Greg Hysen Date: Mon, 4 Jun 2018 18:14:44 -0700 Subject: Fixes after rebasing --- packages/order-utils/src/asset_proxy_utils.ts | 78 ++++++++++++++------------- packages/order-utils/src/order_state_utils.ts | 4 +- 2 files changed, 44 insertions(+), 38 deletions(-) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/asset_proxy_utils.ts b/packages/order-utils/src/asset_proxy_utils.ts index a12be83a3..61a9b12e9 100644 --- a/packages/order-utils/src/asset_proxy_utils.ts +++ b/packages/order-utils/src/asset_proxy_utils.ts @@ -1,11 +1,11 @@ -import { AssetProxyId, ERC20ProxyData, ERC721ProxyData, ProxyData } from '@0xproject/types'; +import { AssetData, AssetProxyId, ERC20AssetData, ERC721AssetData } from '@0xproject/types'; import { BigNumber } from '@0xproject/utils'; import BN = require('bn.js'); import ethUtil = require('ethereumjs-util'); import * as _ from 'lodash'; -const ERC20_PROXY_METADATA_BYTE_LENGTH = 21; -const ERC721_PROXY_METADATA_BYTE_LENGTH = 53; +const ERC20_ASSET_DATA_BYTE_LENGTH = 21; +const ERC721_ASSET_DATA_BYTE_LENGTH = 53; export const assetProxyUtils = { encodeAssetProxyId(assetProxyId: AssetProxyId): Buffer { @@ -44,13 +44,13 @@ export const assetProxyUtils = { encodeERC20AssetData(tokenAddress: string): string { const encodedAssetProxyId = assetProxyUtils.encodeAssetProxyId(AssetProxyId.ERC20); const encodedAddress = assetProxyUtils.encodeAddress(tokenAddress); - const encodedMetadata = Buffer.concat([encodedAddress, encodedAssetProxyId]); - const encodedMetadataHex = ethUtil.bufferToHex(encodedMetadata); - return encodedMetadataHex; + const encodedAssetData = Buffer.concat([encodedAddress, encodedAssetProxyId]); + const encodedAssetDataHex = ethUtil.bufferToHex(encodedAssetData); + return encodedAssetDataHex; }, - decodeERC20ProxyData(proxyData: string): ERC20ProxyData { - const encodedProxyMetadata = ethUtil.toBuffer(proxyData); - if (encodedProxyMetadata.byteLength !== ERC20_PROXY_METADATA_BYTE_LENGTH) { + decodeERC20AssetData(proxyData: string): ERC20AssetData { + const encodedAssetData = ethUtil.toBuffer(proxyData); + if (encodedAssetData.byteLength !== ERC20_ASSET_DATA_BYTE_LENGTH) { throw new Error( `Could not decode ERC20 Proxy Data. Expected length of encoded data to be 21. Got ${ encodedAssetData.byteLength @@ -66,8 +66,8 @@ export const assetProxyUtils = { }), but got ${assetProxyId}`, ); } - const addressOffset = ERC20_PROXY_METADATA_BYTE_LENGTH - 1; - const encodedTokenAddress = encodedProxyMetadata.slice(0, addressOffset); + const addressOffset = ERC20_ASSET_DATA_BYTE_LENGTH - 1; + const encodedTokenAddress = encodedAssetData.slice(0, addressOffset); const tokenAddress = assetProxyUtils.decodeAddress(encodedTokenAddress); const erc20AssetData = { assetProxyId, @@ -75,30 +75,36 @@ export const assetProxyUtils = { }; return erc20AssetData; }, - encodeERC721AssetData(tokenAddress: string, tokenId: BigNumber, data?: string): string { + encodeERC721AssetData(tokenAddress: string, tokenId: BigNumber, receiverData?: string): string { const encodedAssetProxyId = assetProxyUtils.encodeAssetProxyId(AssetProxyId.ERC721); const encodedAddress = assetProxyUtils.encodeAddress(tokenAddress); const encodedTokenId = assetProxyUtils.encodeUint256(tokenId); - let encodedMetadata = Buffer.concat([encodedAddress, encodedTokenId]); - if (!_.isUndefined(data)) { - const encodedData = ethUtil.toBuffer(data); - const dataLength = new BigNumber(encodedData.byteLength); - const encodedDataLength = assetProxyUtils.encodeUint256(dataLength); - encodedMetadata = Buffer.concat([encodedMetadata, encodedDataLength, encodedData]); + let encodedAssetData = Buffer.concat([encodedAddress, encodedTokenId]); + if (!_.isUndefined(receiverData)) { + const encodedReceiverData = ethUtil.toBuffer(receiverData); + const receiverDataLength = new BigNumber(encodedReceiverData.byteLength); + const encodedReceiverDataLength = assetProxyUtils.encodeUint256(receiverDataLength); + encodedAssetData = Buffer.concat([encodedAssetData, encodedReceiverDataLength, encodedReceiverData]); } - encodedMetadata = Buffer.concat([encodedMetadata, encodedAssetProxyId]); - const encodedMetadataHex = ethUtil.bufferToHex(encodedMetadata); - return encodedMetadataHex; + encodedAssetData = Buffer.concat([encodedAssetData, encodedAssetProxyId]); + const encodedAssetDataHex = ethUtil.bufferToHex(encodedAssetData); + return encodedAssetDataHex; }, decodeERC721AssetData(assetData: string): ERC721AssetData { const encodedAssetData = ethUtil.toBuffer(assetData); - if (encodedAssetData.byteLength < ERC721_PROXY_METADATA_BYTE_LENGTH) { + if (encodedAssetData.byteLength < ERC721_ASSET_DATA_BYTE_LENGTH) { throw new Error( `Could not decode ERC20 Proxy Data. Expected length of encoded data to be at least 53. Got ${ encodedAssetData.byteLength }`, ); } + const addressOffset = 0; + const tokenIdOffset = 20; + const receiverDataLengthOffset = 52; + const receiverDataOffset = 84; + const encodedTokenAddress = encodedAssetData.slice(addressOffset, tokenIdOffset); + const proxyIdOffset = encodedAssetData.byteLength - 1; const encodedAssetProxyId = encodedAssetData.slice(-1); const assetProxyId = assetProxyUtils.decodeAssetProxyId(encodedAssetProxyId); if (assetProxyId !== AssetProxyId.ERC721) { @@ -108,31 +114,31 @@ export const assetProxyUtils = { }), but got ${assetProxyId}`, ); } - const addressOffset = ERC20_PROXY_METADATA_BYTE_LENGTH - 1; - const encodedTokenAddress = encodedProxyMetadata.slice(0, addressOffset); const tokenAddress = assetProxyUtils.decodeAddress(encodedTokenAddress); - const tokenIdOffset = ERC721_PROXY_METADATA_BYTE_LENGTH - 1; - const encodedTokenId = encodedProxyMetadata.slice(addressOffset, tokenIdOffset); + const encodedTokenId = encodedAssetData.slice(tokenIdOffset, receiverDataLengthOffset); const tokenId = assetProxyUtils.decodeUint256(encodedTokenId); const nullData = '0x'; - let data = nullData; - if (encodedAssetData.byteLength > 53) { - const encodedDataLength = encodedAssetData.slice(52, 84); - const dataLength = assetProxyUtils.decodeUint256(encodedDataLength); - const expectedDataLength = new BigNumber(encodedAssetData.byteLength - 85); - if (!dataLength.equals(expectedDataLength)) { + let receiverData = nullData; + if (encodedAssetData.byteLength > receiverDataLengthOffset + 1) { + const encodedReceiverDataLength = encodedAssetData.slice(receiverDataLengthOffset, receiverDataOffset); + const receiverDataLength = assetProxyUtils.decodeUint256(encodedReceiverDataLength); + const expectedReceiverDataLength = new BigNumber(encodedAssetData.byteLength - (receiverDataOffset + 1)); + if (!receiverDataLength.equals(expectedReceiverDataLength)) { throw new Error( - `Data length (${dataLength}) does not match actual length of data (${expectedDataLength})`, + `Data length (${receiverDataLength}) does not match actual length of data (${expectedReceiverDataLength})`, ); } - const encodedData = encodedAssetData.slice(84, expectedDataLength.toNumber() + 84); - data = ethUtil.bufferToHex(encodedData); + const encodedReceiverData = encodedAssetData.slice( + receiverDataOffset, + receiverDataOffset + receiverDataLength.toNumber(), + ); + receiverData = ethUtil.bufferToHex(encodedReceiverData); } const erc721AssetData: ERC721AssetData = { assetProxyId, tokenAddress, tokenId, - data, + receiverData, }; return erc721AssetData; }, diff --git a/packages/order-utils/src/order_state_utils.ts b/packages/order-utils/src/order_state_utils.ts index ca18097c9..12f5d8f7e 100644 --- a/packages/order-utils/src/order_state_utils.ts +++ b/packages/order-utils/src/order_state_utils.ts @@ -111,8 +111,8 @@ export class OrderStateUtils { const transferrableMakerAssetAmount = BigNumber.min([makerProxyAllowance, makerBalance]); const transferrableFeeAssetAmount = BigNumber.min([makerFeeProxyAllowance, makerFeeBalance]); - const zrxAssetData = assetProxyUtils.encodeERC20ProxyData(zrxTokenAddress); - const isMakerAssetZRX = signedOrder.makerAssetData === zrxAssetData; + const zrxAssetData = assetProxyUtils.encodeERC20AssetData(zrxTokenAddress); + const isMakerTokenZRX = signedOrder.makerAssetData === zrxAssetData; const remainingFillableCalculator = new RemainingFillableCalculator( signedOrder.makerFee, signedOrder.makerAssetAmount, -- cgit v1.2.3 From 774d831fae5809408f9ddfcf9393d579416b1bfb Mon Sep 17 00:00:00 2001 From: Greg Hysen Date: Mon, 4 Jun 2018 22:34:04 -0700 Subject: Style updates to ERC721 onReceiver --- packages/order-utils/src/asset_proxy_utils.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/asset_proxy_utils.ts b/packages/order-utils/src/asset_proxy_utils.ts index 61a9b12e9..c7b301c1a 100644 --- a/packages/order-utils/src/asset_proxy_utils.ts +++ b/packages/order-utils/src/asset_proxy_utils.ts @@ -119,10 +119,12 @@ export const assetProxyUtils = { const tokenId = assetProxyUtils.decodeUint256(encodedTokenId); const nullData = '0x'; let receiverData = nullData; - if (encodedAssetData.byteLength > receiverDataLengthOffset + 1) { + const lengthUpToReceiverDataLength = receiverDataLengthOffset + 1; + if (encodedAssetData.byteLength > lengthUpToReceiverDataLength) { const encodedReceiverDataLength = encodedAssetData.slice(receiverDataLengthOffset, receiverDataOffset); const receiverDataLength = assetProxyUtils.decodeUint256(encodedReceiverDataLength); - const expectedReceiverDataLength = new BigNumber(encodedAssetData.byteLength - (receiverDataOffset + 1)); + const lengthUpToReceiverData = receiverDataOffset + 1; + const expectedReceiverDataLength = new BigNumber(encodedAssetData.byteLength - lengthUpToReceiverData); if (!receiverDataLength.equals(expectedReceiverDataLength)) { throw new Error( `Data length (${receiverDataLength}) does not match actual length of data (${expectedReceiverDataLength})`, @@ -167,12 +169,12 @@ export const assetProxyUtils = { return generalizedERC20AssetData; case AssetProxyId.ERC721: const erc721AssetData = assetProxyUtils.decodeERC721AssetData(assetData); - const generaliedERC721AssetData = { + const generalizedERC721AssetData = { assetProxyId, tokenAddress: erc721AssetData.tokenAddress, data: erc721AssetData.tokenId, }; - return generaliedERC721AssetData; + return generalizedERC721AssetData; default: throw new Error(`Unrecognized asset proxy id: ${assetProxyId}`); } -- cgit v1.2.3 From db086de84ae7a238b91b5ce79fcc1a8e4c830ac5 Mon Sep 17 00:00:00 2001 From: Greg Hysen Date: Wed, 6 Jun 2018 17:14:13 -0700 Subject: Union types for generalized decodeAssetData --- packages/order-utils/src/asset_proxy_utils.ts | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/asset_proxy_utils.ts b/packages/order-utils/src/asset_proxy_utils.ts index c7b301c1a..1d34172c7 100644 --- a/packages/order-utils/src/asset_proxy_utils.ts +++ b/packages/order-utils/src/asset_proxy_utils.ts @@ -1,4 +1,4 @@ -import { AssetData, AssetProxyId, ERC20AssetData, ERC721AssetData } from '@0xproject/types'; +import { AssetProxyId, ERC20AssetData, ERC721AssetData } from '@0xproject/types'; import { BigNumber } from '@0xproject/utils'; import BN = require('bn.js'); import ethUtil = require('ethereumjs-util'); @@ -157,24 +157,15 @@ export const assetProxyUtils = { const assetProxyId = assetProxyUtils.decodeAssetProxyId(encodedAssetProxyId); return assetProxyId; }, - decodeAssetData(assetData: string): AssetData { + decodeAssetData(assetData: string): ERC20AssetData | ERC721AssetData { const assetProxyId = assetProxyUtils.decodeAssetDataId(assetData); switch (assetProxyId) { case AssetProxyId.ERC20: const erc20AssetData = assetProxyUtils.decodeERC20AssetData(assetData); - const generalizedERC20AssetData = { - assetProxyId, - tokenAddress: erc20AssetData.tokenAddress, - }; - return generalizedERC20AssetData; + return erc20AssetData; case AssetProxyId.ERC721: const erc721AssetData = assetProxyUtils.decodeERC721AssetData(assetData); - const generalizedERC721AssetData = { - assetProxyId, - tokenAddress: erc721AssetData.tokenAddress, - data: erc721AssetData.tokenId, - }; - return generalizedERC721AssetData; + return erc721AssetData; default: throw new Error(`Unrecognized asset proxy id: ${assetProxyId}`); } -- cgit v1.2.3 From f457a56d4a0a4e5a5b5b11289f65df64cf2c7f1f Mon Sep 17 00:00:00 2001 From: Greg Hysen Date: Thu, 7 Jun 2018 11:11:40 -0700 Subject: Style updates to contracts --- packages/order-utils/src/asset_proxy_utils.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/asset_proxy_utils.ts b/packages/order-utils/src/asset_proxy_utils.ts index 1d34172c7..ed8832b18 100644 --- a/packages/order-utils/src/asset_proxy_utils.ts +++ b/packages/order-utils/src/asset_proxy_utils.ts @@ -4,6 +4,8 @@ import BN = require('bn.js'); import ethUtil = require('ethereumjs-util'); import * as _ from 'lodash'; +import { constants } from '../../src/utils/constants'; + const ERC20_ASSET_DATA_BYTE_LENGTH = 21; const ERC721_ASSET_DATA_BYTE_LENGTH = 53; @@ -117,8 +119,7 @@ export const assetProxyUtils = { const tokenAddress = assetProxyUtils.decodeAddress(encodedTokenAddress); const encodedTokenId = encodedAssetData.slice(tokenIdOffset, receiverDataLengthOffset); const tokenId = assetProxyUtils.decodeUint256(encodedTokenId); - const nullData = '0x'; - let receiverData = nullData; + let receiverData = constants.NULL_BYTE; const lengthUpToReceiverDataLength = receiverDataLengthOffset + 1; if (encodedAssetData.byteLength > lengthUpToReceiverDataLength) { const encodedReceiverDataLength = encodedAssetData.slice(receiverDataLengthOffset, receiverDataOffset); -- cgit v1.2.3 From f0200ab69722a7913671f3e59ab650da1e77d6ef Mon Sep 17 00:00:00 2001 From: Greg Hysen Date: Thu, 7 Jun 2018 11:21:31 -0700 Subject: Moved some constants to global scope in assetProxyUtils --- packages/order-utils/src/asset_proxy_utils.ts | 44 ++++++++++++++++----------- 1 file changed, 26 insertions(+), 18 deletions(-) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/asset_proxy_utils.ts b/packages/order-utils/src/asset_proxy_utils.ts index ed8832b18..e2b377899 100644 --- a/packages/order-utils/src/asset_proxy_utils.ts +++ b/packages/order-utils/src/asset_proxy_utils.ts @@ -1,13 +1,15 @@ import { AssetProxyId, ERC20AssetData, ERC721AssetData } from '@0xproject/types'; -import { BigNumber } from '@0xproject/utils'; +import { BigNumber, NULL_BYTES } from '@0xproject/utils'; import BN = require('bn.js'); import ethUtil = require('ethereumjs-util'); import * as _ from 'lodash'; -import { constants } from '../../src/utils/constants'; - const ERC20_ASSET_DATA_BYTE_LENGTH = 21; const ERC721_ASSET_DATA_BYTE_LENGTH = 53; +const ASSET_DATA_ADDRESS_OFFSET = 0; +const ERC721_ASSET_DATA_TOKEN_ID_OFFSET = 20; +const ERC721_ASSET_DATA_RECEIVER_DATA_LENGTH_OFFSET = 52; +const ERC721_ASSET_DATA_RECEIVER_DATA_OFFSET = 84; export const assetProxyUtils = { encodeAssetProxyId(assetProxyId: AssetProxyId): Buffer { @@ -59,7 +61,8 @@ export const assetProxyUtils = { }`, ); } - const encodedAssetProxyId = encodedAssetData.slice(-1); + const assetProxyIdOffset = encodedAssetData.byteLength - 1; + const encodedAssetProxyId = encodedAssetData.slice(assetProxyIdOffset); const assetProxyId = assetProxyUtils.decodeAssetProxyId(encodedAssetProxyId); if (assetProxyId !== AssetProxyId.ERC20) { throw new Error( @@ -68,8 +71,7 @@ export const assetProxyUtils = { }), but got ${assetProxyId}`, ); } - const addressOffset = ERC20_ASSET_DATA_BYTE_LENGTH - 1; - const encodedTokenAddress = encodedAssetData.slice(0, addressOffset); + const encodedTokenAddress = encodedAssetData.slice(ASSET_DATA_ADDRESS_OFFSET, assetProxyIdOffset); const tokenAddress = assetProxyUtils.decodeAddress(encodedTokenAddress); const erc20AssetData = { assetProxyId, @@ -101,11 +103,11 @@ export const assetProxyUtils = { }`, ); } - const addressOffset = 0; - const tokenIdOffset = 20; - const receiverDataLengthOffset = 52; - const receiverDataOffset = 84; - const encodedTokenAddress = encodedAssetData.slice(addressOffset, tokenIdOffset); + + const encodedTokenAddress = encodedAssetData.slice( + ASSET_DATA_ADDRESS_OFFSET, + ERC721_ASSET_DATA_TOKEN_ID_OFFSET, + ); const proxyIdOffset = encodedAssetData.byteLength - 1; const encodedAssetProxyId = encodedAssetData.slice(-1); const assetProxyId = assetProxyUtils.decodeAssetProxyId(encodedAssetProxyId); @@ -117,14 +119,20 @@ export const assetProxyUtils = { ); } const tokenAddress = assetProxyUtils.decodeAddress(encodedTokenAddress); - const encodedTokenId = encodedAssetData.slice(tokenIdOffset, receiverDataLengthOffset); + const encodedTokenId = encodedAssetData.slice( + ERC721_ASSET_DATA_TOKEN_ID_OFFSET, + ERC721_ASSET_DATA_RECEIVER_DATA_LENGTH_OFFSET, + ); const tokenId = assetProxyUtils.decodeUint256(encodedTokenId); - let receiverData = constants.NULL_BYTE; - const lengthUpToReceiverDataLength = receiverDataLengthOffset + 1; + let receiverData = NULL_BYTES; + const lengthUpToReceiverDataLength = ERC721_ASSET_DATA_RECEIVER_DATA_LENGTH_OFFSET + 1; if (encodedAssetData.byteLength > lengthUpToReceiverDataLength) { - const encodedReceiverDataLength = encodedAssetData.slice(receiverDataLengthOffset, receiverDataOffset); + const encodedReceiverDataLength = encodedAssetData.slice( + ERC721_ASSET_DATA_RECEIVER_DATA_LENGTH_OFFSET, + ERC721_ASSET_DATA_RECEIVER_DATA_OFFSET, + ); const receiverDataLength = assetProxyUtils.decodeUint256(encodedReceiverDataLength); - const lengthUpToReceiverData = receiverDataOffset + 1; + const lengthUpToReceiverData = ERC721_ASSET_DATA_RECEIVER_DATA_OFFSET + 1; const expectedReceiverDataLength = new BigNumber(encodedAssetData.byteLength - lengthUpToReceiverData); if (!receiverDataLength.equals(expectedReceiverDataLength)) { throw new Error( @@ -132,8 +140,8 @@ export const assetProxyUtils = { ); } const encodedReceiverData = encodedAssetData.slice( - receiverDataOffset, - receiverDataOffset + receiverDataLength.toNumber(), + ERC721_ASSET_DATA_RECEIVER_DATA_OFFSET, + ERC721_ASSET_DATA_RECEIVER_DATA_OFFSET + receiverDataLength.toNumber(), ); receiverData = ethUtil.bufferToHex(encodedReceiverData); } -- cgit v1.2.3 From 5bb7219f4b8d5ce22169d5139bd1c07d7b2fcafd Mon Sep 17 00:00:00 2001 From: Greg Hysen Date: Thu, 7 Jun 2018 11:43:17 -0700 Subject: Camelcase in memCopy --- packages/order-utils/src/asset_proxy_utils.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/asset_proxy_utils.ts b/packages/order-utils/src/asset_proxy_utils.ts index e2b377899..ee5fff1d2 100644 --- a/packages/order-utils/src/asset_proxy_utils.ts +++ b/packages/order-utils/src/asset_proxy_utils.ts @@ -5,7 +5,7 @@ import ethUtil = require('ethereumjs-util'); import * as _ from 'lodash'; const ERC20_ASSET_DATA_BYTE_LENGTH = 21; -const ERC721_ASSET_DATA_BYTE_LENGTH = 53; +const ERC721_ASSET_DATA_MINIMUM_BYTE_LENGTH = 53; const ASSET_DATA_ADDRESS_OFFSET = 0; const ERC721_ASSET_DATA_TOKEN_ID_OFFSET = 20; const ERC721_ASSET_DATA_RECEIVER_DATA_LENGTH_OFFSET = 52; @@ -96,7 +96,7 @@ export const assetProxyUtils = { }, decodeERC721AssetData(assetData: string): ERC721AssetData { const encodedAssetData = ethUtil.toBuffer(assetData); - if (encodedAssetData.byteLength < ERC721_ASSET_DATA_BYTE_LENGTH) { + if (encodedAssetData.byteLength < ERC721_ASSET_DATA_MINIMUM_BYTE_LENGTH) { throw new Error( `Could not decode ERC20 Proxy Data. Expected length of encoded data to be at least 53. Got ${ encodedAssetData.byteLength -- cgit v1.2.3 From d62ff34a5a5794a586c0b4bbf27c51ea36efd659 Mon Sep 17 00:00:00 2001 From: Greg Hysen Date: Thu, 7 Jun 2018 15:53:30 -0700 Subject: Cleanup after last rebase --- packages/order-utils/src/order_state_utils.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/order_state_utils.ts b/packages/order-utils/src/order_state_utils.ts index 12f5d8f7e..40f235da7 100644 --- a/packages/order-utils/src/order_state_utils.ts +++ b/packages/order-utils/src/order_state_utils.ts @@ -79,7 +79,7 @@ export class OrderStateUtils { } public async getOrderRelevantStateAsync(signedOrder: SignedOrder): Promise { const zrxTokenAddress = this._orderFilledCancelledFetcher.getZRXTokenAddress(); - const makerProxyData = assetProxyUtils.decodeERC20ProxyData(signedOrder.makerAssetData); + const makerProxyData = assetProxyUtils.decodeERC20AssetData(signedOrder.makerAssetData); const makerAssetAddress = makerProxyData.tokenAddress; const orderHash = orderHashUtils.getOrderHashHex(signedOrder); const makerBalance = await this._balanceAndProxyAllowanceFetcher.getBalanceAsync( @@ -112,7 +112,7 @@ export class OrderStateUtils { const transferrableFeeAssetAmount = BigNumber.min([makerFeeProxyAllowance, makerFeeBalance]); const zrxAssetData = assetProxyUtils.encodeERC20AssetData(zrxTokenAddress); - const isMakerTokenZRX = signedOrder.makerAssetData === zrxAssetData; + const isMakerAssetZRX = signedOrder.makerAssetData === zrxAssetData; const remainingFillableCalculator = new RemainingFillableCalculator( signedOrder.makerFee, signedOrder.makerAssetAmount, -- cgit v1.2.3 From c39301b6da9f51ebccf11f06865c439ffed7f8f6 Mon Sep 17 00:00:00 2001 From: Greg Hysen Date: Fri, 8 Jun 2018 11:04:07 -0700 Subject: Fixed assetProxyUtils for linter --- packages/order-utils/src/asset_proxy_utils.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/asset_proxy_utils.ts b/packages/order-utils/src/asset_proxy_utils.ts index ee5fff1d2..915ee5032 100644 --- a/packages/order-utils/src/asset_proxy_utils.ts +++ b/packages/order-utils/src/asset_proxy_utils.ts @@ -109,7 +109,7 @@ export const assetProxyUtils = { ERC721_ASSET_DATA_TOKEN_ID_OFFSET, ); const proxyIdOffset = encodedAssetData.byteLength - 1; - const encodedAssetProxyId = encodedAssetData.slice(-1); + const encodedAssetProxyId = encodedAssetData.slice(proxyIdOffset); const assetProxyId = assetProxyUtils.decodeAssetProxyId(encodedAssetProxyId); if (assetProxyId !== AssetProxyId.ERC721) { throw new Error( @@ -141,7 +141,7 @@ export const assetProxyUtils = { } const encodedReceiverData = encodedAssetData.slice( ERC721_ASSET_DATA_RECEIVER_DATA_OFFSET, - ERC721_ASSET_DATA_RECEIVER_DATA_OFFSET + receiverDataLength.toNumber(), + receiverDataLength.add(ERC721_ASSET_DATA_RECEIVER_DATA_OFFSET).toNumber(), ); receiverData = ethUtil.bufferToHex(encodedReceiverData); } -- cgit v1.2.3 From e4afe603f9c4dd5128f2446f9fe075516a3d4894 Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Mon, 11 Jun 2018 19:15:41 +0200 Subject: export parseECSignature method --- packages/order-utils/src/index.ts | 1 + 1 file changed, 1 insertion(+) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/index.ts b/packages/order-utils/src/index.ts index cb859dcb9..9e78c6b93 100644 --- a/packages/order-utils/src/index.ts +++ b/packages/order-utils/src/index.ts @@ -7,6 +7,7 @@ export { isValidECSignature, ecSignOrderHashAsync, addSignedMessagePrefix, + parseECSignature, } from './signature_utils'; export { orderFactory } from './order_factory'; export { constants } from './constants'; -- cgit v1.2.3 From 21f7722f1023cc9d1848737b7c986f7df7a07122 Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Mon, 11 Jun 2018 19:21:32 +0200 Subject: Move OrderValidationUtils (+ tests) and ExchangeTransferSimulator to order-utils --- ...abstract_balance_and_proxy_allowance_fetcher.ts | 4 +- ...tract_balance_and_proxy_allowance_lazy_store.ts | 11 + packages/order-utils/src/artifacts.ts | 12 +- packages/order-utils/src/constants.ts | 5 + .../order-utils/src/exchange_transfer_simulator.ts | 114 +++++++++++ packages/order-utils/src/index.ts | 2 + packages/order-utils/src/order_validation_utils.ts | 223 +++++++++++++++++++++ packages/order-utils/src/signature_utils.ts | 25 ++- .../balance_and_proxy_allowance_lazy_store.ts | 82 ++++++++ packages/order-utils/src/types.ts | 10 + packages/order-utils/src/utils.ts | 6 + 11 files changed, 478 insertions(+), 16 deletions(-) create mode 100644 packages/order-utils/src/abstract/abstract_balance_and_proxy_allowance_lazy_store.ts create mode 100644 packages/order-utils/src/exchange_transfer_simulator.ts create mode 100644 packages/order-utils/src/order_validation_utils.ts create mode 100644 packages/order-utils/src/store/balance_and_proxy_allowance_lazy_store.ts (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/abstract/abstract_balance_and_proxy_allowance_fetcher.ts b/packages/order-utils/src/abstract/abstract_balance_and_proxy_allowance_fetcher.ts index 857c6167f..b2760d98e 100644 --- a/packages/order-utils/src/abstract/abstract_balance_and_proxy_allowance_fetcher.ts +++ b/packages/order-utils/src/abstract/abstract_balance_and_proxy_allowance_fetcher.ts @@ -1,6 +1,6 @@ import { BigNumber } from '@0xproject/utils'; export abstract class AbstractBalanceAndProxyAllowanceFetcher { - public abstract async getBalanceAsync(tokenAddress: string, userAddress: string): Promise; - public abstract async getProxyAllowanceAsync(tokenAddress: string, userAddress: string): Promise; + public abstract async getBalanceAsync(assetData: string, userAddress: string): Promise; + public abstract async getProxyAllowanceAsync(assetData: string, userAddress: string): Promise; } diff --git a/packages/order-utils/src/abstract/abstract_balance_and_proxy_allowance_lazy_store.ts b/packages/order-utils/src/abstract/abstract_balance_and_proxy_allowance_lazy_store.ts new file mode 100644 index 000000000..38e08b7fe --- /dev/null +++ b/packages/order-utils/src/abstract/abstract_balance_and_proxy_allowance_lazy_store.ts @@ -0,0 +1,11 @@ +import { BigNumber } from '@0xproject/utils'; + +export abstract class AbstractBalanceAndProxyAllowanceLazyStore { + public abstract async getBalanceAsync(assetData: string, userAddress: string): Promise; + public abstract async getProxyAllowanceAsync(assetData: string, userAddress: string): Promise; + public abstract setBalance(assetData: string, userAddress: string, balance: BigNumber): void; + public abstract deleteBalance(assetData: string, userAddress: string): void; + public abstract setProxyAllowance(assetData: string, userAddress: string, proxyAllowance: BigNumber): void; + public abstract deleteProxyAllowance(assetData: string, userAddress: string): void; + public abstract deleteAll(): void; +} diff --git a/packages/order-utils/src/artifacts.ts b/packages/order-utils/src/artifacts.ts index f6fd00472..3d2d1e953 100644 --- a/packages/order-utils/src/artifacts.ts +++ b/packages/order-utils/src/artifacts.ts @@ -1,10 +1,14 @@ -import { Artifact } from '@0xproject/types'; +import { ContractArtifact } from '@0xproject/sol-compiler'; +import * as DummyERC20Token from './artifacts/DummyERC20Token.json'; +import * as ERC20Proxy from './artifacts/ERC20Proxy.json'; import * as Exchange from './artifacts/Exchange.json'; import * as IValidator from './artifacts/IValidator.json'; import * as IWallet from './artifacts/IWallet.json'; export const artifacts = { - Exchange: (Exchange as any) as Artifact, - IWallet: (IWallet as any) as Artifact, - IValidator: (IValidator as any) as Artifact, + ERC20Proxy: (ERC20Proxy as any) as ContractArtifact, + DummyERC20Token: (DummyERC20Token as any) as ContractArtifact, + Exchange: (Exchange as any) as ContractArtifact, + IWallet: (IWallet as any) as ContractArtifact, + IValidator: (IValidator as any) as ContractArtifact, }; diff --git a/packages/order-utils/src/constants.ts b/packages/order-utils/src/constants.ts index ec2fe744a..ed5bd8101 100644 --- a/packages/order-utils/src/constants.ts +++ b/packages/order-utils/src/constants.ts @@ -1,3 +1,8 @@ +import { BigNumber } from '@0xproject/utils'; + export const constants = { NULL_ADDRESS: '0x0000000000000000000000000000000000000000', + // tslint:disable-next-line:custom-no-magic-numbers + UNLIMITED_ALLOWANCE_IN_BASE_UNITS: new BigNumber(2).pow(256).minus(1), + TESTRPC_NETWORK_ID: 50, }; diff --git a/packages/order-utils/src/exchange_transfer_simulator.ts b/packages/order-utils/src/exchange_transfer_simulator.ts new file mode 100644 index 000000000..1cb132aba --- /dev/null +++ b/packages/order-utils/src/exchange_transfer_simulator.ts @@ -0,0 +1,114 @@ +import { ExchangeContractErrs } from '@0xproject/types'; +import { BigNumber } from '@0xproject/utils'; +import { BlockParamLiteral } from 'ethereum-types'; + +import { AbstractBalanceAndProxyAllowanceLazyStore } from './abstract/abstract_balance_and_proxy_allowance_lazy_store'; +import { constants } from './constants'; +import { TradeSide, TransferType } from './types'; + +enum FailureReason { + Balance = 'balance', + ProxyAllowance = 'proxyAllowance', +} + +const ERR_MSG_MAPPING = { + [FailureReason.Balance]: { + [TradeSide.Maker]: { + [TransferType.Trade]: ExchangeContractErrs.InsufficientMakerBalance, + [TransferType.Fee]: ExchangeContractErrs.InsufficientMakerFeeBalance, + }, + [TradeSide.Taker]: { + [TransferType.Trade]: ExchangeContractErrs.InsufficientTakerBalance, + [TransferType.Fee]: ExchangeContractErrs.InsufficientTakerFeeBalance, + }, + }, + [FailureReason.ProxyAllowance]: { + [TradeSide.Maker]: { + [TransferType.Trade]: ExchangeContractErrs.InsufficientMakerAllowance, + [TransferType.Fee]: ExchangeContractErrs.InsufficientMakerFeeAllowance, + }, + [TradeSide.Taker]: { + [TransferType.Trade]: ExchangeContractErrs.InsufficientTakerAllowance, + [TransferType.Fee]: ExchangeContractErrs.InsufficientTakerFeeAllowance, + }, + }, +}; + +export class ExchangeTransferSimulator { + private _store: AbstractBalanceAndProxyAllowanceLazyStore; + private static _throwValidationError( + failureReason: FailureReason, + tradeSide: TradeSide, + transferType: TransferType, + ): never { + const errMsg = ERR_MSG_MAPPING[failureReason][tradeSide][transferType]; + throw new Error(errMsg); + } + constructor(store: AbstractBalanceAndProxyAllowanceLazyStore) { + this._store = store; + } + /** + * Simulates transferFrom call performed by a proxy + * @param assetData Data of the asset being transferred. Includes + * it's identifying information and assetType, + * e.g address for ERC20, address & tokenId for ERC721 + * @param from Owner of the transferred tokens + * @param to Recipient of the transferred tokens + * @param amountInBaseUnits The amount of tokens being transferred + * @param tradeSide Is Maker/Taker transferring + * @param transferType Is it a fee payment or a value transfer + */ + public async transferFromAsync( + assetData: string, + from: string, + to: string, + amountInBaseUnits: BigNumber, + tradeSide: TradeSide, + transferType: TransferType, + ): Promise { + // HACK: When simulating an open order (e.g taker is NULL_ADDRESS), we don't want to adjust balances/ + // allowances for the taker. We do however, want to increase the balance of the maker since the maker + // might be relying on those funds to fill subsequent orders or pay the order's fees. + if (from === constants.NULL_ADDRESS && tradeSide === TradeSide.Taker) { + await this._increaseBalanceAsync(assetData, to, amountInBaseUnits); + return; + } + const balance = await this._store.getBalanceAsync(assetData, from); + const proxyAllowance = await this._store.getProxyAllowanceAsync(assetData, from); + if (proxyAllowance.lessThan(amountInBaseUnits)) { + ExchangeTransferSimulator._throwValidationError(FailureReason.ProxyAllowance, tradeSide, transferType); + } + if (balance.lessThan(amountInBaseUnits)) { + ExchangeTransferSimulator._throwValidationError(FailureReason.Balance, tradeSide, transferType); + } + await this._decreaseProxyAllowanceAsync(assetData, from, amountInBaseUnits); + await this._decreaseBalanceAsync(assetData, from, amountInBaseUnits); + await this._increaseBalanceAsync(assetData, to, amountInBaseUnits); + } + private async _decreaseProxyAllowanceAsync( + assetData: string, + userAddress: string, + amountInBaseUnits: BigNumber, + ): Promise { + const proxyAllowance = await this._store.getProxyAllowanceAsync(assetData, userAddress); + if (!proxyAllowance.eq(constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS)) { + this._store.setProxyAllowance(assetData, userAddress, proxyAllowance.minus(amountInBaseUnits)); + } + } + private async _increaseBalanceAsync( + assetData: string, + userAddress: string, + amountInBaseUnits: BigNumber, + ): Promise { + const balance = await this._store.getBalanceAsync(assetData, userAddress); + this._store.setBalance(assetData, userAddress, balance.plus(amountInBaseUnits)); + } + private async _decreaseBalanceAsync( + assetData: string, + userAddress: string, + amountInBaseUnits: BigNumber, + ): Promise { + const balance = await this._store.getBalanceAsync(assetData, userAddress); + this._store.setBalance(assetData, userAddress, balance.minus(amountInBaseUnits)); + } +} diff --git a/packages/order-utils/src/index.ts b/packages/order-utils/src/index.ts index 9e78c6b93..f9b37df82 100644 --- a/packages/order-utils/src/index.ts +++ b/packages/order-utils/src/index.ts @@ -19,3 +19,5 @@ export { AbstractOrderFilledCancelledFetcher } from './abstract/abstract_order_f export { RemainingFillableCalculator } from './remaining_fillable_calculator'; export { OrderStateUtils } from './order_state_utils'; export { assetProxyUtils } from './asset_proxy_utils'; +export { OrderValidationUtils } from './order_validation_utils'; +export { ExchangeTransferSimulator } from './exchange_transfer_simulator'; diff --git a/packages/order-utils/src/order_validation_utils.ts b/packages/order-utils/src/order_validation_utils.ts new file mode 100644 index 000000000..4280e4d97 --- /dev/null +++ b/packages/order-utils/src/order_validation_utils.ts @@ -0,0 +1,223 @@ +import { ExchangeContractErrs, Order, SignedOrder } from '@0xproject/types'; +import { BigNumber } from '@0xproject/utils'; +import * as _ from 'lodash'; + +import { OrderError, TradeSide, TransferType } from './types'; + +import { constants } from './constants'; +import { ExchangeTransferSimulator } from './exchange_transfer_simulator'; +import { ExchangeContract } from './generated_contract_wrappers/exchange'; +import { orderHashUtils } from './order_hash'; +import { isValidECSignature, parseECSignature } from './signature_utils'; +import { utils } from './utils'; + +export class OrderValidationUtils { + private _exchangeContract: ExchangeContract; + // TODO: Write some tests for the function + // const numerator = new BigNumber(20); + // const denominator = new BigNumber(999); + // const target = new BigNumber(50); + // rounding error = ((20*50/999) - floor(20*50/999)) / (20*50/999) = 0.1% + public static isRoundingError(numerator: BigNumber, denominator: BigNumber, target: BigNumber): boolean { + // Solidity's mulmod() in JS + // Source: https://solidity.readthedocs.io/en/latest/units-and-global-variables.html#mathematical-and-cryptographic-functions + if (denominator.eq(0)) { + throw new Error('denominator cannot be 0'); + } + const remainder = target.mul(numerator).mod(denominator); + if (remainder.eq(0)) { + return false; // no rounding error + } + + // tslint:disable-next-line:custom-no-magic-numbers + const errPercentageTimes1000000 = remainder.mul(1000000).div(numerator.mul(target)); + // tslint:disable-next-line:custom-no-magic-numbers + const isError = errPercentageTimes1000000.gt(1000); + return isError; + } + public static validateCancelOrderThrowIfInvalid( + order: Order, + cancelTakerTokenAmount: BigNumber, + filledTakerTokenAmount: BigNumber, + ): void { + if (cancelTakerTokenAmount.eq(0)) { + throw new Error(ExchangeContractErrs.OrderCancelAmountZero); + } + if (order.takerAssetAmount.eq(filledTakerTokenAmount)) { + throw new Error(ExchangeContractErrs.OrderAlreadyCancelledOrFilled); + } + const currentUnixTimestampSec = utils.getCurrentUnixTimestampSec(); + if (order.expirationTimeSeconds.lessThan(currentUnixTimestampSec)) { + throw new Error(ExchangeContractErrs.OrderCancelExpired); + } + } + public static async validateFillOrderBalancesAllowancesThrowIfInvalidAsync( + exchangeTradeEmulator: ExchangeTransferSimulator, + signedOrder: SignedOrder, + fillTakerTokenAmount: BigNumber, + senderAddress: string, + zrxTokenAddress: string, + ): Promise { + const fillMakerTokenAmount = OrderValidationUtils._getPartialAmount( + fillTakerTokenAmount, + signedOrder.takerAssetAmount, + signedOrder.makerAssetAmount, + ); + await exchangeTradeEmulator.transferFromAsync( + signedOrder.makerAssetData, + signedOrder.makerAddress, + senderAddress, + fillMakerTokenAmount, + TradeSide.Maker, + TransferType.Trade, + ); + await exchangeTradeEmulator.transferFromAsync( + signedOrder.takerAssetData, + senderAddress, + signedOrder.makerAddress, + fillTakerTokenAmount, + TradeSide.Taker, + TransferType.Trade, + ); + const makerFeeAmount = OrderValidationUtils._getPartialAmount( + fillTakerTokenAmount, + signedOrder.takerAssetAmount, + signedOrder.makerFee, + ); + await exchangeTradeEmulator.transferFromAsync( + zrxTokenAddress, + signedOrder.makerAddress, + signedOrder.feeRecipientAddress, + makerFeeAmount, + TradeSide.Maker, + TransferType.Fee, + ); + const takerFeeAmount = OrderValidationUtils._getPartialAmount( + fillTakerTokenAmount, + signedOrder.takerAssetAmount, + signedOrder.takerFee, + ); + await exchangeTradeEmulator.transferFromAsync( + zrxTokenAddress, + senderAddress, + signedOrder.feeRecipientAddress, + takerFeeAmount, + TradeSide.Taker, + TransferType.Fee, + ); + } + private static _validateRemainingFillAmountNotZeroOrThrow( + takerAssetAmount: BigNumber, + filledTakerTokenAmount: BigNumber, + ): void { + if (takerAssetAmount.eq(filledTakerTokenAmount)) { + throw new Error(ExchangeContractErrs.OrderRemainingFillAmountZero); + } + } + private static _validateOrderNotExpiredOrThrow(expirationTimeSeconds: BigNumber): void { + const currentUnixTimestampSec = utils.getCurrentUnixTimestampSec(); + if (expirationTimeSeconds.lessThan(currentUnixTimestampSec)) { + throw new Error(ExchangeContractErrs.OrderFillExpired); + } + } + private static _getPartialAmount(numerator: BigNumber, denominator: BigNumber, target: BigNumber): BigNumber { + const fillMakerTokenAmount = numerator + .mul(target) + .div(denominator) + .round(0); + return fillMakerTokenAmount; + } + constructor(exchangeContract: ExchangeContract) { + this._exchangeContract = exchangeContract; + } + public async validateOrderFillableOrThrowAsync( + exchangeTradeEmulator: ExchangeTransferSimulator, + signedOrder: SignedOrder, + zrxTokenAddress: string, + expectedFillTakerTokenAmount?: BigNumber, + ): Promise { + const orderHash = orderHashUtils.getOrderHashHex(signedOrder); + const filledTakerTokenAmount = await this._exchangeContract.filled.callAsync(orderHash); + OrderValidationUtils._validateRemainingFillAmountNotZeroOrThrow( + signedOrder.takerAssetAmount, + filledTakerTokenAmount, + ); + OrderValidationUtils._validateOrderNotExpiredOrThrow(signedOrder.expirationTimeSeconds); + let fillTakerTokenAmount = signedOrder.takerAssetAmount.minus(filledTakerTokenAmount); + if (!_.isUndefined(expectedFillTakerTokenAmount)) { + fillTakerTokenAmount = expectedFillTakerTokenAmount; + } + await OrderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync( + exchangeTradeEmulator, + signedOrder, + fillTakerTokenAmount, + signedOrder.takerAddress, + zrxTokenAddress, + ); + } + public async validateFillOrderThrowIfInvalidAsync( + exchangeTradeEmulator: ExchangeTransferSimulator, + signedOrder: SignedOrder, + fillTakerTokenAmount: BigNumber, + takerAddress: string, + zrxTokenAddress: string, + ): Promise { + if (fillTakerTokenAmount.eq(0)) { + throw new Error(ExchangeContractErrs.OrderFillAmountZero); + } + const orderHash = orderHashUtils.getOrderHashHex(signedOrder); + // TODO: Verify all signature types! To do this, we need access to a Provider... + const ecSignature = parseECSignature(signedOrder.signature); + if (!isValidECSignature(orderHash, ecSignature, signedOrder.makerAddress)) { + throw new Error(OrderError.InvalidSignature); + } + const filledTakerTokenAmount = await this._exchangeContract.filled.callAsync(orderHash); + OrderValidationUtils._validateRemainingFillAmountNotZeroOrThrow( + signedOrder.takerAssetAmount, + filledTakerTokenAmount, + ); + if (signedOrder.takerAddress !== constants.NULL_ADDRESS && signedOrder.takerAddress !== takerAddress) { + throw new Error(ExchangeContractErrs.TransactionSenderIsNotFillOrderTaker); + } + OrderValidationUtils._validateOrderNotExpiredOrThrow(signedOrder.expirationTimeSeconds); + const remainingTakerTokenAmount = signedOrder.takerAssetAmount.minus(filledTakerTokenAmount); + const desiredFillTakerTokenAmount = remainingTakerTokenAmount.lessThan(fillTakerTokenAmount) + ? remainingTakerTokenAmount + : fillTakerTokenAmount; + await OrderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync( + exchangeTradeEmulator, + signedOrder, + desiredFillTakerTokenAmount, + takerAddress, + zrxTokenAddress, + ); + + const wouldRoundingErrorOccur = await OrderValidationUtils.isRoundingError( + filledTakerTokenAmount, + signedOrder.takerAssetAmount, + signedOrder.makerAssetAmount, + ); + if (wouldRoundingErrorOccur) { + throw new Error(ExchangeContractErrs.OrderFillRoundingError); + } + return filledTakerTokenAmount; + } + public async validateFillOrKillOrderThrowIfInvalidAsync( + exchangeTradeEmulator: ExchangeTransferSimulator, + signedOrder: SignedOrder, + fillTakerTokenAmount: BigNumber, + takerAddress: string, + zrxTokenAddress: string, + ): Promise { + const filledTakerTokenAmount = await this.validateFillOrderThrowIfInvalidAsync( + exchangeTradeEmulator, + signedOrder, + fillTakerTokenAmount, + takerAddress, + zrxTokenAddress, + ); + if (filledTakerTokenAmount !== fillTakerTokenAmount) { + throw new Error(ExchangeContractErrs.InsufficientRemainingFillAmount); + } + } +} diff --git a/packages/order-utils/src/signature_utils.ts b/packages/order-utils/src/signature_utils.ts index c3fa0b6a5..44a7203a0 100644 --- a/packages/order-utils/src/signature_utils.ts +++ b/packages/order-utils/src/signature_utils.ts @@ -90,7 +90,7 @@ export async function isValidPresignedSignatureAsync( data: string, signerAddress: string, ): Promise { - const exchangeContract = new ExchangeContract(artifacts.Exchange.abi, signerAddress, provider); + const exchangeContract = new ExchangeContract(artifacts.Exchange.compilerOutput.abi, signerAddress, provider); const isValid = await exchangeContract.preSigned.callAsync(data, signerAddress); return isValid; } @@ -110,7 +110,7 @@ export async function isValidWalletSignatureAsync( ): Promise { // tslint:disable-next-line:custom-no-magic-numbers const signatureWithoutType = signature.slice(-2); - const walletContract = new IWalletContract(artifacts.IWallet.abi, signerAddress, provider); + const walletContract = new IWalletContract(artifacts.IWallet.compilerOutput.abi, signerAddress, provider); const isValid = await walletContract.isValidSignature.callAsync(data, signatureWithoutType); return isValid; } @@ -129,7 +129,7 @@ export async function isValidValidatorSignatureAsync( signerAddress: string, ): Promise { const validatorSignature = parseValidatorSignature(signature); - const exchangeContract = new ExchangeContract(artifacts.Exchange.abi, signerAddress, provider); + const exchangeContract = new ExchangeContract(artifacts.Exchange.compilerOutput.abi, signerAddress, provider); const isValidatorApproved = await exchangeContract.allowedValidators.callAsync( signerAddress, validatorSignature.validatorAddress, @@ -138,7 +138,7 @@ export async function isValidValidatorSignatureAsync( throw new Error(`Validator ${validatorSignature.validatorAddress} was not pre-approved by ${signerAddress}.`); } - const validatorContract = new IValidatorContract(artifacts.IValidator.abi, signerAddress, provider); + const validatorContract = new IValidatorContract(artifacts.IValidator.compilerOutput.abi, signerAddress, provider); const isValid = await validatorContract.isValidSignature.callAsync( data, signerAddress, @@ -260,12 +260,12 @@ export function addSignedMessagePrefix(message: string, messagePrefixType: Messa } } -function hashTrezorPersonalMessage(message: Buffer): Buffer { - const prefix = ethUtil.toBuffer('\x19Ethereum Signed Message:\n' + String.fromCharCode(message.length)); - return ethUtil.sha3(Buffer.concat([prefix, message])); -} - -function parseECSignature(signature: string): ECSignature { +/** + * Parse a 0x protocol hex-encoded signature string into it's ECSignature components + * @param signature A hex encoded ecSignature 0x Protocol signature + * @return An ECSignature object with r,s,v parameters + */ +export function parseECSignature(signature: string): ECSignature { const ecSignatureTypes = [SignatureType.EthSign, SignatureType.EIP712, SignatureType.Trezor]; assert.isOneOfExpectedSignatureTypes(signature, ecSignatureTypes); @@ -276,6 +276,11 @@ function parseECSignature(signature: string): ECSignature { return ecSignature; } +function hashTrezorPersonalMessage(message: Buffer): Buffer { + const prefix = ethUtil.toBuffer('\x19Ethereum Signed Message:\n' + String.fromCharCode(message.length)); + return ethUtil.sha3(Buffer.concat([prefix, message])); +} + function parseValidatorSignature(signature: string): ValidatorSignature { assert.isOneOfExpectedSignatureTypes(signature, [SignatureType.Validator]); // tslint:disable:custom-no-magic-numbers diff --git a/packages/order-utils/src/store/balance_and_proxy_allowance_lazy_store.ts b/packages/order-utils/src/store/balance_and_proxy_allowance_lazy_store.ts new file mode 100644 index 000000000..b5bd2801a --- /dev/null +++ b/packages/order-utils/src/store/balance_and_proxy_allowance_lazy_store.ts @@ -0,0 +1,82 @@ +import { BigNumber } from '@0xproject/utils'; +import { BlockParamLiteral } from 'ethereum-types'; +import * as _ from 'lodash'; + +import { AbstractBalanceAndProxyAllowanceFetcher } from '../abstract/abstract_balance_and_proxy_allowance_fetcher'; +import { AbstractBalanceAndProxyAllowanceLazyStore } from '../abstract/abstract_balance_and_proxy_allowance_lazy_store'; + +/** + * Copy on read store for balances/proxyAllowances of tokens/accounts + */ +export class BalanceAndProxyAllowanceLazyStore implements AbstractBalanceAndProxyAllowanceLazyStore { + private _balanceAndProxyAllowanceFetcher: AbstractBalanceAndProxyAllowanceFetcher; + private _balance: { + [assetData: string]: { + [userAddress: string]: BigNumber; + }; + }; + private _proxyAllowance: { + [assetData: string]: { + [userAddress: string]: BigNumber; + }; + }; + constructor(token: AbstractBalanceAndProxyAllowanceFetcher) { + this._balanceAndProxyAllowanceFetcher = token; + this._balance = {}; + this._proxyAllowance = {}; + } + public async getBalanceAsync(assetData: string, userAddress: string): Promise { + if (_.isUndefined(this._balance[assetData]) || _.isUndefined(this._balance[assetData][userAddress])) { + const balance = await this._balanceAndProxyAllowanceFetcher.getBalanceAsync(assetData, userAddress); + this.setBalance(assetData, userAddress, balance); + } + const cachedBalance = this._balance[assetData][userAddress]; + return cachedBalance; + } + public setBalance(assetData: string, userAddress: string, balance: BigNumber): void { + if (_.isUndefined(this._balance[assetData])) { + this._balance[assetData] = {}; + } + this._balance[assetData][userAddress] = balance; + } + public deleteBalance(assetData: string, userAddress: string): void { + if (!_.isUndefined(this._balance[assetData])) { + delete this._balance[assetData][userAddress]; + if (_.isEmpty(this._balance[assetData])) { + delete this._balance[assetData]; + } + } + } + public async getProxyAllowanceAsync(assetData: string, userAddress: string): Promise { + if ( + _.isUndefined(this._proxyAllowance[assetData]) || + _.isUndefined(this._proxyAllowance[assetData][userAddress]) + ) { + const proxyAllowance = await this._balanceAndProxyAllowanceFetcher.getProxyAllowanceAsync( + assetData, + userAddress, + ); + this.setProxyAllowance(assetData, userAddress, proxyAllowance); + } + const cachedProxyAllowance = this._proxyAllowance[assetData][userAddress]; + return cachedProxyAllowance; + } + public setProxyAllowance(assetData: string, userAddress: string, proxyAllowance: BigNumber): void { + if (_.isUndefined(this._proxyAllowance[assetData])) { + this._proxyAllowance[assetData] = {}; + } + this._proxyAllowance[assetData][userAddress] = proxyAllowance; + } + public deleteProxyAllowance(assetData: string, userAddress: string): void { + if (!_.isUndefined(this._proxyAllowance[assetData])) { + delete this._proxyAllowance[assetData][userAddress]; + if (_.isEmpty(this._proxyAllowance[assetData])) { + delete this._proxyAllowance[assetData]; + } + } + } + public deleteAll(): void { + this._balance = {}; + this._proxyAllowance = {}; + } +} diff --git a/packages/order-utils/src/types.ts b/packages/order-utils/src/types.ts index db0bfb249..3f1fce66d 100644 --- a/packages/order-utils/src/types.ts +++ b/packages/order-utils/src/types.ts @@ -23,3 +23,13 @@ export interface MessagePrefixOpts { prefixType: MessagePrefixType; shouldAddPrefixBeforeCallingEthSign: boolean; } + +export enum TradeSide { + Maker = 'maker', + Taker = 'taker', +} + +export enum TransferType { + Trade = 'trade', + Fee = 'fee', +} diff --git a/packages/order-utils/src/utils.ts b/packages/order-utils/src/utils.ts index 3b465cece..6149316f6 100644 --- a/packages/order-utils/src/utils.ts +++ b/packages/order-utils/src/utils.ts @@ -1,3 +1,5 @@ +import { BigNumber } from '@0xproject/utils'; + export const utils = { getSignatureTypeIndexIfExists(signature: string): number { // tslint:disable-next-line:custom-no-magic-numbers @@ -6,4 +8,8 @@ export const utils = { const signatureTypeInt = parseInt(signatureTypeHex, base); return signatureTypeInt; }, + getCurrentUnixTimestampSec(): BigNumber { + const milisecondsInSecond = 1000; + return new BigNumber(Date.now() / milisecondsInSecond).round(); + }, }; -- cgit v1.2.3 From 89b7b56a2cb38d95f65067e5493e8135cb1e7e98 Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Mon, 11 Jun 2018 19:43:40 +0200 Subject: Fix tslint issues --- packages/order-utils/src/exchange_transfer_simulator.ts | 1 - packages/order-utils/src/order_validation_utils.ts | 2 +- .../order-utils/src/store/balance_and_proxy_allowance_lazy_store.ts | 1 - 3 files changed, 1 insertion(+), 3 deletions(-) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/exchange_transfer_simulator.ts b/packages/order-utils/src/exchange_transfer_simulator.ts index 1cb132aba..32d53d6a2 100644 --- a/packages/order-utils/src/exchange_transfer_simulator.ts +++ b/packages/order-utils/src/exchange_transfer_simulator.ts @@ -1,6 +1,5 @@ import { ExchangeContractErrs } from '@0xproject/types'; import { BigNumber } from '@0xproject/utils'; -import { BlockParamLiteral } from 'ethereum-types'; import { AbstractBalanceAndProxyAllowanceLazyStore } from './abstract/abstract_balance_and_proxy_allowance_lazy_store'; import { constants } from './constants'; diff --git a/packages/order-utils/src/order_validation_utils.ts b/packages/order-utils/src/order_validation_utils.ts index 4280e4d97..aebb6db70 100644 --- a/packages/order-utils/src/order_validation_utils.ts +++ b/packages/order-utils/src/order_validation_utils.ts @@ -192,7 +192,7 @@ export class OrderValidationUtils { zrxTokenAddress, ); - const wouldRoundingErrorOccur = await OrderValidationUtils.isRoundingError( + const wouldRoundingErrorOccur = OrderValidationUtils.isRoundingError( filledTakerTokenAmount, signedOrder.takerAssetAmount, signedOrder.makerAssetAmount, diff --git a/packages/order-utils/src/store/balance_and_proxy_allowance_lazy_store.ts b/packages/order-utils/src/store/balance_and_proxy_allowance_lazy_store.ts index b5bd2801a..08d50b924 100644 --- a/packages/order-utils/src/store/balance_and_proxy_allowance_lazy_store.ts +++ b/packages/order-utils/src/store/balance_and_proxy_allowance_lazy_store.ts @@ -1,5 +1,4 @@ import { BigNumber } from '@0xproject/utils'; -import { BlockParamLiteral } from 'ethereum-types'; import * as _ from 'lodash'; import { AbstractBalanceAndProxyAllowanceFetcher } from '../abstract/abstract_balance_and_proxy_allowance_fetcher'; -- cgit v1.2.3 From fe58b449162e0c55b6021a65a93d17719f1eb98f Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Mon, 11 Jun 2018 22:14:03 +0200 Subject: Validate all signature types rather then only ECSignatures --- packages/order-utils/src/order_validation_utils.ts | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) (limited to 'packages/order-utils/src') diff --git a/packages/order-utils/src/order_validation_utils.ts b/packages/order-utils/src/order_validation_utils.ts index aebb6db70..3a6704f26 100644 --- a/packages/order-utils/src/order_validation_utils.ts +++ b/packages/order-utils/src/order_validation_utils.ts @@ -1,5 +1,6 @@ import { ExchangeContractErrs, Order, SignedOrder } from '@0xproject/types'; import { BigNumber } from '@0xproject/utils'; +import { Provider } from 'ethereum-types'; import * as _ from 'lodash'; import { OrderError, TradeSide, TransferType } from './types'; @@ -8,7 +9,7 @@ import { constants } from './constants'; import { ExchangeTransferSimulator } from './exchange_transfer_simulator'; import { ExchangeContract } from './generated_contract_wrappers/exchange'; import { orderHashUtils } from './order_hash'; -import { isValidECSignature, parseECSignature } from './signature_utils'; +import { isValidSignatureAsync } from './signature_utils'; import { utils } from './utils'; export class OrderValidationUtils { @@ -157,6 +158,7 @@ export class OrderValidationUtils { } public async validateFillOrderThrowIfInvalidAsync( exchangeTradeEmulator: ExchangeTransferSimulator, + provider: Provider, signedOrder: SignedOrder, fillTakerTokenAmount: BigNumber, takerAddress: string, @@ -166,9 +168,13 @@ export class OrderValidationUtils { throw new Error(ExchangeContractErrs.OrderFillAmountZero); } const orderHash = orderHashUtils.getOrderHashHex(signedOrder); - // TODO: Verify all signature types! To do this, we need access to a Provider... - const ecSignature = parseECSignature(signedOrder.signature); - if (!isValidECSignature(orderHash, ecSignature, signedOrder.makerAddress)) { + const isValid = await isValidSignatureAsync( + provider, + orderHash, + signedOrder.signature, + signedOrder.makerAddress, + ); + if (!isValid) { throw new Error(OrderError.InvalidSignature); } const filledTakerTokenAmount = await this._exchangeContract.filled.callAsync(orderHash); @@ -204,6 +210,7 @@ export class OrderValidationUtils { } public async validateFillOrKillOrderThrowIfInvalidAsync( exchangeTradeEmulator: ExchangeTransferSimulator, + provider: Provider, signedOrder: SignedOrder, fillTakerTokenAmount: BigNumber, takerAddress: string, @@ -211,6 +218,7 @@ export class OrderValidationUtils { ): Promise { const filledTakerTokenAmount = await this.validateFillOrderThrowIfInvalidAsync( exchangeTradeEmulator, + provider, signedOrder, fillTakerTokenAmount, takerAddress, -- cgit v1.2.3