alaexplorerjs16
General purpose library for ALAIO blockchains.
Versions
ALAIO/alaexplorerjs16 | Npm | ALAIO/ala | Docker Hub |
---|---|---|---|
tags: 16.0.0 - 16.0.9 | npm install alaexplorerjs16 |
tags: v1.1.n - v1.2.4 | alaio/ala:v1.2.4 |
Prior version matrix.
Usage
- Install with:
npm install alaexplorerjs16
- Html script tag, see releases for the correct version and its matching script integrity hash.
<!--sha512-fqmNgLjSEhMSiGW9Tkv735UpvnPPKlaVOHgYwrOEhzRbzcsB5z7g2zHYtAOKgIOYNkGg3Q3CBfJapbVU9lzbpA== lib/ala.jssha512-zhPSKFEBlDVvUzjl9aBS66cI8tDYoLetynuKvIekHT8NZZ12oxwcZ//M/eT/2Rb/pR/cjFvLD8104Cy//sdEnA== lib/ala.min.jssha512-VKOxq8R14PpPh4nbLvD8DtxxTv1UmZp7pb3+P8IOQ36m3PBJpm6cd8pI8WRI6d9/aozwADKb3HSFQ7A8s+OhSA== lib/ala.min.js.map-->
Usage
Ways to instantiate alaexplorerjs16.
Ala = // Private key or keys (array) provided statically or by way of a function.// For multiple keys, the get_required_keys API is used (more on that below).keyProvider: '5HzzqBmg4DeneRqNRznPiBubRDGEPdcVjGZCTMGjGJWJubKm2Pe' // Localhost Testnet (run ./docker/up.sh)ala = // Connect to a testnet or mainnetala = // Cold-storageala = // Add support for non-ALA public key prefixes, such as PUB, etcala = // Read-only instance when 'alaexplorerjs16' is already a dependencyala = Alamodules // Read-only instance when an application never needs to write (smaller library)AlaApi = ala =
No-arguments prints usage.
ala
USAGEgetBlock - Fetch a block from the blockchain. PARAMETERS
Start a alanoded process. The docker in this repository provides a setup that supports the examples in this README.
cd ./docker && ./up.sh
All blockchain functions (read and write) follow this pattern:
// If the last argument is a function it is treated as a callbackala // If a callback is not provided, a Promise is returnedala // @returns {Promise} // Parameters can be positional or an objectala // An API with no parameters is invoked with an empty object or callback (avoids logging usage)ala // @returns {Promise}ala
API Documentation
Chain and history API functions are available after creating the ala
object.
Configuration
Ala = // Default configurationconfig = chainId: null // 32 byte (64 char) hex string keyProvider: 'PrivateKeys...' // WIF string or array of keys.. httpEndpoint: 'http://127.0.0.1:8888' expireInSeconds: 60 broadcast: true verbose: false // API activity sign: true ala =
-
chainId
hex
- Unique ID for the blockchain you're connecting to. This is required for valid transaction signing. The chainId is provided via the get_info API call.Identifies a chain by its initial genesis block. All transactions signed will only be valid the blockchain with this chainId. Verify the chainId for security reasons.
-
keyProvider
[array<string>|string|function]
- Provides private keys used to sign transactions. If multiple private keys are found, the APIget_required_keys
is called to discover which signing keys to use. If a function is provided, this function is called for each transaction.If a keyProvider is not provided here, one may be provided on a per-action or per-transaction basis in Options.
-
keyPrefix
[string='ALA']
- Change the public key prefix. -
httpEndpoint
string
- http or https location of a alanoded server providing a chain API. When using alaexplorerjs16 from a browser remember to configure the same origin policy in alanoded or proxy server. For testing, alanoded configurationaccess-control-allow-origin = *
could be used.Set this value to null for a cold-storage (no network) configuration.
-
expireInSeconds
number
- number of seconds before the transaction will expire. The time is based on the alanoded's clock. An unexpired transaction that may have had an error is a liability until the expiration is reached, this time should be brief. -
broadcast
[boolean=true]
- post the transaction to the blockchain. Use false to obtain a fully signed transaction. -
verbose
[boolean=false]
- verbose logging such as API activity. -
debug
[boolean=false]
- low level debug logging (serialization). -
sign
[boolean=true]
- sign the transaction with a private key. Leaving a transaction unsigned avoids the need to provide a private key. -
mockTransactions (advanced)
mockTransactions: () => null // 'pass', or 'fail'
pass
- do not broadcast, always pretend that the transaction workedfail
- do not broadcast, pretend the transaction failednull|undefined
- broadcast as usual
-
transactionHeaders (advanced) - manually calculate transaction header. This may be provided so alaexplorerjs16 does not need to make header related API calls to alanode. Used in environments like cold-storage. This callback is called for every transaction. Headers are documented here ala-api7#headers.
transactionHeaders: (expireInSeconds, callback) => {callback(null/*error*/, headers)}
-
logger - default logging configuration.
logger:log: configverbose ? consolelog : null // null to disableerror: configverbose ? consoleerror : nullFor example, redirect error logs:
config.logger = {error: (...args) => ..}
-
authorization - replace the default alaexplorerjs16 authorization on actions. An authorization provided here may still be over-written by specifying an authorization for each individual action.
For example, if most actions in an dapp are based on the posting key, this would replace the default active authorization with a posting authorization:
authorization: '@posting'
Options
Options may be provided after parameters.
NOTE: authorization
is for individual actions, it does not belong in Ala(config)
.
options = authorization: 'alice@active' broadcast: true sign: true
ala
-
authorization
[array<auth>|auth]
- identifies the signing account and permission typically in a multisig configuration. Authorization may be a string formatted asaccount@permission
or anobject<{actor: account, permission}>
.- If missing default authorizations will be calculated.
- If provided additional authorizations will not be added.
- Performs deterministic sorting by account name
If a default authorization is calculated the action's 1st field must be an account_name. The account_name in the 1st field gets added as the active key authorization for the action.
-
broadcast
[boolean=true]
- post the transaction to the blockchain. Use false to obtain a fully signed transaction. -
sign
[boolean=true]
- sign the transaction with a private key. Leaving a transaction unsigned avoids the need to provide a private key. -
keyProvider
[array<string>|string|function]
- just like the global keyProvider except this provides a temporary key for a single action or transaction.await alaawait ala
Transaction
The transaction function accepts the standard blockchain transaction.
Required transaction header fields will be added unless you are signing without a network connection (httpEndpoint == null). In that case provide you own headers:
// only needed in cold-storage or for offline transactionsconst headers = expiration: '2018-06-14T18:16:10' ref_block_num: 1 ref_block_prefix: 452435776
Create and send (broadcast) a transaction:
/** @return */ala
Named action functions
More concise functions are provided for applications that may use actions more frequently. This avoids having lots of JSON in the code.
// Run with no arguments to print usage.ala // Callback is last, when omitted a promise is returnedalaala // @returns {Promise} // positional parametersala // named parametersala // options appear after parametersoptions = broadcast: true sign: true // `false` is a shortcut for {broadcast: false}ala
Read-write API methods and documentation are generated from the alaio token and system.
Assets amounts require zero padding. For a better user-experience, if you know the correct precision you may use DecimalPad to add the padding.
DecimalPad = AlamodulesformatDecimalPaduserInput = '10.2'precision = 4assert
For more advanced signing, see keyProvider
and signProvider
in
index.test.js.
Shorthand
Shorthand is available for some types such as Asset and Authority. This syntax
is only for concise functions and does not work when providing entire transaction
objects to ala.transaction
..
For example:
- permission
inita
defaultsinita@active
- authority
'ALA6MRy..'
expands{threshold: 1, keys: [{key: 'ALA6MRy..', weight: 1}]}
- authority
inita
expands{threshold: 1, accounts: [{permission: {actor: 'inita', permission: 'active'}, weight: 1}]}
New Account
New accounts will likely require some staked tokens for RAM and bandwidth.
wif = '5HzzqBmg4DeneRqNRznPiBubRDGEPdcVjGZCTMGjGJWJubKm2Pe'pubkey = 'ALA8dM36QedcUfPTNF7maThtRqHP5xvCqMsYiHUz1Rz7sPfhvCYuo' ala
Contract
Deploy and call smart contracts.
Compile
If you're loading a wasm file, you do not need binaryen. If you're loading a wast file you can include and configure the binaryen compiler, this is used to compile to wasm automatically when calling setcode.
Versions of binaryen may be problematic.
$ npm install binaryen@37.0.0
binaryen = ala =
Deploy
wasm = fsabi = fs // Publish contract to the blockchainala // @returns {Promise}ala // @returns {Promise}
Fetch a smart contract
// @returns {Promise}ala // Run immediately, `myaction` returns a Promiseala // Group actions. `transaction` returns a Promise but `myaction` does notala // Transaction with multiple contractsala
Offline or cold-storage contract
ala = abi = fsalafcabiCache // Check that the ABI is available (print usage)ala
Offline or cold-storage transaction
// ONLINE // Prepare headersexpireInSeconds = 60 * 60 // 1 hour ala = info = await alachainDate = infohead_block_time + 'Z'expiration = chainDate + expireInSeconds * 1000expiration = expiration0 block = await ala transactionHeaders = expiration ref_block_num: infolast_irreversible_block_num & 0xFFFF ref_block_prefix: blockref_block_prefix // OFFLINE (bring `transactionHeaders`) // All keys in keyProvider will sign.ala = transfer = await alatransferTransaction = transfertransaction // ONLINE (bring `transferTransaction`) ala = processedTransaction = await ala // alacli version:const alacliTransaction = transferTransactiontransactionalacliTransactionsignatures = transferTransactionsignatures// `cloes push transaction ${JSON.stringify(alacliTransaction)}`
Custom Token
// more on the contract / transaction syntax await ala const balance = await alaconsole
Calling Actions
Other ways to use contracts and transactions.
// if either transfer fails, both will fail (1 transaction, 2 messages)await ala // transaction on a single contractawait ala // mix contracts in the same transactionawait ala // The contract method does not take an array so must be called once for// each contract that is needed.const myaccount = await alaawait myaccount // a transaction to a contract instance can specify multiple actionsawait myaccount
Development
From time-to-time the alaexplorerjs16 and alanode binary format will change between releases
so you may need to start alanode
with the --skip-transaction-signatures
parameter
to get your transactions to pass.
Note, package.json
has a "main" pointing to ./lib
. The ./lib
folder is for
es2015 code built in a separate step. If you're changing and testing code,
import from ./src
instead.
Ala = // forceActionDataHex = false helps transaction readability but may trigger back-end bugsconfig = verbose: true debug: false broadcast: true forceActionDataHex: true keyProvider ala =
Fcbuffer
The ala
instance can provide serialization:
// 'asset' is a type but could be any struct or type like: transaction or uint8type = type: 1 data: '00ff'buffer = alafcassert // ABI Serializationala
Use Node v10+ for package-lock.json
.
Related Libraries
These libraries are integrated into alaexplorerjs16
seamlessly so you probably do not
need to use them directly. They are exported here giving more API access or
in some cases may be used standalone.
var format api ecc json Fcbuffer = Alamodules
-
format ./format.md
- Blockchain name validation
- Asset string formatting
-
- Remote API to an ALA blockchain node (alanode)
- Use this library directly if you need read-only access to the blockchain (don't need to sign transactions).
-
- Private Key, Public Key, Signature, AES, Encryption / Decryption
- Validate public or private keys
- Encrypt or decrypt with ALA compatible checksums
- Calculate a shared secret
-
- Blockchain definitions (api method names, blockchain schema)
-
- private key storage and key management
-
- Binary serialization used by the blockchain
- Clients sign the binary form of the transaction
- Allows client to know what it is signing
Environment
Node and browser (es2015)