How to use @0x/order-utils - 10 common examples

To help you get started, we’ve selected a few @0x/order-utils examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ethfinex / efx-api-node / src / api / sign / order.js View on Github external
module.exports = async (efx, order) => {
  const orderHash = orderHashUtils.getOrderHashHex(order)

  const provider = efx.isMetaMask
                    ? new MetamaskSubprovider(efx.web3.currentProvider)
                    : efx.web3.currentProvider

  const signature = await signatureUtils.ecSignHashAsync(
    provider,
    orderHash,
    efx.get('account')
  )

  // create a copy of the object and add signature field
  order = {
    ...order,
    signature
  }

  /**
  const isValid = signatureUtils.isValidSignatureAsync(orderHash, signedOrder, efx.get('account').toLowerCase())

  console.log( "is_valid ->", isValid)
  **/
github 0xProject / 0x-monorepo / packages / contract-wrappers / src / fetchers / asset_balance_and_proxy_allowance_fetcher.ts View on Github external
public async getBalanceAsync(assetData: string, userAddress: string): Promise {
        const decodedAssetData = assetDataUtils.decodeAssetDataOrThrow(assetData);
        let balance: BigNumber | undefined;
        if (assetDataUtils.isERC20AssetData(decodedAssetData)) {
            balance = await this._erc20Token.getBalanceAsync(decodedAssetData.tokenAddress, userAddress, {
                defaultBlock: this._stateLayer,
            });
        } else if (assetDataUtils.isERC721AssetData(decodedAssetData)) {
            const tokenOwner = await this._erc721Token.getOwnerOfAsync(
                decodedAssetData.tokenAddress,
                decodedAssetData.tokenId,
                {
                    defaultBlock: this._stateLayer,
                },
            );
            balance = tokenOwner === userAddress ? new BigNumber(1) : new BigNumber(0);
        } else if (assetDataUtils.isMultiAssetData(decodedAssetData)) {
            // The `balance` for MultiAssetData is the total units of the entire `assetData` that are held by the `userAddress`.
github 0xProject / 0x-monorepo / packages / pipeline / src / parsers / sra_orders / index.ts View on Github external
export function _convertToEntity(apiOrder: APIOrder): SraOrder {
    // TODO(albrow): refactor out common asset data decoding code.
    const makerAssetData = assetDataUtils.decodeAssetDataOrThrow(apiOrder.order.makerAssetData);
    const makerAssetType = makerAssetData.assetProxyId === AssetProxyId.ERC20 ? 'erc20' : 'erc721';
    const takerAssetData = assetDataUtils.decodeAssetDataOrThrow(apiOrder.order.takerAssetData);
    const takerAssetType = takerAssetData.assetProxyId === AssetProxyId.ERC20 ? 'erc20' : 'erc721';

    const sraOrder = new SraOrder();
    sraOrder.exchangeAddress = apiOrder.order.exchangeAddress;
    sraOrder.orderHashHex = orderHashUtils.getOrderHashHex(apiOrder.order);

    sraOrder.makerAddress = apiOrder.order.makerAddress;
    sraOrder.takerAddress = apiOrder.order.takerAddress;
    sraOrder.feeRecipientAddress = apiOrder.order.feeRecipientAddress;
    sraOrder.senderAddress = apiOrder.order.senderAddress;
    sraOrder.makerAssetAmount = apiOrder.order.makerAssetAmount;
    sraOrder.takerAssetAmount = apiOrder.order.takerAssetAmount;
    sraOrder.makerFee = apiOrder.order.makerFee;
    sraOrder.takerFee = apiOrder.order.takerFee;
    sraOrder.expirationTimeSeconds = apiOrder.order.expirationTimeSeconds;
    sraOrder.salt = apiOrder.order.salt;
github 0xProject / 0x-monorepo / packages / pipeline / src / parsers / sra_orders / index.ts View on Github external
export function _convertToEntity(apiOrder: APIOrder): SraOrder {
    // TODO(albrow): refactor out common asset data decoding code.
    const makerAssetData = assetDataUtils.decodeAssetDataOrThrow(apiOrder.order.makerAssetData);
    const makerAssetType = makerAssetData.assetProxyId === AssetProxyId.ERC20 ? 'erc20' : 'erc721';
    const takerAssetData = assetDataUtils.decodeAssetDataOrThrow(apiOrder.order.takerAssetData);
    const takerAssetType = takerAssetData.assetProxyId === AssetProxyId.ERC20 ? 'erc20' : 'erc721';

    const sraOrder = new SraOrder();
    sraOrder.exchangeAddress = apiOrder.order.exchangeAddress;
    sraOrder.orderHashHex = orderHashUtils.getOrderHashHex(apiOrder.order);

    sraOrder.makerAddress = apiOrder.order.makerAddress;
    sraOrder.takerAddress = apiOrder.order.takerAddress;
    sraOrder.feeRecipientAddress = apiOrder.order.feeRecipientAddress;
    sraOrder.senderAddress = apiOrder.order.senderAddress;
    sraOrder.makerAssetAmount = apiOrder.order.makerAssetAmount;
    sraOrder.takerAssetAmount = apiOrder.order.takerAssetAmount;
    sraOrder.makerFee = apiOrder.order.makerFee;
    sraOrder.takerFee = apiOrder.order.takerFee;
github 0xProject / 0x-monorepo / packages / asset-swapper / src / swap_quoter.ts View on Github external
private async _getSignedOrdersAsync(makerAssetData: string, takerAssetData: string): Promise {
        assert.isString('makerAssetData', makerAssetData);
        assert.isString('takerAssetData', takerAssetData);
        assetDataUtils.decodeAssetDataOrThrow(takerAssetData);
        assetDataUtils.decodeAssetDataOrThrow(makerAssetData);
        // get orders
        const apiOrders = await this.orderbook.getOrdersAsync(makerAssetData, takerAssetData);
        const orders = _.map(apiOrders, o => o.order);
        const prunedOrders = orderPrunerUtils.pruneForUsableSignedOrders(
            orders,
            this.permittedOrderFeeTypes,
            this.expiryBufferMs,
        );
        const sortedPrunedOrders = sortingUtils.sortOrders(prunedOrders);
        return sortedPrunedOrders;
    }
github 0xProject / 0x-monorepo / packages / asset-swapper / src / swap_quoter.ts View on Github external
private async _getSignedOrdersAsync(makerAssetData: string, takerAssetData: string): Promise {
        assert.isString('makerAssetData', makerAssetData);
        assert.isString('takerAssetData', takerAssetData);
        assetDataUtils.decodeAssetDataOrThrow(takerAssetData);
        assetDataUtils.decodeAssetDataOrThrow(makerAssetData);
        // get orders
        const apiOrders = await this.orderbook.getOrdersAsync(makerAssetData, takerAssetData);
        const orders = _.map(apiOrders, o => o.order);
        const prunedOrders = orderPrunerUtils.pruneForUsableSignedOrders(
            orders,
            this.permittedOrderFeeTypes,
            this.expiryBufferMs,
        );
        const sortedPrunedOrders = sortingUtils.sortOrders(prunedOrders);
        return sortedPrunedOrders;
    }
github veilco / veil-js / src / 0x.ts View on Github external
export async function signOrder(
  provider: Provider,
  zeroExOrder: Order
): Promise {
  const orderHash = orderHashUtils.getOrderHashHex({
    ...zeroExOrder,
    expirationTimeSeconds: new BigNumber(zeroExOrder.expirationTimeSeconds),
    makerFee: new BigNumber(zeroExOrder.makerFee),
    makerAssetAmount: new BigNumber(zeroExOrder.makerAssetAmount),
    salt: new BigNumber(zeroExOrder.salt),
    takerFee: new BigNumber(zeroExOrder.takerFee),
    takerAssetAmount: new BigNumber(zeroExOrder.takerAssetAmount)
  });
  const signature = await signatureUtils.ecSignHashAsync(
    provider,
    orderHash,
    zeroExOrder.makerAddress
  );

  // Append signature to order
  const signedOrder = {
github 0xProject / 0x-monorepo / packages / website / ts / components / fill_order.tsx View on Github external
private async _validateFillOrderFireAndForgetAsync(orderJSON: string): Promise {
        let orderJSONErrMsg = '';
        let parsedOrder: PortalOrder;
        let orderHash: string;
        try {
            const order = orderParser.parseJsonString(orderJSON);
            const validationResult = validator.validate(order, portalOrderSchema);
            if (validationResult.errors.length > 0) {
                orderJSONErrMsg = 'Submitted order JSON is not a valid order';
                logUtils.log(`Unexpected order JSON validation error: ${validationResult.errors.join(', ')}`);
                return;
            }
            parsedOrder = order;
            const signedOrder = parsedOrder.signedOrder;
            orderHash = orderHashUtils.getOrderHashHex(signedOrder);
            const exchangeContractAddr = this.props.blockchain.getExchangeContractAddressIfExists();
            const signature = signedOrder.signature;
            const isSignatureValid = await this.props.blockchain.isValidSignatureAsync(
                orderHash,
                signature,
                signedOrder.makerAddress,
            );
            if (exchangeContractAddr !== signedOrder.exchangeAddress) {
                orderJSONErrMsg = 'This order was made on another network or using a deprecated Exchange contract';
                parsedOrder = undefined;
            } else if (!isSignatureValid) {
                orderJSONErrMsg = 'Order signature is invalid';
                parsedOrder = undefined;
            } else {
                // Update user supplied order cache so that if they navigate away from fill view
                // e.g to set a token allowance, when they come back, the fill order persists
github 0xProject / 0x-monorepo / packages / contract-wrappers / src / contract_wrappers / exchange_wrapper.ts View on Github external
const balanceAllowanceStore = new BalanceAndProxyAllowanceLazyStore(balanceAllowanceFetcher);
        const exchangeTradeSimulator = new ExchangeTransferSimulator(balanceAllowanceStore);
        const filledCancelledFetcher = new OrderFilledCancelledFetcher(this, BlockParamLiteral.Latest);

        let fillableTakerAssetAmount;
        const shouldValidateRemainingOrderAmountIsFillable =
            opts.validateRemainingOrderAmountIsFillable === undefined
                ? true
                : opts.validateRemainingOrderAmountIsFillable;
        if (opts.expectedFillTakerTokenAmount) {
            // If the caller has specified a taker fill amount, we use this for all validation
            fillableTakerAssetAmount = opts.expectedFillTakerTokenAmount;
        } else if (shouldValidateRemainingOrderAmountIsFillable) {
            // Default behaviour is to validate the amount left on the order.
            const filledTakerTokenAmount = await this.getFilledTakerAssetAmountAsync(
                orderHashUtils.getOrderHashHex(signedOrder),
            );
            fillableTakerAssetAmount = signedOrder.takerAssetAmount.minus(filledTakerTokenAmount);
        } else {
            const orderStateUtils = new OrderStateUtils(balanceAllowanceStore, filledCancelledFetcher);
            // Calculate the taker amount fillable given the maker balance and allowance
            const orderRelevantState = await orderStateUtils.getOpenOrderRelevantStateAsync(signedOrder);
            fillableTakerAssetAmount = orderRelevantState.remainingFillableTakerAssetAmount;
        }

        const orderValidationUtils = new OrderValidationUtils(filledCancelledFetcher, this._web3Wrapper.getProvider());
        await orderValidationUtils.validateOrderFillableOrThrowAsync(
            exchangeTradeSimulator,
            signedOrder,
            this.getZRXAssetData(),
            fillableTakerAssetAmount,
        );
github 0xProject / 0x-monorepo / packages / website / ts / redux / reducer.ts View on Github external
flashMessage: string | React.ReactNode;
    providerType: ProviderType;
    injectedProviderName: string;
    translate: Translate;
}

export const INITIAL_STATE: State = {
    // Portal
    blockchainErr: BlockchainErrs.NoError,
    blockchainIsLoaded: false,
    networkId: undefined,
    orderExpiryTimestamp: utils.initialOrderExpiryUnixTimestampSec(),
    orderFillAmount: undefined,
    orderSignature: '',
    orderTakerAddress: constants.NULL_ADDRESS,
    orderSalt: generatePseudoRandomSalt(),
    nodeVersion: undefined,
    screenWidth: utils.getScreenWidth(),
    shouldBlockchainErrDialogBeOpen: false,
    sideToAssetToken: {
        [Side.Deposit]: {},
        [Side.Receive]: {},
    },
    tokenByAddress: {},
    lastForceTokenStateRefetch: moment().unix(),
    userAddress: '',
    userEtherBalanceInWei: undefined,
    userSuppliedOrderCache: undefined,
    portalOnboardingStep: 0,
    isPortalOnboardingShowing: false,
    hasPortalOnboardingBeenClosed: false,
    // Docs