Standard: add spacing as required

pull/1/head
Alex Beregszaszi 9 years ago
parent 4fb1947c21
commit 3a7bc52ed6
  1. 6
      background.js
  2. 142
      src/app.js
  3. 52
      src/app/compiler.js
  4. 58
      src/app/editor.js
  5. 6
      src/app/gist-handler.js
  6. 6
      src/app/query-params.js
  7. 104
      src/app/renderer.js
  8. 18
      src/app/storage-handler.js
  9. 10
      src/app/utils.js
  10. 2
      src/index.js
  11. 196
      src/universal-dapp.js

@ -1,9 +1,9 @@
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.storage.sync.set({'chrome-app-sync': true});
chrome.storage.sync.set({ 'chrome-app-sync' : true });
chrome.tabs.create({'url': chrome.extension.getURL('index.html')}, function(tab) {
chrome.tabs.create({ 'url': chrome.extension.getURL('index.html') }, function (tab) {
// tab opened
});

@ -11,16 +11,16 @@ var Compiler = require('./app/compiler');
// The event listener needs to be registered as early as possible, because the
// parent will send the message upon the "load" event.
var filesToLoad = null;
var loadFilesCallback = function(files) { filesToLoad = files; }; // will be replaced later
window.addEventListener('message', function(ev) {
var loadFilesCallback = function (files) { filesToLoad = files; }; // will be replaced later
window.addEventListener('message', function (ev) {
if (typeof ev.data === typeof [] && ev.data[0] === 'loadFiles') {
loadFilesCallback(ev.data[1]);
}
}, false);
var run = function() {
var run = function () {
function loadFiles(files) {
function loadFiles (files) {
for (var f in files) {
var key = utils.fileKey(f);
var content = files[f].content;
@ -36,7 +36,7 @@ var run = function() {
updateFiles();
}
loadFilesCallback = function(files) {
loadFilesCallback = function (files) {
loadFiles(files);
};
@ -46,8 +46,8 @@ var run = function() {
// ------------------ query params (hash) ----------------
function syncQueryParams() {
$('#optimize').attr( 'checked', (queryParams.get().optimize === 'true') );
function syncQueryParams () {
$('#optimize').attr('checked', (queryParams.get().optimize === 'true'));
}
window.onhashchange = syncQueryParams;
@ -56,15 +56,15 @@ var run = function() {
// ------------------ gist load ----------------
var loadingFromGist = gistHandler.handleLoad(function(gistId) {
var loadingFromGist = gistHandler.handleLoad(function (gistId) {
$.ajax({
url: 'https://api.github.com/gists/'+gistId,
url: 'https://api.github.com/gists/' + gistId,
jsonp: 'callback',
dataType: 'jsonp',
success: function(response) {
success: function (response) {
if (response.data) {
if (!response.data.files) {
alert( 'Gist load error: ' + response.data.message );
alert('Gist load error: ' + response.data.message);
return;
}
loadFiles(response.data.files);
@ -88,9 +88,9 @@ var run = function() {
// ----------------- tabbed menu -------------------
$('#options li').click(function(ev){
$('#options li').click(function (ev) {
var $el = $(this);
var match = /[a-z]+View/.exec( $el.get(0).className );
var match = /[a-z]+View/.exec($el.get(0).className);
if (!match) return;
var cls = match[0];
if (!$el.hasClass('active')) {
@ -106,11 +106,11 @@ var run = function() {
// ------------------ gist publish --------------
$('#gist').click(function(){
$('#gist').click(function () {
if (confirm('Are you sure you want to publish all your files anonymously as a public gist on github.com?')) {
var files = editor.packageFiles();
var description = 'Created using browser-solidity: Realtime Ethereum Contract Compiler and Runtime. \n Load this file by pasting this gists URL or ID at https://ethereum.github.io/browser-solidity/#version=' + queryParams.get().version + '&optimize='+ queryParams.get().optimize +'&gist=';
var description = 'Created using browser-solidity: Realtime Ethereum Contract Compiler and Runtime. \n Load this file by pasting this gists URL or ID at https://ethereum.github.io/browser-solidity/#version=' + queryParams.get().version + '&optimize=' + queryParams.get().optimize + '&gist=';
$.ajax({
url: 'https://api.github.com/gists',
@ -120,15 +120,15 @@ var run = function() {
public: true,
files: files
})
}).done(function(response) {
}).done(function (response) {
if (response.html_url && confirm('Created a gist at ' + response.html_url + ' Would you like to open it in a new window?')) {
window.open( response.html_url, '_blank' );
window.open(response.html_url, '_blank');
}
});
}
});
$('#copyOver').click(function(){
$('#copyOver').click(function () {
var target = prompt(
'To which other browser-solidity instance do you want to copy over all files?',
'https://ethereum.github.io/browser-solidity/'
@ -136,7 +136,7 @@ var run = function() {
if (target === null)
return;
var files = editor.packageFiles();
var iframe = $('<iframe/>', {src: target, style: 'display:none;', load: function() {
var iframe = $('<iframe/>', {src: target, style: 'display:none;', load: function () {
this.contentWindow.postMessage(['loadFiles', files], '*');
}}).appendTo('body');
});
@ -146,30 +146,30 @@ var run = function() {
var $filesEl = $('#files');
var FILE_SCROLL_DELTA = 300;
$('.newFile').on('click', function() {
$('.newFile').on('click', function () {
editor.newFile();
updateFiles();
$filesEl.animate({left: Math.max( (0 - activeFilePos() + (FILE_SCROLL_DELTA/2)), 0)+ 'px'}, 'slow', function(){
$filesEl.animate({ left: Math.max((0 - activeFilePos() + (FILE_SCROLL_DELTA / 2)), 0) + 'px' }, 'slow', function () {
reAdjust();
});
});
$filesEl.on('click', '.file:not(.active)', showFileHandler);
$filesEl.on('click', '.file.active', function(ev) {
$filesEl.on('click', '.file.active', function (ev) {
var $fileTabEl = $(this);
var originalName = $fileTabEl.find('.name').text();
ev.preventDefault();
if ($(this).find('input').length > 0) return false;
var $fileNameInputEl = $('<input value="'+originalName+'"/>');
var $fileNameInputEl = $('<input value="' + originalName + '"/>');
$fileTabEl.html($fileNameInputEl);
$fileNameInputEl.focus();
$fileNameInputEl.select();
$fileNameInputEl.on('blur', handleRename);
$fileNameInputEl.keyup(handleRename);
function handleRename(ev) {
function handleRename (ev) {
ev.preventDefault();
if (ev.which && ev.which !== 13) return false;
var newName = ev.target.value;
@ -177,9 +177,9 @@ var run = function() {
$fileNameInputEl.off('keyup');
if (newName !== originalName && confirm('Are you sure you want to rename: ' + originalName + ' to ' + newName + '?')) {
var content = window.localStorage.getItem( utils.fileKey(originalName) );
window.localStorage[utils.fileKey( newName )] = content;
window.localStorage.removeItem( utils.fileKey( originalName) );
var content = window.localStorage.getItem(utils.fileKey(originalName));
window.localStorage[utils.fileKey(newName)] = content;
window.localStorage.removeItem(utils.fileKey(originalName));
editor.setCacheFile(newName);
}
@ -190,32 +190,32 @@ var run = function() {
return false;
});
$filesEl.on('click', '.file .remove', function(ev) {
$filesEl.on('click', '.file .remove', function (ev) {
ev.preventDefault();
var name = $(this).parent().find('.name').text();
if (confirm('Are you sure you want to remove: ' + name + ' from local storage?')) {
window.localStorage.removeItem( utils.fileKey( name ) );
window.localStorage.removeItem(utils.fileKey(name));
editor.setNextFile(utils.fileKey(name));
updateFiles();
}
return false;
});
function showFileHandler(ev) {
function showFileHandler (ev) {
ev.preventDefault();
editor.setCacheFile($(this).find('.name').text());
updateFiles();
return false;
}
function activeFileTab() {
function activeFileTab () {
var name = editor.getCacheFile();
return $('#files .file').filter(function(){ return $(this).find('.name').text() === name; });
return $('#files .file').filter(function () { return $(this).find('.name').text() === name; });
}
function updateFiles() {
function updateFiles () {
var $filesEl = $('#files');
var files = editor.getFiles();
@ -230,72 +230,72 @@ var run = function() {
active.addClass('active');
editor.resetSession();
}
$('#input').toggle( editor.cacheFileIsPresent() );
$('#output').toggle( editor.cacheFileIsPresent() );
$('#input').toggle(editor.cacheFileIsPresent());
$('#output').toggle(editor.cacheFileIsPresent());
reAdjust();
}
function fileTabTemplate(key) {
function fileTabTemplate (key) {
var name = utils.fileNameFromKey(key);
return $('<li class="file"><span class="name">'+name+'</span><span class="remove"><i class="fa fa-close"></i></span></li>');
return $('<li class="file"><span class="name">' + name + '</span><span class="remove"><i class="fa fa-close"></i></span></li>');
}
var $filesWrapper = $('.files-wrapper');
var $scrollerRight = $('.scroller-right');
var $scrollerLeft = $('.scroller-left');
function widthOfList (){
function widthOfList () {
var itemsWidth = 0;
$('.file').each(function(){
$('.file').each(function () {
var itemWidth = $(this).outerWidth();
itemsWidth += itemWidth;
});
return itemsWidth;
}
function widthOfHidden(){
function widthOfHidden () {
return ($filesWrapper.outerWidth() - widthOfList() - getLeftPosi());
}
function widthOfVisible(){
function widthOfVisible () {
return $filesWrapper.outerWidth();
}
function getLeftPosi(){
function getLeftPosi () {
return $filesEl.position().left;
}
function activeFilePos() {
function activeFilePos () {
var el = $filesEl.find('.active');
var l = el.position().left;
return l;
}
function reAdjust (){
function reAdjust () {
if (widthOfList() + getLeftPosi() > + widthOfVisible()) {
$scrollerRight.fadeIn('fast');
} else {
$scrollerRight.fadeOut('fast');
}
if (getLeftPosi()<0) {
if (getLeftPosi() < 0) {
$scrollerLeft.fadeIn('fast');
} else {
$scrollerLeft.fadeOut('fast');
$filesEl.animate({left: getLeftPosi() + 'px'},'slow');
$filesEl.animate({ left: getLeftPosi() + 'px' }, 'slow');
}
}
$scrollerRight.click(function() {
$scrollerRight.click(function () {
var delta = (getLeftPosi() - FILE_SCROLL_DELTA);
$filesEl.animate({left: delta + 'px'},'slow',function(){
$filesEl.animate({ left: delta + 'px' }, 'slow', function () {
reAdjust();
});
});
$scrollerLeft.click(function() {
var delta = Math.min( (getLeftPosi() + FILE_SCROLL_DELTA), 0 );
$filesEl.animate({left: delta + 'px'},'slow',function(){
$scrollerLeft.click(function () {
var delta = Math.min((getLeftPosi() + FILE_SCROLL_DELTA), 0);
$filesEl.animate({ left: delta + 'px' }, 'slow', function () {
reAdjust();
});
});
@ -307,14 +307,14 @@ var run = function() {
// var soljsonSources is provided by bin/list.js
$('option', '#versionSelector').remove();
$.each(soljsonSources, function(i, file) {
$.each(soljsonSources, function (i, file) {
if (file) {
var version = file.replace(/soljson-(.*).js/, '$1');
$('#versionSelector').append(new Option(version, file));
}
});
$('#versionSelector').change(function() {
queryParams.update({version: $('#versionSelector').val() });
$('#versionSelector').change(function () {
queryParams.update({ version: $('#versionSelector').val() });
loadVersion($('#versionSelector').val());
});
@ -322,7 +322,7 @@ var run = function() {
var EDITOR_SIZE_CACHE_KEY = 'editor-size-cache';
var dragging = false;
$('#dragbar').mousedown(function(e){
$('#dragbar').mousedown(function (e) {
e.preventDefault();
dragging = true;
var main = $('#righthand-panel');
@ -333,8 +333,8 @@ var run = function() {
}
}).prependTo('body');
$(document).mousemove(function(e){
ghostbar.css('left',e.pageX+2);
$(document).mousemove(function (e) {
ghostbar.css('left', e.pageX + 2);
});
});
@ -346,13 +346,13 @@ var run = function() {
onResize();
}
function getEditorSize(){
function getEditorSize () {
window.localStorage[EDITOR_SIZE_CACHE_KEY] = $('#righthand-panel').width();
}
$(document).mouseup(function(e){
$(document).mouseup(function (e) {
if (dragging) {
var delta = $body.width() - e.pageX+2;
var delta = $body.width() - e.pageX + 2;
$('#ghostbar').remove();
$(document).unbind('mousemove');
dragging = false;
@ -371,19 +371,19 @@ var run = function() {
// ----------------- toggle right hand panel -----------------
var hidingRHP = false;
$('.toggleRHP').click(function(){
$('.toggleRHP').click(function () {
hidingRHP = !hidingRHP;
setEditorSize( hidingRHP ? 0 : window.localStorage[EDITOR_SIZE_CACHE_KEY] );
setEditorSize(hidingRHP ? 0 : window.localStorage[EDITOR_SIZE_CACHE_KEY]);
$('.toggleRHP i').toggleClass('fa-angle-double-right', !hidingRHP);
$('.toggleRHP i').toggleClass('fa-angle-double-left', hidingRHP);
if (!hidingRHP) compiler.compile();
});
function getHidingRHP() { return hidingRHP; }
function getHidingRHP () { return hidingRHP; }
// ----------------- editor resize ---------------
function onResize() {
function onResize () {
editor.resize();
reAdjust();
}
@ -396,23 +396,23 @@ var run = function() {
// ----------------- compiler output renderer ----------------------
$('.asmOutput button').click(function() {$(this).parent().find('pre').toggle(); });
$('.asmOutput button').click(function () { $(this).parent().find('pre').toggle(); });
// ----------------- compiler ----------------------
function handleGithubCall(root, path, cb) {
function handleGithubCall (root, path, cb) {
$('#output').append($('<div/>').append($('<pre/>').text('Loading github.com/' + root + '/' + path + ' ...')));
return $.getJSON('https://api.github.com/repos/' + root + '/contents/' + path, cb);
}
var compiler = new Compiler(editor, handleGithubCall, $('#output'), getHidingRHP, updateFiles);
function setVersionText(text) {
function setVersionText (text) {
$('#version').text(text);
}
var loadVersion = function(version) {
var loadVersion = function (version) {
setVersionText('(loading)');
queryParams.update({version: version});
var isFirefox = typeof InstallTrigger !== 'undefined';
@ -428,7 +428,7 @@ var run = function() {
newScript.type = 'text/javascript';
newScript.src = 'https://ethereum.github.io/solc-bin/bin/' + version;
document.getElementsByTagName('head')[0].appendChild(newScript);
var check = window.setInterval(function() {
var check = window.setInterval(function () {
if (!Module) return;
window.clearInterval(check);
compiler.onCompilerLoaded(setVersionText);
@ -436,9 +436,9 @@ var run = function() {
}
};
loadVersion( queryParams.get().version || 'soljson-latest.js');
loadVersion(queryParams.get().version || 'soljson-latest.js');
document.querySelector('#optimize').addEventListener('change', function(){
document.querySelector('#optimize').addEventListener('change', function () {
queryParams.update({optimize: document.querySelector('#optimize').checked });
compiler.compile();
});

@ -4,7 +4,7 @@ var Renderer = require('./renderer');
var Base64 = require('js-base64').Base64;
function Compiler(editor, handleGithubCall, outputField, hidingRHP, updateFiles) {
function Compiler (editor, handleGithubCall, outputField, hidingRHP, updateFiles) {
var renderer = new Renderer(editor, this, updateFiles);
var compileJSON;
@ -18,7 +18,7 @@ function Compiler(editor, handleGithubCall, outputField, hidingRHP, updateFiles)
var compileTimeout = null;
function onChange() {
function onChange () {
var input = editor.getValue();
if (input === '') {
editor.setCacheFileContent('');
@ -33,7 +33,7 @@ function Compiler(editor, handleGithubCall, outputField, hidingRHP, updateFiles)
editor.onChangeSetup(onChange);
var compile = function(missingInputs) {
var compile = function (missingInputs) {
editor.clearAnnotations();
sourceAnnotations = [];
outputField.empty();
@ -42,7 +42,7 @@ function Compiler(editor, handleGithubCall, outputField, hidingRHP, updateFiles)
var files = {};
files[editor.getCacheFile()] = input;
gatherImports(files, missingInputs, function(input, error) {
gatherImports(files, missingInputs, function (input, error) {
outputField.empty();
if (input === null) {
renderer.error(error);
@ -54,41 +54,41 @@ function Compiler(editor, handleGithubCall, outputField, hidingRHP, updateFiles)
};
this.compile = compile;
this.addAnnotation = function(annotation) {
this.addAnnotation = function (annotation) {
sourceAnnotations[sourceAnnotations.length] = annotation;
editor.setAnnotations(sourceAnnotations);
};
this.setCompileJSON = function() {
compileJSON = function(source, optimize) { compilationFinished('{}'); };
this.setCompileJSON = function () {
compileJSON = function (source, optimize) { compilationFinished('{}'); };
};
function onCompilerLoaded(setVersionText) {
function onCompilerLoaded (setVersionText) {
if (worker === null) {
var compile;
var missingInputs = [];
if ('_compileJSONCallback' in Module) {
compilerAcceptsMultipleFiles = true;
var missingInputsCallback = Module.Runtime.addFunction(function(path, contents, error) {
var missingInputsCallback = Module.Runtime.addFunction(function (path, contents, error) {
missingInputs.push(Module.Pointer_stringify(path));
});
var compileInternal = Module.cwrap('compileJSONCallback', 'string', ['string', 'number', 'number']);
compile = function(input, optimize) {
var compileInternal = Module.cwrap('compileJSONCallback', 'string', [ 'string', 'number', 'number' ]);
compile = function (input, optimize) {
missingInputs.length = 0;
return compileInternal(input, optimize, missingInputsCallback);
};
} else if ('_compileJSONMulti' in Module) {
compilerAcceptsMultipleFiles = true;
compile = Module.cwrap('compileJSONMulti', 'string', ['string', 'number']);
compile = Module.cwrap('compileJSONMulti', 'string', [ 'string', 'number' ]);
} else {
compilerAcceptsMultipleFiles = false;
compile = Module.cwrap('compileJSON', 'string', ['string', 'number']);
compile = Module.cwrap('compileJSON', 'string', [ 'string', 'number' ]);
}
compileJSON = function(source, optimize, cb) {
compileJSON = function (source, optimize, cb) {
try {
var result = compile(source, optimize);
} catch (exception) {
result = JSON.stringify({error: 'Uncaught JavaScript exception:\n' + exception});
result = JSON.stringify({ error: 'Uncaught JavaScript exception:\n' + exception });
}
compilationFinished(result, missingInputs);
};
@ -99,7 +99,7 @@ function Compiler(editor, handleGithubCall, outputField, hidingRHP, updateFiles)
};
this.onCompilerLoaded = onCompilerLoaded;
function compilationFinished(result, missingInputs) {
function compilationFinished (result, missingInputs) {
var data;
var noFatalErrors = true; // ie warnings are ok
@ -115,7 +115,7 @@ function Compiler(editor, handleGithubCall, outputField, hidingRHP, updateFiles)
if (utils.errortype(data['error']) !== 'warning') noFatalErrors = false;
}
if (data['errors'] !== undefined) {
data['errors'].forEach(function(err) {
data['errors'].forEach(function (err) {
renderer.error(err);
if (utils.errortype(err) !== 'warning') noFatalErrors = false;
});
@ -127,11 +127,11 @@ function Compiler(editor, handleGithubCall, outputField, hidingRHP, updateFiles)
renderer.contracts(data, editor.getValue());
}
this.initializeWorker = function(version, setVersionText) {
this.initializeWorker = function (version, setVersionText) {
if (worker !== null)
worker.terminate();
worker = new Worker('worker.js');
worker.addEventListener('message', function(msg) {
worker.addEventListener('message', function (msg) {
var data = msg.data;
switch (data.cmd) {
case 'versionLoaded':
@ -144,15 +144,15 @@ function Compiler(editor, handleGithubCall, outputField, hidingRHP, updateFiles)
break;
};
});
worker.onerror = function(msg) { console.log(msg.data); };
worker.addEventListener('error', function(msg) { console.log(msg.data); });
compileJSON = function(source, optimize) {
worker.onerror = function (msg) { console.log(msg.data); };
worker.addEventListener('error', function (msg) { console.log(msg.data); });
compileJSON = function (source, optimize) {
worker.postMessage({cmd: 'compile', source: source, optimize: optimize});
};
worker.postMessage({cmd: 'loadVersion', data: 'https://ethereum.github.io/solc-bin/bin/' + version});
};
function gatherImports(files, importHints, cb) {
function gatherImports (files, importHints, cb) {
importHints = importHints || [];
if (!compilerAcceptsMultipleFiles)
{
@ -182,7 +182,7 @@ function Compiler(editor, handleGithubCall, outputField, hidingRHP, updateFiles)
files[m] = cachedRemoteFiles[m];
reloop = true;
} else if (githubMatch = /^(https?:\/\/)?(www.)?github.com\/([^\/]*\/[^\/]*)\/(.*)/.exec(m)) {
handleGithubCall(githubMatch[3], githubMatch[4], function(result) {
handleGithubCall(githubMatch[3], githubMatch[4], function (result) {
if ('content' in result)
{
var content = Base64.decode(result.content);
@ -192,7 +192,7 @@ function Compiler(editor, handleGithubCall, outputField, hidingRHP, updateFiles)
}
else
cb(null, 'Unable to import "' + m + '"');
}).fail(function(){
}).fail(function () {
cb(null, 'Unable to import "' + m + '"');
});
return;
@ -202,7 +202,7 @@ function Compiler(editor, handleGithubCall, outputField, hidingRHP, updateFiles)
}
}
} while (reloop);
cb(JSON.stringify({'sources':files}));
cb(JSON.stringify({ 'sources': files }));
}
}

@ -3,9 +3,9 @@ var utils = require('./utils');
var ace = require('brace');
require('../mode-solidity.js');
function Editor(loadingFromGist) {
function Editor (loadingFromGist) {
this.newFile = function() {
this.newFile = function () {
untitledCount = '';
while (window.localStorage[SOL_CACHE_UNTITLED + untitledCount])
untitledCount = (untitledCount - 0) + 1;
@ -14,40 +14,40 @@ function Editor(loadingFromGist) {
this.setCacheFileContent('');
};
this.setCacheFileContent = function(content) {
this.setCacheFileContent = function (content) {
window.localStorage.setItem(SOL_CACHE_FILE, content);
};
this.setCacheFile = function(cacheFile) {
this.setCacheFile = function (cacheFile) {
SOL_CACHE_FILE = utils.fileKey(cacheFile);
};
this.getCacheFile = function() {
this.getCacheFile = function () {
return utils.fileNameFromKey(SOL_CACHE_FILE);
};
this.cacheFileIsPresent = function() {
this.cacheFileIsPresent = function () {
return !!SOL_CACHE_FILE;
};
this.setNextFile = function(fileKey) {
var index = this.getFiles().indexOf( fileKey );
this.setCacheFile(this.getFiles()[ Math.max(0, index - 1)]);
this.setNextFile = function (fileKey) {
var index = this.getFiles().indexOf(fileKey);
this.setCacheFile(this.getFiles()[ Math.max(0, index - 1) ]);
};
this.resetSession = function() {
editor.setSession( sessions[SOL_CACHE_FILE] );
this.resetSession = function () {
editor.setSession(sessions[SOL_CACHE_FILE]);
editor.focus();
};
this.hasFile = function(name) {
this.hasFile = function (name) {
return this.getFiles().indexOf(utils.fileKey(name)) !== -1
};
this.getFiles = function() {
this.getFiles = function () {
var files = [];
for (var f in localStorage ) {
if (f.indexOf( utils.getCacheFilePrefix(), 0 ) === 0) {
for (var f in localStorage) {
if (f.indexOf(utils.getCacheFilePrefix(), 0) === 0) {
files.push(f);
if (!sessions[f]) sessions[f] = newEditorSession(f);
}
@ -55,7 +55,7 @@ function Editor(loadingFromGist) {
return files;
}
this.packageFiles = function() {
this.packageFiles = function () {
var files = {};
var filesArr = this.getFiles();
@ -67,46 +67,46 @@ function Editor(loadingFromGist) {
return files;
};
this.resize = function() {
this.resize = function () {
editor.resize();
var session = editor.getSession();
session.setUseWrapMode(document.querySelector('#editorWrap').checked);
if(session.getUseWrapMode()) {
if (session.getUseWrapMode()) {
var characterWidth = editor.renderer.characterWidth;
var contentWidth = editor.container.ownerDocument.getElementsByClassName('ace_scroller')[0].clientWidth;
if(contentWidth > 0) {
if (contentWidth > 0) {
session.setWrapLimit(parseInt(contentWidth / characterWidth, 10));
}
}
};
this.getValue = function() {
this.getValue = function () {
return editor.getValue();
};
this.clearAnnotations = function() {
this.clearAnnotations = function () {
editor.getSession().clearAnnotations();
};
this.setAnnotations = function(sourceAnnotations) {
this.setAnnotations = function (sourceAnnotations) {
editor.getSession().setAnnotations(sourceAnnotations);
};
this.onChangeSetup = function(onChange) {
this.onChangeSetup = function (onChange) {
editor.getSession().on('change', onChange);
editor.on('changeSession', function(){
editor.on('changeSession', function () {
editor.getSession().on('change', onChange);
onChange();
})
};
this.handleErrorClick = function(errLine, errCol) {
this.handleErrorClick = function (errLine, errCol) {
editor.focus();
editor.gotoLine(errLine + 1, errCol - 1, true);
};
function newEditorSession(filekey) {
function newEditorSession (filekey) {
var s = new ace.EditSession(window.localStorage[filekey], 'ace/mode/javascript')
s.setUndoManager(new ace.UndoManager());
s.setTabSize(4);
@ -115,10 +115,10 @@ function Editor(loadingFromGist) {
return s;
}
function setupStuff(files) {
function setupStuff (files) {
var untitledCount = '';
if (!files.length || window.localStorage['sol-cache']) {
if(loadingFromGist) return;
if (loadingFromGist) return;
// Backwards-compatibility
while (window.localStorage[SOL_CACHE_UNTITLED + untitledCount])
untitledCount = (untitledCount - 0) + 1;
@ -133,7 +133,7 @@ function Editor(loadingFromGist) {
sessions[files[x]] = newEditorSession(files[x])
}
editor.setSession( sessions[SOL_CACHE_FILE] );
editor.setSession(sessions[SOL_CACHE_FILE]);
editor.resize(true);
}

@ -1,6 +1,6 @@
var queryParams = require('./query-params');
function handleLoad(cb) {
function handleLoad (cb) {
var params = queryParams.get();
var loadingFromGist = false;
if (typeof params['gist'] !== undefined) {
@ -8,7 +8,7 @@ function handleLoad(cb) {
if (params['gist'] === '') {
var str = prompt('Enter the URL or ID of the Gist you would like to load.');
if (str !== '') {
gistId = getGistId( str );
gistId = getGistId(str);
loadingFromGist = !!gistId;
}
} else {
@ -20,7 +20,7 @@ function handleLoad(cb) {
return loadingFromGist;
}
function getGistId(str) {
function getGistId (str) {
var idr = /[0-9A-Fa-f]{8,}/;
var match = idr.exec(str);
return match ? match[0] : null;

@ -1,4 +1,4 @@
function getQueryParams() {
function getQueryParams () {
var qs = window.location.hash.substr(1);
if (window.location.search.length > 0) {
@ -16,7 +16,7 @@ function getQueryParams() {
return params;
}
function updateQueryParams(params) {
function updateQueryParams (params) {
var currentParams = getQueryParams();
var keys = Object.keys(params);
for (var x in keys) {
@ -24,7 +24,7 @@ function updateQueryParams(params) {
}
var queryString = '#';
var updatedKeys = Object.keys(currentParams);
for( var y in updatedKeys) {
for (var y in updatedKeys) {
queryString += updatedKeys[y] + '=' + currentParams[updatedKeys[y]] + '&';
}
window.location.hash = queryString.slice(0, -1);

@ -5,15 +5,15 @@ var UniversalDApp = require('../universal-dapp.js');
var utils = require('./utils');
function Renderer(editor, compiler, updateFiles) {
function Renderer (editor, compiler, updateFiles) {
var detailsOpen = {};
var executionContext = 'vm';
// Forcing all of this setup into its own scope.
(function(){
(function () {
function executionContextChange (ev) {
if (ev.target.value === 'web3' && !confirm('Are you sure you want to connect to a local ethereum node?') ) {
if (ev.target.value === 'web3' && !confirm('Are you sure you want to connect to a local ethereum node?')) {
$vmToggle.get(0).checked = true;
executionContext = 'vm';
} else {
@ -23,7 +23,7 @@ function Renderer(editor, compiler, updateFiles) {
compiler.compile();
}
function setProviderFromEndpoint() {
function setProviderFromEndpoint () {
var endpoint = $web3endpoint.val();
if (endpoint === 'ipc')
web3.setProvider(new web3.providers.IpcProvider());
@ -40,19 +40,19 @@ function Renderer(editor, compiler, updateFiles) {
$vmToggle.get(0).checked = true;
$vmToggle.on('change', executionContextChange );
$web3Toggle.on('change', executionContextChange );
$web3endpoint.on('change', function() {
$vmToggle.on('change', executionContextChange);
$web3Toggle.on('change', executionContextChange);
$web3endpoint.on('change', function () {
setProviderFromEndpoint();
if (executionContext === 'web3') compiler.compile();
});
})();
function renderError(message) {
function renderError (message) {
var type = utils.errortype(message);
var $pre = $('<pre />').text(message);
var $error = $('<div class="sol ' + type + '"><div class="close"><i class="fa fa-close"></i></div></div>').prepend($pre);
$('#output').append( $error );
$('#output').append($error);
var err = message.match(/^([^:]*):([0-9]*):(([0-9]*):)? /);
if (err) {
var errFile = err[1];
@ -66,16 +66,16 @@ function Renderer(editor, compiler, updateFiles) {
type: type
});
}
$error.click(function(ev){
$error.click(function (ev) {
if (errFile !== '' && errFile !== editor.getCacheFile() && editor.hasFile(errFile)) {
// Switch to file
editor.setCacheFile(errFile);
updateFiles();
//@TODO could show some error icon in files with errors
// @TODO could show some error icon in files with errors
}
editor.handleErrorClick(errLine, errCol);
});
$error.find('.close').click(function(ev){
$error.find('.close').click(function (ev) {
ev.preventDefault();
$error.remove();
return false;
@ -84,11 +84,11 @@ function Renderer(editor, compiler, updateFiles) {
};
this.error = renderError;
var combined = function(contractName, jsonInterface, bytecode){
return JSON.stringify([{name: contractName, interface: jsonInterface, bytecode: bytecode}]);
var combined = function (contractName, jsonInterface, bytecode) {
return JSON.stringify([{ name: contractName, interface: jsonInterface, bytecode: bytecode }]);
};
function renderContracts(data, source) {
function renderContracts (data, source) {
var udappContracts = [];
for (var contractName in data.contracts) {
@ -104,19 +104,19 @@ function Renderer(editor, compiler, updateFiles) {
mode: executionContext === 'vm' ? 'vm' : 'web3',
web3: web3,
removable: false,
getAddress: function(){ return $('#txorigin').val(); },
getValue: function(){
getAddress: function () { return $('#txorigin').val(); },
getValue: function () {
var comp = $('#value').val().split(' ');
return web3.toWei(comp[0], comp.slice(1).join(' '));
},
removable_instances: true,
renderOutputModifier: function(contractName, $contractOutput) {
renderOutputModifier: function (contractName, $contractOutput) {
var contract = data.contracts[contractName];
return $contractOutput
.append(textRow('Bytecode', contract.bytecode))
.append(textRow('Interface', contract['interface']))
.append(textRow('Web3 deploy', gethDeploy(contractName.toLowerCase(),contract['interface'],contract.bytecode), 'deploy'))
.append(textRow('uDApp', combined(contractName,contract['interface'],contract.bytecode), 'deploy'))
.append(textRow('Web3 deploy', gethDeploy(contractName.toLowerCase(), contract['interface'], contract.bytecode), 'deploy'))
.append(textRow('uDApp', combined(contractName, contract['interface'], contract.bytecode), 'deploy'))
.append(getDetails(contract, source, contractName));
}
});
@ -125,43 +125,43 @@ function Renderer(editor, compiler, updateFiles) {
var $txOrigin = $('#txorigin');
function renderAccounts(err, accounts) {
function renderAccounts (err, accounts) {
if (err)
renderError(err.message);
if (accounts && accounts[0]){
if (accounts && accounts[0]) {
$txOrigin.empty();
for( var a in accounts) { $txOrigin.append($('<option />').val(accounts[a]).text(accounts[a])); }
for (var a in accounts) { $txOrigin.append($('<option />').val(accounts[a]).text(accounts[a])); }
$txOrigin.val(accounts[0]);
} else $txOrigin.val('unknown');
}
dapp.getAccounts(renderAccounts);
$contractOutput.find('.title').click(function(ev){ $(this).closest('.contract').toggleClass('hide'); });
$('#output').append( $contractOutput );
$('.col2 input,textarea').click(function() { this.select(); });
$contractOutput.find('.title').click(function (ev) { $(this).closest('.contract').toggleClass('hide'); });
$('#output').append($contractOutput);
$('.col2 input,textarea').click(function () { this.select(); });
};
this.contracts = renderContracts;
var tableRowItems = function(first, second, cls) {
var tableRowItems = function (first, second, cls) {
return $('<div class="crow"/>')
.addClass(cls)
.append($('<div class="col1">').append(first))
.append($('<div class="col2">').append(second));
};
var tableRow = function(description, data) {
var tableRow = function (description, data) {
return tableRowItems(
$('<span/>').text(description),
$('<input readonly="readonly"/>').val(data));
};
var textRow = function(description, data, cls) {
var textRow = function (description, data, cls) {
return tableRowItems(
$('<strong/>').text(description),
$('<textarea readonly="readonly" class="gethDeployText"/>').val(data),
cls);
};
var getDetails = function(contract, source, contractName) {
var getDetails = function (contract, source, contractName) {
var button = $('<button>Toggle Details</button>');
var details = $('<div style="display: none;"/>')
.append(tableRow('Solidity Interface', contract.solidity_interface))
@ -181,14 +181,14 @@ function Renderer(editor, compiler, updateFiles) {
var assembly = $('<pre/>').text(formatAssemblyText(contract.assembly, '', source));
details.append(assembly);
}
button.click(function() { detailsOpen[contractName] = !detailsOpen[contractName]; details.toggle(); });
button.click(function () { detailsOpen[contractName] = !detailsOpen[contractName]; details.toggle(); });
if (detailsOpen[contractName])
details.show();
return $('<div class="contractDetails"/>').append(button).append(details);
};
var formatGasEstimates = function(data) {
var gasToText = function(g) { return g === null ? 'unknown' : g; }
var formatGasEstimates = function (data) {
var gasToText = function (g) { return g === null ? 'unknown' : g; }
var text = '';
var fun;
if ('creation' in data)
@ -202,11 +202,11 @@ function Renderer(editor, compiler, updateFiles) {
return text;
};
var formatAssemblyText = function(asm, prefix, source) {
if (typeof(asm) === typeof('') || asm === null || asm === undefined)
var formatAssemblyText = function (asm, prefix, source) {
if (typeof asm === typeof '' || asm === null || asm === undefined)
return prefix + asm + '\n';
var text = prefix + '.code\n';
$.each(asm['.code'], function(i, item) {
$.each(asm['.code'], function (i, item) {
var v = item.value === undefined ? '' : item.value;
var src = '';
if (item.begin !== undefined && item.end !== undefined)
@ -215,11 +215,11 @@ function Renderer(editor, compiler, updateFiles) {
src = src.slice(0, 30) + '...';
if (item.name !== 'tag')
text += ' ';
text += prefix + item.name + ' ' + v + '\t\t\t' + src + '\n';
text += prefix + item.name + ' ' + v + '\t\t\t' + src + '\n';
});
text += prefix + '.data\n';
if (asm['.data'])
$.each(asm['.data'], function(i, item) {
$.each(asm['.data'], function (i, item) {
text += ' ' + prefix + '' + i + ':\n';
text += formatAssemblyText(item, prefix + ' ', source);
});
@ -227,28 +227,28 @@ function Renderer(editor, compiler, updateFiles) {
return text;
};
function gethDeploy(contractName, jsonInterface, bytecode){
function gethDeploy (contractName, jsonInterface, bytecode) {
var code = '';
var funABI = getConstructorInterface(JSON.parse(jsonInterface));
funABI.inputs.forEach(function(inp) {
funABI.inputs.forEach(function (inp) {
code += 'var ' + inp.name + ' = /* var of type ' + inp.type + ' here */ ;\n';
});
code += 'var ' + contractName + 'Contract = web3.eth.contract(' + jsonInterface.replace('\n','') + ');'
+'\nvar ' + contractName + ' = ' + contractName + 'Contract.new(';
code += 'var ' + contractName + 'Contract = web3.eth.contract(' + jsonInterface.replace('\n', '') + ');' +
'\nvar ' + contractName + ' = ' + contractName + 'Contract.new(';
funABI.inputs.forEach(function(inp) {
funABI.inputs.forEach(function (inp) {
code += '\n ' + inp.name + ',';
});
code += '\n {'+
'\n from: web3.eth.accounts[0], '+
'\n data: \''+bytecode+'\', '+
'\n gas: 3000000'+
'\n }, function(e, contract){'+
'\n console.log(e, contract);'+
'\n if (typeof contract.address !== \'undefined\') {'+
code += '\n {' +
'\n from: web3.eth.accounts[0], ' +
'\n data: \'' + bytecode + '\', ' +
'\n gas: 3000000' +
'\n }, function (e, contract){' +
'\n console.log(e, contract);' +
'\n if (typeof contract.address !== \'undefined\') {' +
'\n console.log(\'Contract mined! address: \' + contract.address + \' transactionHash: \' + contract.transactionHash);' +
'\n }' +
'\n })';
@ -257,8 +257,8 @@ function Renderer(editor, compiler, updateFiles) {
return code;
}
function getConstructorInterface(abi) {
var funABI = {'name':'','inputs':[],'type':'constructor','outputs':[]};
function getConstructorInterface (abi) {
var funABI = { 'name': '', 'inputs': [], 'type': 'constructor', 'outputs': [] };
for (var i = 0; i < abi.length; i++)
if (abi[i].type === 'constructor') {
funABI.inputs = abi[i].inputs || [];

@ -1,8 +1,8 @@
var utils = require('./utils');
function StorageHandler(updateFiles) {
function StorageHandler (updateFiles) {
this.sync = function() {
this.sync = function () {
if (typeof chrome === 'undefined' || !chrome || !chrome.storage || !chrome.storage.sync) return;
@ -11,20 +11,20 @@ function StorageHandler(updateFiles) {
var count = 0
var dont = 0;
function check(key){
chrome.storage.sync.get( key, function(resp){
function check (key) {
chrome.storage.sync.get(key, function (resp) {
console.log('comparing to cloud', key, resp);
if (typeof resp[key] !== 'undefined' && obj[key] !== resp[key] && confirm('Overwrite "' + fileNameFromKey(key) + '"? Click Ok to overwrite local file with file from cloud. Cancel will push your local file to the cloud.')) {
console.log('Overwriting', key );
localStorage.setItem( key, resp[key] );
console.log('Overwriting', key);
localStorage.setItem(key, resp[key]);
updateFiles();
} else {
console.log( 'add to obj', obj, key);
console.log('add to obj', obj, key);
obj[key] = localStorage[key];
}
done++;
if (done >= count) chrome.storage.sync.set( obj, function(){
console.log( 'updated cloud files with: ', obj, this, arguments);
if (done >= count) chrome.storage.sync.set(obj, function () {
console.log('updated cloud files with: ', obj, this, arguments);
})
})
}

@ -1,18 +1,18 @@
var SOL_CACHE_FILE_PREFIX = 'sol-cache-file-';
function getCacheFilePrefix() {
function getCacheFilePrefix () {
return SOL_CACHE_FILE_PREFIX;
}
function fileKey( name ) {
function fileKey (name) {
return getCacheFilePrefix() + name;
}
function fileNameFromKey(key) {
return key.replace( getCacheFilePrefix(), '' );
function fileNameFromKey (key) {
return key.replace(getCacheFilePrefix(), '');
}
function errortype(message) {
function errortype (message) {
return message.match(/^.*:[0-9]*:[0-9]* Warning: /) ? 'warning' : 'error';
}

@ -2,4 +2,4 @@ require('es6-shim');
var app = require('./app.js');
var $ = require('jquery');
$(document).ready(function() { app.run(); });
$(document).ready(function () { app.run(); });

@ -10,7 +10,7 @@ function UniversalDApp (contracts, options) {
this.options = options || {};
this.$el = $('<div class="udapp" />');
this.contracts = contracts;
this.renderOutputModifier = options.renderOutputModifier || function(name, content) { return content; };
this.renderOutputModifier = options.renderOutputModifier || function (name, content) { return content; };
this.web3 = options.web3;
if (!this.web3) {
@ -40,7 +40,7 @@ UniversalDApp.prototype.addAccount = function (privateKey, balance) {
var address = ethJSUtil.privateToAddress(privateKey);
// FIXME: we don't care about the callback, but we should still make this proper
this.vm.stateManager.putAccountBalance(address, balance || 'f00000000000000001', function cb() {} );
this.vm.stateManager.putAccountBalance(address, balance || 'f00000000000000001', function cb () {});
this.accounts['0x' + address.toString('hex')] = { privateKey: privateKey, nonce: 0 };
}
@ -82,65 +82,65 @@ UniversalDApp.prototype.getBalance = function (address, cb) {
UniversalDApp.prototype.render = function () {
if (this.contracts.length === 0) {
this.$el.append( this.getABIInputForm() );
this.$el.append(this.getABIInputForm());
} else {
for (var c in this.contracts) {
var $contractEl = $('<div class="contract"/>');
if (this.contracts[c].address) {
this.getInstanceInterface(this.contracts[c], this.contracts[c].address, $contractEl );
this.getInstanceInterface(this.contracts[c], this.contracts[c].address, $contractEl);
} else {
var $title = $('<span class="title"/>').text( this.contracts[c].name );
var $title = $('<span class="title"/>').text(this.contracts[c].name);
if (this.contracts[c].bytecode) {
$title.append($('<div class="size"/>').text((this.contracts[c].bytecode.length / 2) + ' bytes'));
}
$contractEl.append( $title ).append( this.getCreateInterface( $contractEl, this.contracts[c]) );
$contractEl.append($title).append(this.getCreateInterface($contractEl, this.contracts[c]));
}
this.$el.append(this.renderOutputModifier(this.contracts[c].name, $contractEl));
}
}
var $legend = $('<div class="legend" />')
.append( $('<div class="attach"/>').text('Attach') )
.append( $('<div class="transact"/>').text('Transact') )
.append( $('<div class="call"/>').text('Call') );
.append($('<div class="attach"/>').text('Attach'))
.append($('<div class="transact"/>').text('Transact'))
.append($('<div class="call"/>').text('Call'));
this.$el.append( $('<div class="poweredBy" />')
.html('<a href="http://github.com/d11e9/universal-dapp">Universal ÐApp</a> powered by The Blockchain') );
this.$el.append($('<div class="poweredBy" />')
.html('<a href="http://github.com/d11e9/universal-dapp">Universal ÐApp</a> powered by The Blockchain'));
this.$el.append( $legend );
this.$el.append($legend);
return this.$el;
};
UniversalDApp.prototype.getContractByName = function(contractName) {
UniversalDApp.prototype.getContractByName = function (contractName) {
for (var c in this.contracts)
if (this.contracts[c].name === contractName)
return this.contracts[c];
return null;
};
UniversalDApp.prototype.getABIInputForm = function (cb){
UniversalDApp.prototype.getABIInputForm = function (cb) {
var self = this;
var $el = $('<div class="udapp-setup" />');
var $jsonInput = $('<textarea class="json" placeholder=\'[ { "name": name, "bytecode": bytecode, "interface": abi }, { ... } ]\'/>');
var $createButton = $('<button class="udapp-create"/>').text('Create a Universal ÐApp');
$createButton.click(function(ev){
var contracts = $.parseJSON( $jsonInput.val() );
$createButton.click(function (ev) {
var contracts = $.parseJSON($jsonInput.val());
if (cb) {
var err = null;
var dapp = null;
try {
dapp = new UniversalDApp( contracts, self.options );
} catch(e) {
dapp = new UniversalDApp(contracts, self.options);
} catch (e) {
err = e;
}
cb( err, dapp );
cb(err, dapp);
} else {
self.contracts = contracts;
self.$el.empty().append( self.render() );
self.$el.empty().append(self.render());
}
});
$el.append( $jsonInput ).append( $createButton );
$el.append($jsonInput).append($createButton);
return $el;
};
@ -150,21 +150,21 @@ UniversalDApp.prototype.getCreateInterface = function ($container, contract) {
var $createInterface = $('<div class="create"/>');
if (this.options.removable) {
var $close = $('<div class="udapp-close" />');
$close.click( function(){ self.$el.remove(); } );
$createInterface.append( $close );
$close.click(function () { self.$el.remove(); });
$createInterface.append($close);
}
var $newButton = this.getInstanceInterface( contract );
var $atButton = $('<button class="atAddress"/>').text('At Address').click( function(){ self.clickContractAt( self, $container.find('.createContract'), contract ); } );
$createInterface.append( $atButton ).append( $newButton );
var $newButton = this.getInstanceInterface(contract);
var $atButton = $('<button class="atAddress"/>').text('At Address').click(function () { self.clickContractAt(self, $container.find('.createContract'), contract); });
$createInterface.append($atButton).append($newButton);
return $createInterface;
};
UniversalDApp.prototype.getInstanceInterface = function (contract, address, $target) {
var self = this;
var abi = JSON.parse(contract.interface).sort(function(a,b){
var abi = JSON.parse(contract.interface).sort(function (a, b) {
if (a.name > b.name) return -1;
else return 1;
}).sort(function(a,b){
}).sort(function (a, b) {
if (a.constant === true) return -1;
else return 1;
});
@ -172,50 +172,50 @@ UniversalDApp.prototype.getInstanceInterface = function (contract, address, $tar
var funABI = this.getConstructorInterface(abi);
var $createInterface = $('<div class="createContract"/>');
var appendFunctions = function (address, $el){
var appendFunctions = function (address, $el) {
var $instance = $('<div class="instance"/>');
if (self.options.removable_instances) {
var $close = $('<div class="udapp-close" />');
$close.click( function(){ $instance.remove(); } );
$instance.append( $close );
$close.click(function () { $instance.remove(); });
$instance.append($close);
}
var context = self.options.vm ? 'memory' : 'blockchain';
var $title = $('<span class="title"/>').text( contract.name + ' at ' + (self.options.vm ? '0x' : '') + address.toString('hex') + ' (' + context + ')');
$title.click(function(){
var $title = $('<span class="title"/>').text(contract.name + ' at ' + (self.options.vm ? '0x' : '') + address.toString('hex') + ' (' + context + ')');
$title.click(function () {
$instance.toggleClass('hide');
});
var $events = $('<div class="events"/>');
var parseLogs = function(err,response) {
var parseLogs = function (err, response) {
if (err)
return;
var $event = $('<div class="event" />');
var $close = $('<div class="udapp-close" />');
$close.click( function(){ $event.remove(); } );
$close.click(function () { $event.remove(); });
$event.append( $('<span class="name"/>').text(response.event) )
.append( $('<span class="args" />').text( JSON.stringify(response.args, null, 2) ) )
.append( $close );
$event.append($('<span class="name"/>').text(response.event))
.append($('<span class="args" />').text(JSON.stringify(response.args, null, 2)))
.append($close);
$events.append( $event );
$events.append($event);
};
if (self.options.vm){
if (self.options.vm) {
// FIXME: support indexed events
var eventABI = {};
$.each(abi, function(i, funABI) {
$.each(abi, function (i, funABI) {
if (funABI.type !== 'event') return;
var hash = ethJSABI.eventID(funABI.name, funABI.inputs.map(function(item) { return item.type; }));
var hash = ethJSABI.eventID(funABI.name, funABI.inputs.map(function (item) { return item.type; }));
eventABI[hash.toString('hex')] = { event: funABI.name, inputs: funABI.inputs };
});
self.vm.on('afterTx', function(response){
self.vm.on('afterTx', function (response) {
for (var i in response.vm.logs) {
// [address, topics, mem]
var log = response.vm.logs[i];
@ -240,36 +240,36 @@ UniversalDApp.prototype.getInstanceInterface = function (contract, address, $tar
var eventFilter = web3contract.at(address).allEvents();
eventFilter.watch(parseLogs);
}
$instance.append( $title );
$instance.append($title);
// Add the fallback function
$instance.append(self.getCallButton({
abi: { constant: false, inputs:[], name: '(fallback)', outputs: [], type: 'function' },
encode: function(args) {
abi: { constant: false, inputs: [], name: '(fallback)', outputs: [], type: 'function' },
encode: function (args) {
return '';
},
address: address
}));
$.each(abi, function(i, funABI) {
$.each(abi, function (i, funABI) {
if (funABI.type !== 'function') return;
// @todo getData cannot be used with overloaded functions
$instance.append(self.getCallButton({
abi: funABI,
encode: function(args) {
encode: function (args) {
var obj = web3contract.at('0x00')[funABI.name];
return obj.getData.apply(obj, args);
},
address: address
}));
});
($el || $createInterface ).append( $instance.append( $events ) );
($el || $createInterface).append($instance.append($events));
};
if (!address || !$target) {
$createInterface.append( this.getCallButton({
$createInterface.append(this.getCallButton({
abi: funABI,
encode: function(args) {
encode: function (args) {
var obj = web3contract.new;
return obj.getData.apply(obj, args);
},
@ -278,14 +278,14 @@ UniversalDApp.prototype.getInstanceInterface = function (contract, address, $tar
appendFunctions: appendFunctions
}));
} else {
appendFunctions( address, $target );
appendFunctions(address, $target);
}
return $createInterface;
};
UniversalDApp.prototype.getConstructorInterface = function(abi) {
var funABI = {'name':'','inputs':[],'type':'constructor','outputs':[]};
UniversalDApp.prototype.getConstructorInterface = function (abi) {
var funABI = { 'name': '', 'inputs': [], 'type': 'constructor', 'outputs': [] };
for (var i = 0; i < abi.length; i++)
if (abi[i].type === 'constructor') {
funABI.inputs = abi[i].inputs || [];
@ -294,15 +294,15 @@ UniversalDApp.prototype.getConstructorInterface = function(abi) {
return funABI;
};
UniversalDApp.prototype.getCallButton = function(args) {
UniversalDApp.prototype.getCallButton = function (args) {
var self = this;
// args.abi, args.encode, args.bytecode [constr only], args.address [fun only]
// args.contractName [constr only], args.appendFunctions [constr only]
var isConstructor = args.bytecode !== undefined;
var lookupOnly = ( args.abi.constant && !isConstructor );
var lookupOnly = (args.abi.constant && !isConstructor);
var inputs = '';
$.each(args.abi.inputs, function(i, inp) {
$.each(args.abi.inputs, function (i, inp) {
if (inputs !== '') inputs += ', ';
inputs += inp.type + ' ' + inp.name;
});
@ -310,10 +310,10 @@ UniversalDApp.prototype.getCallButton = function(args) {
var $outputOverride = $('<div class="value" />');
var outputSpan = $('<div class="output"/>');
var getReturnOutput = function(result) {
var getReturnOutput = function (result) {
var returnName = lookupOnly ? 'Value' : 'Result';
var returnCls = lookupOnly ? 'value' : 'returned';
return $('<div class="' + returnCls + '">').html('<strong>' + returnName + ':</strong> ' + JSON.stringify( result, null, 2 ) );
return $('<div class="' + returnCls + '">').html('<strong>' + returnName + ':</strong> ' + JSON.stringify(result, null, 2));
};
var getGasUsedOutput = function (result, vmResult) {
@ -321,12 +321,12 @@ UniversalDApp.prototype.getCallButton = function(args) {
var caveat = lookupOnly ? '<em>(<span class="caveat" title="Cost only applies when called by a contract">caveat</span>)</em>' : '';
if (result.gasUsed) {
var gas = result.gasUsed.toString(10);
$gasUsed.html('<strong>Transaction cost:</strong> ' + gas + ' gas. ' + caveat );
$gasUsed.html('<strong>Transaction cost:</strong> ' + gas + ' gas. ' + caveat);
}
if (vmResult.gasUsed) {
var $callGasUsed = $('<div class="gasUsed">');
var gas = vmResult.gasUsed.toString(10);
$callGasUsed.append('<strong>Execution cost:</strong> ' + gas + ' gas.' );
$callGasUsed.append('<strong>Execution cost:</strong> ' + gas + ' gas.');
$gasUsed.append($callGasUsed);
}
return $gasUsed;
@ -345,28 +345,28 @@ UniversalDApp.prototype.getCallButton = function(args) {
return $('<div class="decoded">').html('<strong>Decoded:</strong> ').append($decoded);
};
var getOutput = function() {
var getOutput = function () {
var $result = $('<div class="result" />');
var $close = $('<div class="udapp-close" />');
$close.click( function(){ $result.remove(); } );
$result.append( $close );
$close.click(function () { $result.remove(); });
$result.append($close);
return $result;
};
var clearOutput = function($result) {
var clearOutput = function ($result) {
$(':not(.udapp-close)', $result).remove();
};
var replaceOutput = function($result, message) {
var replaceOutput = function ($result, message) {
clearOutput($result);
$result.append(message);
};
var handleCallButtonClick = function(ev, $result) {
var handleCallButtonClick = function (ev, $result) {
if (!$result) {
$result = getOutput();
if (lookupOnly && !inputs.length)
$outputOverride.empty().append( $result );
$outputOverride.empty().append($result);
else
outputSpan.append( $result );
outputSpan.append($result);
}
var funArgs = '';
@ -380,7 +380,7 @@ UniversalDApp.prototype.getCallButton = function(args) {
if (!isConstructor || funArgs.length > 0) {
try {
data = args.encode(funArgs);
} catch(e) {
} catch (e) {
replaceOutput($result, $('<span/>').text('Error encoding arguments: ' + e));
return;
}
@ -395,7 +395,7 @@ UniversalDApp.prototype.getCallButton = function(args) {
if (args.bytecode.indexOf('_') >= 0) {
replaceOutput($result, $('<span>Deploying and linking required libraries...</span>'));
if (self.options.vm)
self.linkBytecode(args.contractName, function(err, bytecode) {
self.linkBytecode(args.contractName, function (err, bytecode) {
if (err)
replaceOutput($result, $('<span/>').text('Error deploying required libraries: ' + err));
else {
@ -410,7 +410,7 @@ UniversalDApp.prototype.getCallButton = function(args) {
data = args.bytecode + data;
}
self.runTx(data, args, function(err, result) {
self.runTx(data, args, function (err, result) {
if (err) {
replaceOutput($result, $('<span/>').text(err).addClass('error'));
} else if (self.options.vm && result.vm.exception && result.vm.exceptionError) {
@ -420,7 +420,7 @@ UniversalDApp.prototype.getCallButton = function(args) {
} else if (self.options.vm && isConstructor) {
replaceOutput($result, getGasUsedOutput(result, result.vm));
args.appendFunctions(result.createdAddress);
} else if (self.options.vm){
} else if (self.options.vm) {
var outputObj = '0x' + result.vm.return.toString('hex');
clearOutput($result);
$result.append(getReturnOutput(outputObj)).append(getGasUsedOutput(result, result.vm));
@ -457,16 +457,16 @@ UniversalDApp.prototype.getCallButton = function(args) {
} else {
function tryTillResponse (txhash, done) {
this.web3.eth.getTransactionReceipt(result, testResult );
this.web3.eth.getTransactionReceipt(result, testResult);
function testResult (err, address) {
if (!err && !address) {
setTimeout( function(){ tryTillResponse(txhash, done); }, 500);
} else done( err, address );
setTimeout(function () { tryTillResponse(txhash, done); }, 500);
} else done(err, address);
}
}
tryTillResponse( result, function(err, result) {
tryTillResponse(result, function (err, result) {
if (err) replaceOutput($result, $('<span/>').text(err).addClass('error'));
else if (isConstructor) {
$result.html('');
@ -482,10 +482,10 @@ UniversalDApp.prototype.getCallButton = function(args) {
};
var button = $('<button />')
.addClass( 'call' )
.addClass('call')
.attr('title', args.abi.name)
.text(args.bytecode ? 'Create' : args.abi.name)
.click( handleCallButtonClick );
.click(handleCallButtonClick);
if (lookupOnly && !inputs.length) {
handleCallButtonClick();
@ -493,15 +493,15 @@ UniversalDApp.prototype.getCallButton = function(args) {
var $contractProperty = $('<div class="contractProperty"/>');
$contractProperty
.toggleClass( 'constant', !isConstructor && args.abi.constant )
.toggleClass( 'hasArgs', args.abi.inputs.length > 0)
.toggleClass( 'constructor', isConstructor)
.toggleClass('constant', !isConstructor && args.abi.constant)
.toggleClass('hasArgs', args.abi.inputs.length > 0)
.toggleClass('constructor', isConstructor)
.append(button)
.append( (lookupOnly && !inputs.length) ? $outputOverride : inputField );
.append((lookupOnly && !inputs.length) ? $outputOverride : inputField);
return $contractProperty.append(outputSpan);
};
UniversalDApp.prototype.linkBytecode = function(contractName, cb) {
UniversalDApp.prototype.linkBytecode = function (contractName, cb) {
var bytecode = this.getContractByName(contractName).bytecode;
if (bytecode.indexOf('_') < 0)
return cb(null, bytecode);
@ -512,7 +512,7 @@ UniversalDApp.prototype.linkBytecode = function(contractName, cb) {
if (!this.getContractByName(libraryName))
return cb('Library ' + libraryName + ' not found.');
var self = this;
this.deployLibrary(libraryName, function(err, address) {
this.deployLibrary(libraryName, function (err, address) {
if (err) return cb(err);
var libLabel = '__' + libraryName + Array(39 - libraryName.length).join('_');
var hexAddress = address.toString('hex');
@ -525,18 +525,18 @@ UniversalDApp.prototype.linkBytecode = function(contractName, cb) {
});
};
UniversalDApp.prototype.deployLibrary = function(contractName, cb) {
UniversalDApp.prototype.deployLibrary = function (contractName, cb) {
if (this.getContractByName(contractName).address)
return cb(null, this.getContractByName(contractName).address);
var self = this;
var bytecode = this.getContractByName(contractName).bytecode;
if (bytecode.indexOf('_') >= 0)
this.linkBytecode(contractName, function(err, bytecode) {
this.linkBytecode(contractName, function (err, bytecode) {
if (err) cb(err);
else self.deployLibrary(contractName, cb);
});
else {
this.runTx(bytecode, {abi: {constant: false}, bytecode: bytecode}, function(err, result) {
this.runTx(bytecode, { abi: { constant: false }, bytecode: bytecode }, function (err, result) {
if (err) return cb(err);
self.getContractByName(contractName).address = result.createdAddress;
cb(err, result.createdAddress);
@ -544,12 +544,12 @@ UniversalDApp.prototype.deployLibrary = function(contractName, cb) {
}
};
UniversalDApp.prototype.clickContractAt = function ( self, $output, contract ) {
var address = prompt( 'What Address is this contract at in the Blockchain? ie: 0xdeadbeaf...' );
self.getInstanceInterface(contract, address, $output );
UniversalDApp.prototype.clickContractAt = function (self, $output, contract) {
var address = prompt('What Address is this contract at in the Blockchain? ie: 0xdeadbeaf...');
self.getInstanceInterface(contract, address, $output);
};
UniversalDApp.prototype.runTx = function( data, args, cb) {
UniversalDApp.prototype.runTx = function (data, args, cb) {
var self = this;
var to = args.address;
var constant = args.abi.constant;
@ -578,12 +578,12 @@ UniversalDApp.prototype.runTx = function( data, args, cb) {
value: value
};
if (constant && !isConstructor) {
this.web3.eth.call( tx, cb );
this.web3.eth.call(tx, cb);
} else {
this.web3.eth.estimateGas( tx, function(err, resp){
this.web3.eth.estimateGas(tx, function (err, resp) {
tx.gas = resp;
if (!err) self.web3.eth.sendTransaction( tx, cb );
else cb( err, resp);
if (!err) self.web3.eth.sendTransaction(tx, cb);
else cb(err, resp);
});
}
} else {
@ -593,7 +593,7 @@ UniversalDApp.prototype.runTx = function( data, args, cb) {
tx = new EthJSTX({
nonce: new Buffer([account.nonce++]), //@todo count beyond 255
gasPrice: 1,
gasLimit: 3000000000, //plenty
gasLimit: 3000000000, // plenty
to: to,
value: new this.BN(value, 10),
data: new Buffer(data.slice(2), 'hex')
@ -609,7 +609,7 @@ UniversalDApp.prototype.runTx = function( data, args, cb) {
});
this.vm.runTx({block: block, tx: tx, skipBalance: true, skipNonce: true, enableHomestead: true}, cb);
} catch (e) {
cb( e, null );
cb(e, null);
}
}
};

Loading…
Cancel
Save