Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
chainId: number;
}
interface ItemByChainId {
[chainId: string]: T;
}
enum RequestedAssetType {
ETH = 'ETH', // tslint:disable-line:enum-naming
WETH = 'WETH', // tslint:disable-line:enum-naming
ZRX = 'ZRX', // tslint:disable-line:enum-naming
}
const FIVE_DAYS_IN_MS = 4.32e8; // TODO: make this configurable
const NULL_ADDRESS = '0x0000000000000000000000000000000000000000';
const ZERO = new BigNumber(0);
const ASSET_AMOUNT = new BigNumber(0.1);
export class Handler {
private readonly _chainConfigByChainId: ItemByChainId = {};
private static _createProviderEngine(rpcUrl: string): Web3ProviderEngine {
if (configs.DISPENSER_PRIVATE_KEY === undefined) {
throw new Error('Dispenser Private key not found');
}
const engine = new Web3ProviderEngine();
engine.addProvider(new NonceTrackerSubprovider());
engine.addProvider(new PrivateKeyWalletSubprovider(configs.DISPENSER_PRIVATE_KEY));
engine.addProvider(new RPCSubprovider(rpcUrl));
engine.start();
return engine;
}
constructor() {
const contractAddresses = getContractAddressesForChainOrThrow(chainConfig.chainId);
const order: Order = {
makerAddress: configs.DISPENSER_ADDRESS,
takerAddress: req.params.recipient as string,
makerFee: ZERO,
takerFee: ZERO,
makerAssetAmount,
takerAssetAmount,
makerAssetData,
takerAssetData,
salt: generatePseudoRandomSalt(),
makerFeeAssetData: makerAssetData,
takerFeeAssetData: takerAssetData,
feeRecipientAddress: NULL_ADDRESS,
senderAddress: NULL_ADDRESS,
expirationTimeSeconds: new BigNumber(Date.now() + FIVE_DAYS_IN_MS)
// tslint:disable-next-line:custom-no-magic-numbers
.div(1000)
.integerValue(BigNumber.ROUND_FLOOR),
exchangeAddress: contractAddresses.exchange,
chainId: chainConfig.chainId,
};
const orderHash = orderHashUtils.getOrderHashHex(order);
const signature = await signatureUtils.ecSignHashAsync(
chainConfig.web3Wrapper.getProvider(),
orderHash,
configs.DISPENSER_ADDRESS,
);
const signedOrder: SignedOrder = {
...order,
signature,
};
const makerAssetAmount = Web3Wrapper.toBaseUnitAmount(ASSET_AMOUNT, makerTokenIfExists.decimals);
const takerAssetAmount = Web3Wrapper.toBaseUnitAmount(ASSET_AMOUNT, takerTokenIfExists.decimals);
const makerAssetData = assetDataUtils.encodeERC20AssetData(makerTokenIfExists.address);
const takerAssetData = assetDataUtils.encodeERC20AssetData(takerTokenIfExists.address);
const contractAddresses = getContractAddressesForChainOrThrow(chainConfig.chainId);
const order: Order = {
makerAddress: configs.DISPENSER_ADDRESS,
takerAddress: req.params.recipient as string,
makerFee: ZERO,
takerFee: ZERO,
makerAssetAmount,
takerAssetAmount,
makerAssetData,
takerAssetData,
salt: generatePseudoRandomSalt(),
makerFeeAssetData: makerAssetData,
takerFeeAssetData: takerAssetData,
feeRecipientAddress: NULL_ADDRESS,
senderAddress: NULL_ADDRESS,
expirationTimeSeconds: new BigNumber(Date.now() + FIVE_DAYS_IN_MS)
// tslint:disable-next-line:custom-no-magic-numbers
.div(1000)
.integerValue(BigNumber.ROUND_FLOOR),
exchangeAddress: contractAddresses.exchange,
chainId: chainConfig.chainId,
};
const orderHash = orderHashUtils.getOrderHashHex(order);
const signature = await signatureUtils.ecSignHashAsync(
chainConfig.web3Wrapper.getProvider(),
orderHash,
configs.DISPENSER_ADDRESS,
takerAssetAmount,
makerAssetData,
takerAssetData,
salt: generatePseudoRandomSalt(),
makerFeeAssetData: makerAssetData,
takerFeeAssetData: takerAssetData,
feeRecipientAddress: NULL_ADDRESS,
senderAddress: NULL_ADDRESS,
expirationTimeSeconds: new BigNumber(Date.now() + FIVE_DAYS_IN_MS)
// tslint:disable-next-line:custom-no-magic-numbers
.div(1000)
.integerValue(BigNumber.ROUND_FLOOR),
exchangeAddress: contractAddresses.exchange,
chainId: chainConfig.chainId,
};
const orderHash = orderHashUtils.getOrderHashHex(order);
const signature = await signatureUtils.ecSignHashAsync(
chainConfig.web3Wrapper.getProvider(),
orderHash,
configs.DISPENSER_ADDRESS,
);
const signedOrder: SignedOrder = {
...order,
signature,
};
const payload = JSON.stringify(signedOrder);
logUtils.log(`Dispensed signed order: ${payload}`);
res.status(constants.SUCCESS_STATUS).send(payload);
}
}
makerAssetData,
takerAssetData,
salt: generatePseudoRandomSalt(),
makerFeeAssetData: makerAssetData,
takerFeeAssetData: takerAssetData,
feeRecipientAddress: NULL_ADDRESS,
senderAddress: NULL_ADDRESS,
expirationTimeSeconds: new BigNumber(Date.now() + FIVE_DAYS_IN_MS)
// tslint:disable-next-line:custom-no-magic-numbers
.div(1000)
.integerValue(BigNumber.ROUND_FLOOR),
exchangeAddress: contractAddresses.exchange,
chainId: chainConfig.chainId,
};
const orderHash = orderHashUtils.getOrderHashHex(order);
const signature = await signatureUtils.ecSignHashAsync(
chainConfig.web3Wrapper.getProvider(),
orderHash,
configs.DISPENSER_ADDRESS,
);
const signedOrder: SignedOrder = {
...order,
signature,
};
const payload = JSON.stringify(signedOrder);
logUtils.log(`Dispensed signed order: ${payload}`);
res.status(constants.SUCCESS_STATUS).send(payload);
}
}
submitOrder ({commit, state, dispatch}, order) {
// console.log('hier?')
console.log(order)
if (typeof order === 'string') order = JSON.parse(order)
// {
// try {
// ZeroEx.isValidSignature(order)
// } catch (error) {
// console.error(error)
// dispatch('addNotification', {type: 'error', 'text': 'Order failed, check log for details'})
// }
// }
try {
var orderHash = ZeroEx.getOrderHashHex(order)
console.log('HASH', orderHash)
return zeroEx.signOrderHashAsync(orderHash, state.addresses[0]).then((ecSignature) => {
const signedOrder = {
...order,
ecSignature
}
// console.log(signedOrder)
// commit('ADD_ORDER', signedOrder)
return axios.post('/order/new', signedOrder).then((results) => {
// console.log(results)
dispatch('pageServer')
dispatch('addNotification', {type: 'success', 'text': 'Order Added'})
}).catch((error) => {
dispatch('addNotification', {type: 'error', 'text': 'Order failed, check log for details'})
console.error(error)
})
connect ({dispatch, commit, getters, state}) {
let providerEngine = null
if (window.web3) {
providerEngine = window.web3.currentProvider
} else {
const ROPSTEN_ENDPOINT = 'https://infura.io'
providerEngine = new ProviderEngine()
providerEngine.addProvider(new FilterSubprovider())
providerEngine.addProvider(new RpcSubprovider({rpcUrl: ROPSTEN_ENDPOINT}))
providerEngine.start()
}
zeroEx = new ZeroEx(providerEngine)
zeroEx._web3Wrapper.web3.version.getNetwork((error, response) => {
if (error) console.error(error)
if (parseInt(response) === 42 && window.location.hostname !== 'kovan.0xchange.me') {
window.location.href = 'https://kovan.0xchange.me'
} else if (parseInt(response) === 1 && window.location.hostname === 'kovan.0xchange.me') {
window.location.href = 'https://0xchange.me'
}
})
// commit('SET_ZERO_EX', zeroEx)
// 3117574 kovan
// 4145578 mainnet
// zeroEx.exchange.getLogsAsync('LogFill', {fromBlock: 4219261, toBlock: 'latest'}, {}).then((logs) => {
// console.log(logs)
// commit('ADD_LOGS', logs)
// console.log(logs[0])
// let data = logs[0].data
// // console.log(result)
// // })
// })
// zeroEx.tokenRegistry.getTokensAsync().then((tokens) => {
// console.log('tokens returned')
// commit('ADD_TOKENS', tokens)
// console.log('tokens:', tokens)
// const symbols = getters.tokenSymbols
// var index = symbols.indexOf('WETH')
// if (index !== -1) {
// symbols[index] = 'ETH'
// }
//
// })
commit('SET_NULL_ADDRESS', ZeroEx.NULL_ADDRESS)
zeroEx.etherToken.getContractAddressAsync().then((address) => {
commit('SET_WETH_ADDRESS', address)
})
zeroEx.exchange.getZRXTokenAddressAsync().then((address) => {
commit('SET_ZRX_ADDRESS', address)
})
zeroEx.exchange.getContractAddressAsync().then((address) => {
commit('SET_EXCHANGE_ADDRESS', address)
})
zeroEx.getAvailableAddressesAsync().then((addresses) => {
commit('SET_ADDRESSES', addresses)
})
},
addTokenAddress ({commit}, address) {
const etherTokenAddress = contractAddresses.etherToken;
const dummyERC721TokenContract = dummyERC721TokenContracts[0];
if (!dummyERC721TokenContract) {
console.log('No Dummy ERC721 Tokens deployed on this network');
return;
}
// Initialize the Web3Wrapper, this provides helper functions around fetching
// account information, balances, general contract logs
const web3Wrapper = new Web3Wrapper(providerEngine);
const [maker, taker] = await web3Wrapper.getAvailableAddressesAsync();
const printUtils = new PrintUtils(web3Wrapper, contractWrappers, { maker, taker }, { WETH: etherTokenAddress });
printUtils.printAccounts();
// the amount the maker is selling of maker asset: 1 ERC721 Token
const makerAssetAmount = new BigNumber(1);
// the amount the maker is selling of maker asset
const takerAssetAmount = Web3Wrapper.toBaseUnitAmount(new BigNumber(0.1), DECIMALS);
const tokenId = generatePseudoRandomSalt();
// 0x v2 uses hex encoded asset data strings to encode all the information needed to identify an asset
const makerAssetData = assetDataUtils.encodeERC721AssetData(dummyERC721TokenContract.address, tokenId);
const takerAssetData = assetDataUtils.encodeERC20AssetData(etherTokenAddress);
let txHash;
// Mint a new ERC721 token for the maker
const mintTxHash = await dummyERC721TokenContract.mint.sendTransactionAsync(maker, tokenId, { from: maker });
await printUtils.awaitTransactionMinedSpinnerAsync('Mint ERC721 Token', mintTxHash);
// Allow the 0x ERC721 Proxy to move ERC721 tokens on behalf of maker
const isApproved = true;
const makerERC721ApprovalTxHash = await dummyERC721TokenContract.setApprovalForAll.validateAndSendTransactionAsync(
contractAddresses.erc721Proxy,
isApproved,
export async function scenarioAsync(): Promise {
PrintUtils.printScenario('Exchange Subscribe');
await runMigrationsOnceIfRequiredAsync();
// Initialize the ContractWrappers, this provides helper functions around calling
// 0x contracts as well as ERC20/ERC721 token contracts on the blockchain
const contractWrappers = new ContractWrappers(providerEngine, { networkId: NETWORK_CONFIGS.networkId });
// No filter, get all of the Fill Events
const filterValues: IndexedFilterValues = {};
// Subscribe to the Fill Events on the Exchange
contractWrappers.exchange.subscribe(
ExchangeEvents.Fill,
filterValues,
(err: null | Error, decodedLogEvent?: DecodedLogEvent) => {
if (err) {
console.log('error:', err);
providerEngine.stop();
} else if (decodedLogEvent) {
const fillLog = decodedLogEvent.log;
const makerAssetData = assetDataUtils.decodeERC20AssetData(fillLog.args.makerAssetData);
const takerAssetData = assetDataUtils.decodeERC20AssetData(fillLog.args.takerAssetData);
PrintUtils.printData('Fill Event', [
['orderHash', fillLog.args.orderHash],