reorganizing because zx needs to feel special

This commit is contained in:
2022-10-05 08:22:45 -06:00
parent 822ffa6c94
commit d1b40247be
84 changed files with 1 additions and 1 deletions
@@ -0,0 +1,160 @@
import * as ae_node from './parasite/ae_node.js';
import * as sk from '../sidekick_dist/dist_js/sidekick.js';
/**
* Transfer money to target address
*/
async function
transfer(skl : sk.Skylight,
target_addr : string,
amount : number)
: Promise<any>
{
let endpoint = ae_node.URL_TESTNET;
let src_addr = await sk.address(skl, sk.TIMEOUT_DEF_ADDRESS);
let spendtx = {'recipient_id' : target_addr,
'amount' : amount,
'fee' : ae_node.MIN_FEE,
'sender_id' : src_addr,
'payload' : ""};
let tx_obj = await ae_node.PostSpend(endpoint, spendtx) as ae_node.Tx;
let ret =
await sk.tx_sign_no_propagate(skl,
tx_obj,
sk.NETWORK_ID_TESTNET,
sk.TIMEOUT_DEF_SIGN);
return ret
}
function
current_to_done(class_name : string)
: void
{
let class_items = document.getElementsByClassName(class_name);
for (let class_item of class_items)
{
class_item.classList.remove('current');
class_item.classList.add('done');
}
}
function
disabled_to_current(class_name : string)
: void
{
let class_items = document.getElementsByClassName(class_name);
for (let class_item of class_items)
{
class_item.classList.remove('disabled');
class_item.classList.add('current');
}
}
// connect to superhero do what I mean
async function
step1(skl : sk.Skylight)
: Promise<void>
{
//// await sk.connect_dwim(skl,
//// sk.TIMEOUT_DEF_DETECT,
//// sk.TIMEOUT_DEF_CONNECT,
//// sk.TIMEOUT_DEF_ADDRESS);
//console.log('telling to listen!');
//await sk.listen(skl);
//console.log('listening!');
//console.log('detecting!');
//await sk.detect_dwim(skl, sk.);
//console.log('detected!');
//console.log('connecting!');
//await skl.connect(60000);
//console.log('connected!');
//console.log('addressing!');
//await skl.address(60000);
//console.log('addressed!');
//// sk.TIMEOUT_DEF_DETECT,
//// sk.TIMEOUT_DEF_CONNECT,
//// sk.TIMEOUT_DEF_ADDRESS);
// get wallet address
let wallet_addr = await sk.handshake_def(skl);
// put it in the thing
// bang = turn off the null warning
document.getElementById('user-wallet-address')!.innerHTML = wallet_addr;
// update style
current_to_done('step1');
disabled_to_current('step2');
}
// do tx
async function
step2(skl : sk.Skylight)
: Promise<void>
{
// The angle bracket is typescript type inference jizz; doesn't
// change runtime behavior
//
// https://stackoverflow.com/questions/12989741/the-property-value-does-not-exist-on-value-of-type-htmlelement
let target_addr = (<HTMLInputElement>document.getElementById('step2-recip')).value;
let amts = (<HTMLInputElement>document.getElementById('step2-amt')).value;
let amt = parseInt(amts);
// FIXME (dak)
// @ts-ignore implicit any
let my_transfer = await transfer(skl, target_addr, amt);
let my_transfer_text = sk.pf(my_transfer);
// add info
// bang is typescript jizz which means assume not null
document.getElementById("step3-transaction-info")!.innerHTML =
my_transfer_text;
// update style
current_to_done('step2');
disabled_to_current('step3');
}
async function main()
{
//// this turns on the console logger
//sidekick.snoop_console();
let skl = await sk.start();
// as = type inference helper; doesn't affect runtime js
let step1_fun =
async function()
{
step1(skl)
}
let step2_fun =
async function()
{
step2(skl)
}
// the exclamation point turns off the "object is possibly null"
// typecheck
document.getElementById('btn-step1')!.addEventListener('click', step1_fun);
document.getElementById('btn-step2')!.addEventListener('click', step2_fun);
//let foo = async () => {console.log(my_skylight.msgr.msgq.queue);};
//while(true) {
// await foo();
// await helpers.sleep(1000);
//}
}
main();
@@ -0,0 +1,222 @@
// TODO: make this all into top-level calls
import * as ae_compiler from './parasite/ae_compiler.js';
import * as ae_node from './parasite/ae_node.js';
import * as sidekick from '../sidekick_dist/dist_js/sidekick.js';
function
value_of_id
(str : string)
: string
{
// angle bracket jizz is type inference jizz; does not change
// runtime behavior;
//
// https://stackoverflow.com/questions/12989741/the-property-value-does-not-exist-on-value-of-type-htmlelement
return (<HTMLInputElement>document.getElementById(str)).value;
}
// COMPILE
async function
user_clicked_insert
()
: Promise<void>
{
let template_name = value_of_id("template-name");
let template_resp = await fetch(`http://localhost:8001/contract-examples/${template_name}`);
let template_code = await template_resp.text();
// Angle brackets are type inference jizz
//
// https://stackoverflow.com/questions/12989741/the-property-value-does-not-exist-on-value-of-type-htmlelement
(<HTMLInputElement>document.getElementById('the-filename')).value = template_name;
// bang turns off null warning
document.getElementById('the-code')!.innerHTML = template_code;
}
// COMPILE
async function
user_clicked_compile
()
: Promise<void>
{
let code = value_of_id('the-code');
let filename = value_of_id('the-filename');
console.log('code:');
console.log(code);
let response = await ae_compiler.CompileContract(code, filename);
let status_n = response.status;
let status_t = response.statusText;
let result_json = await response.json();
console.log('status_n', status_n);
console.log('status_t', status_t);
console.log('result_t', result_json);
// bang turns off typescript possibly null warning
document.getElementById('compile-result-status')!.innerText = `${status_n} ${status_t}`;
document.getElementById('compile-result-json')!.innerHTML = sidekick.pf(result_json);
}
function
user_clicked_clear
()
: void
{
// bang turns off typescript possibly null warning
document.getElementById('compile-result-status')!.innerText = '';
document.getElementById('compile-result-json')!.innerHTML = '';
}
// ENCODE CALLDATA
async function
user_clicked_encode
()
: Promise<void>
{
let code = value_of_id('the-code');
let filename = value_of_id('the-filename');
let fn_name = value_of_id('EncodeCalldata-function-name');
let fn_args_s = value_of_id('EncodeCalldata-function-args');
let fn_args = JSON.parse(fn_args_s);
let response =
await ae_compiler.EncodeCalldata(code,
filename,
fn_name,
fn_args);
let status_n = response.status;
let status_t = response.statusText;
let result_json = await response.json();
console.log('status_n', status_n);
console.log('status_t', status_t);
console.log('result_t', result_json);
// bang turns off null warnings in tsc
document.getElementById('EncodeCalldata-result-status')!.innerText = `${status_n} ${status_t}`;
document.getElementById('EncodeCalldata-result-json')!.innerHTML = sidekick.pf(result_json);
}
function
user_clicked_encode_clear
()
: void
{
// bang turns off null warnings in tsc
document.getElementById('EncodeCalldata-result-status')!.innerText = '';
document.getElementById('EncodeCalldata-result-json')!.innerText = '';
}
// CONNECT TO SUPERHERO
async function
user_clicked_connect
(skl : sidekick.Skylight)
: Promise<void>
{
let wallet_addr = await sidekick.handshake_def(skl);
// put it in the thing
// bang turns off maybe null typescript warning
document.getElementById('user-wallet-address')!.innerHTML = wallet_addr;
}
async function
user_clicked_create
(skl : sidekick.Skylight)
: Promise<void>
{
// create_contract(whoami : string,
// code : string,
// filename : string,
// init_args : Array<string>)
let whoami = await sidekick.address(skl, sidekick.TIMEOUT_DEF_ADDRESS);
let code = value_of_id('the-code');
let filename = value_of_id('the-filename');
let fn_args_s = value_of_id('deploy-function-args');
let fn_args = JSON.parse(fn_args_s);
let resp = await ae_node.create_contract(whoami, code, filename, fn_args);
let resp_status_n = await resp.status;
let resp_status_t = await resp.statusText;
let resp_json = await resp.json();
// bang tsc null warning jizz
document.getElementById('contract-create-result-status')!.innerText = `${resp_status_n} ${resp_status_t}`;
document.getElementById('contract-create-result-json')!.innerHTML = sidekick.pf(resp_json);
// sign
let tx_base58str = resp_json.tx;
let tx_obj = {tx: tx_base58str};
let result = await sidekick.tx_sign_yes_propagate(skl, tx_obj, sidekick.NETWORK_ID_TESTNET, sidekick.TIMEOUT_DEF_SIGN);
// bang tsc null warning jizz
document.getElementById('superhero-sign-result-json')!.innerHTML = sidekick.pf(result);
// // try to post transaction
// console.log('attempting to post transaction');
// let posttx_resp = await ae_node.PostTransaction(ae_node.URL_TESTNET, {tx: result.signedTransaction});
// let posttx_resp_status_n = await posttx_resp.status;
// let posttx_resp_status_t = await posttx_resp.statusText;
// let posttx_resp_json = await posttx_resp.json();
//
// // fill in boxes
// // bang is tsc null checking warning turn off thing
// document.getElementById('post-transaction-result-status')!.innerHTML = `${posttx_resp_status_n} ${posttx_resp_status_t}`;
// document.getElementById('post-transaction-result-json')!.innerHTML = helpers.pf(posttx_resp_json);
}
// MAIN
async function
main
()
: Promise<void>
{
// bang tsc null warning jizz
// TEMPLATE NAME
document.getElementById('insert-template-button')!.addEventListener('click', user_clicked_insert);
// COMPILE
document.getElementById('compile-button')!.addEventListener('click', user_clicked_compile);
document.getElementById('compile-clear')!.addEventListener('click', user_clicked_clear);
// ENCODE CALLDATA
document.getElementById('EncodeCalldata-button')!.addEventListener('click', user_clicked_encode);
document.getElementById('EncodeCalldata-button-clear')!.addEventListener('click', user_clicked_encode_clear);
// DEPLOY
// this turns on the console logger
sidekick.snoop_console();
let my_skylight = await sidekick.start();
// connect button
document .getElementById('connect-to-superhero')!
.addEventListener('click',
function () { user_clicked_connect(my_skylight) });
// create button
document .getElementById('contract-create-button')!
.addEventListener('click',
function () { user_clicked_create(my_skylight) });
}
main();
@@ -0,0 +1,96 @@
/*******************************************************************
** Compiler API
**
** The manner in which this module is laid out differs meaningfully
** from the `ae_node` module.
**
** - ae_node basically exposes a subset of the node interface as
** functions. It only black-boxes away the networking aspects.
**
** - part of the reason for this is that the data structures that get
** sent to the node tend to be pretty involved (lots of fields)
**
** - in general, the node interface is significantly more complicated
** than the compiler interface
**
** - by contrast, the data structures that get sent to the compiler
** tend to be pretty simple and only have a small number of fields
**
** - the manner in which this manifests is that ae_node functions
** tend to have a weird esoteric data structure as the input,
** because otherwise there would be too many parameters.
**
** here, there are few parameters, and they are passed directly
**
** - in general, the compiler has fewer things it can do, and the
** things it does tend to depend on less information. so this
** interface is significantly simpler than the node interface
*******************************************************************/
import * as net from './net.js';
const URL_COMPILER = 'https://compiler.aepps.com';
// endpoints
const EPT_CompileContract = URL_COMPILER + '/compile';
const EPT_EncodeCalldata = URL_COMPILER + '/encode-calldata';
//-------------------------------------------------------------------
// HELPERS
//-------------------------------------------------------------------
// make a CompileOpts data structure
function
compile_options(filename: string)
: object
{
return {"backend" : "fate",
"file_system" : {},
"src_file" : filename};
}
//-------------------------------------------------------------------
// API CALLS
//-------------------------------------------------------------------
// send back compile response
async function
CompileContract(code : string,
filename : string)
: Promise<Response>
{
let send_obj =
{"code" : code,
"options" : compile_options(filename)};
let response = await net.post_json_response(EPT_CompileContract, send_obj);
return response;
}
async function
EncodeCalldata(code : string,
filename : string,
function_name : string,
function_args : Array<string>)
: Promise<Response>
{
let send_obj =
{"source" : code,
"options" : compile_options(filename),
"function" : function_name,
"arguments" : function_args};
let response = await net.post_json_response(EPT_EncodeCalldata, send_obj);
return response;
}
export {
CompileContract,
EncodeCalldata
}
@@ -0,0 +1,272 @@
/********************************************************************
** Node API: functions for talking to an Aeternity node
**
** In the future, everything that this module does will be replaced
** by the backend.
**
** Functions should be sorted in alphabetical order.
**
** Names are what they are in the documentation
**
** Useful links:
**
** - HTML API docs : https://api-docs.aeternity.io/
** - YAML API docs : https://github.com/aeternity/aeternity/blob/master/apps/aehttp/priv/swagger.yaml
**
********************************************************************/
import * as net from './net.js'
import * as ae_compiler from './ae_compiler.js'
//-------------------------------------------------------------------
// CONSTANTS
//-------------------------------------------------------------------
export const MIN_FEE = 16660000000000;
export const MIN_CONTRACT_FEE = 79080000000000;
export const MIN_GAS_PRICE = 1000000000;
export const URL_MAINNET = "https://mainnet.aeternity.io/v2";
export const URL_TESTNET = "https://testnet.aeternity.io/v2";
//-------------------------------------------------------------------
// CANONICAL TYPES ("MODELS") FROM THE DOCUMENTATION
//
// All of these names are as given in the documentation except `Error`
// (which is a reserve term in JS), renamed to `ErrorReason`
//-------------------------------------------------------------------
// Error
//
// Docs: https://api-docs.aeternity.io/#/definitions/Error
// Docs: https://github.com/aeternity/aeternity/blob/v6.4.0/apps/aehttp/priv/swagger.yaml#L3168-L3172
type ErrorReason = {reason: string};
type Tx = {tx: string};
//-------------------------------------------------------------------
// FUNCTIONS
//
// The names here follow their names in the documentation
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// GetAccountNextNonce: /accounts/{pubkey}/next-nonce
//
// Docs: https://api-docs.aeternity.io/#/account/GetAccountNextNonce
//
// > Get an account's next nonce; This is computed according to
// > whatever is the current account nonce and what transactions are
// > currently present in the transaction pool
//-------------------------------------------------------------------
type GetAccountNextNonce_params = {pubkey : string,
strategy? : "max" | "continuity"};
type GetAccountNextNonce_ret = {next_nonce: string};
async function
GetAccountNextNonce(endpoint_url : string,
params : GetAccountNextNonce_params)
: Promise< GetAccountNextNonce_ret
| ErrorReason>
{
let pubkey = params.pubkey;
let url = `${endpoint_url}/accounts/${pubkey}/next-nonce`;
// if the "strategy" field is present, add it as a ?strategy=x
// option
//
// note if the field is absent from `params`, then
// `params.strategy` will be `undefined`, which in js whacko
// world is "falsy"
let strategy = params.strategy;
if (strategy)
{
let addon = `?strategy=${strategy}`;
url += addon;
}
// irrespective of the response code, this is what we return
// so branching is gay
let ret = await net.get_json(url);
return ret;
}
//-------------------------------------------------------------------
// PostContractCreate
//
// Docs: https://api-docs.aeternity.io/#/contract/PostContractCreate
//-------------------------------------------------------------------
// > Get a contract_create transaction object
type ContractCreateTx = {owner_id : string,
nonce? : number,
code : string,
vm_version : number,
abi_version : number,
deposit : number,
amount : number,
gas : number,
gas_price : number,
fee : number,
ttl? : number,
call_data : string};
async function
PostContractCreate(endpoint_url : string,
body_obj : ContractCreateTx)
: Promise<Response>
{
// console.log('body_obj', body_obj);
let url = `${endpoint_url}/debug/contracts/create`;
let ret = await net.post_json_response(url, body_obj);
return ret;
}
async function
create_contract(whoami : string,
code : string,
filename : string,
init_args : Array<string>)
: Promise<Response>
{
let code_resp = await ae_compiler.CompileContract(code, filename);
let code_json = await code_resp.json();
let bytecode = code_json.bytecode;
let calldata_resp = await ae_compiler.EncodeCalldata(code, filename, "init", init_args);
// assert(calldata_resp.ok);
let calldata_json = await calldata_resp.json();
let calldata = calldata_json.calldata;
let cctx: ContractCreateTx =
{owner_id : whoami,
code : bytecode,
vm_version : 7,
abi_version : 3,
deposit : 0,
amount : 0,
gas : 25000,
gas_price : 1*MIN_GAS_PRICE,
fee : 1*MIN_CONTRACT_FEE,
call_data : calldata};
let ret = await PostContractCreate(URL_TESTNET, cctx);
return ret;
}
//-------------------------------------------------------------------
// PostSpend: /debug/transactions/spend
//
// Docs:
// - Input type : https://api-docs.aeternity.io/#/definitions/SpendTx
// - Return type : https://api-docs.aeternity.io/#/definitions/Tx
// - Function : https://api-docs.aeternity.io/#/transaction/PostSpend
//
// > Get a spend transaction object
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// SpendTx
//
// Docs: https://api-docs.aeternity.io/#/definitions/SpendTx
// Docs: https://github.com/aeternity/aeternity/blob/v6.4.0/apps/aehttp/priv/swagger.yaml#L2187-L2209
//-------------------------------------------------------------------
type SpendTx =
{recipient_id : string,
amount : number,
fee : number,
ttl? : number,
sender_id : string,
nonce? : number,
payload : string};
async function
PostSpend(endpoint_url : string,
body_obj : SpendTx)
: Promise<Tx | ErrorReason>
{
let url = `${endpoint_url}/debug/transactions/spend`;
let ret = await net.post_json(url, body_obj);
return ret;
}
//-------------------------------------------------------------------
// PostTransaction
//
// Docs: https://api-docs.aeternity.io/#/contract/PostTransaction
//
// > Post a new transaction
//-------------------------------------------------------------------
async function
PostTransaction(endpoint_url : string,
body_obj : Tx)
: Promise<Response>
{
// console.log('body_obj', body_obj);
let url = `${endpoint_url}/transactions`;
let ret = await net.post_json_response(url, body_obj);
return ret;
}
//-------------------------------------------------------------------
// GetTransactionInfoByHash
//
// Docs: https://api-docs.aeternity.io/#/contract/GetTransactionInfoByHash
//-------------------------------------------------------------------
async function
GetTransactionInfoByHash(endpoint_url : string,
hash : string)
: Promise<Response>
{
// console.log('body_obj', body_obj);
let url = `${endpoint_url}/transactions/${hash}/info`;
let ret = await net.get_json_response(url);
return ret;
}
//-------------------------------------------------------------------
// EXPORTS
//-------------------------------------------------------------------
// type exports
export type {
ErrorReason,
Tx,
SpendTx,
ContractCreateTx
};
export {
GetAccountNextNonce,
PostContractCreate,
create_contract,
PostSpend,
PostTransaction
};
@@ -0,0 +1,85 @@
//-------------------------------------------------------------------
// Common networking functions
//
// Mozilla fetch docs : https://developer.mozilla.org/en-US/docs/Web/API/fetch
//-------------------------------------------------------------------
/* pf = pretty format
*/
function pf(x : any) : string
{
return JSON.stringify(x, undefined, 4);
}
//-------------------------------------------------------------------
// FUNCTIONS
//-------------------------------------------------------------------
// GET request with return type of JSON
async function
get_json(url: string)
: Promise<any>
{
let response = await fetch(url);
let ret = await response.json();
return ret;
}
// GET request with return type of JSON
async function
get_json_response(url: string)
: Promise<Response>
{
let response = await fetch(url);
//let ret = await response.json();
return response;
}
// POST request with content type of json and return type of JSON
async function
post_json(url : string,
body_obj : any)
: Promise<any>
{
let body_str = pf(body_obj);
let req_opts = {method : 'POST',
body : body_str,
headers : {"Content-Type": "application/json"}};
let response = await fetch(url, req_opts);
let ret = await response.json();
return ret;
}
async function
post_json_response(url : string,
body_obj : any)
: Promise<Response>
{
let body_str = pf(body_obj);
let req_opts = {method : 'POST',
body : body_str,
headers : {"Content-Type": "application/json"}};
let response = await fetch(url, req_opts);
return response;
}
//-------------------------------------------------------------------
// EXPORTS
//-------------------------------------------------------------------
export {
get_json,
get_json_response,
post_json,
post_json_response
}