Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@avalabs/avalanchejs

Package Overview
Dependencies
Maintainers
1
Versions
53
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@avalabs/avalanchejs - npm Package Compare versions

Comparing version 3.17.0 to 3.18.0-alpha.1

dist/constants/bls.d.ts

125

dist/index.d.ts

@@ -1,118 +0,9 @@

/**
* @packageDocumentation
* @module Avalanche
*/
import AvalancheCore from "./avalanche";
import { AdminAPI } from "./apis/admin/api";
import { AuthAPI } from "./apis/auth/api";
import { AVMAPI } from "./apis/avm/api";
import { EVMAPI } from "./apis/evm/api";
import { GenesisAsset } from "./apis/avm/genesisasset";
import { GenesisData } from "./apis/avm/genesisdata";
import { HealthAPI } from "./apis/health/api";
import { IndexAPI } from "./apis/index/api";
import { InfoAPI } from "./apis/info/api";
import { KeystoreAPI } from "./apis/keystore/api";
import { MetricsAPI } from "./apis/metrics/api";
import { PlatformVMAPI } from "./apis/platformvm/api";
import { Socket } from "./apis/socket/socket";
import BinTools from "./utils/bintools";
import DB from "./utils/db";
import Mnemonic from "./utils/mnemonic";
import PubSub from "./utils/pubsub";
import HDNode from "./utils/hdnode";
import BN from "bn.js";
import { Buffer } from "buffer/";
/**
* AvalancheJS is middleware for interacting with Avalanche node RPC APIs.
*
* Example usage:
* ```js
* const avalanche: Avalanche = new Avalanche("127.0.0.1", 9650, "https")
* ```
*
*/
export default class Avalanche extends AvalancheCore {
/**
* Returns a reference to the Admin RPC.
*/
Admin: () => AdminAPI;
/**
* Returns a reference to the Auth RPC.
*/
Auth: () => AuthAPI;
/**
* Returns a reference to the EVMAPI RPC pointed at the C-Chain.
*/
CChain: () => EVMAPI;
/**
* Returns a reference to the AVM RPC pointed at the X-Chain.
*/
XChain: () => AVMAPI;
/**
* Returns a reference to the Health RPC for a node.
*/
Health: () => HealthAPI;
/**
* Returns a reference to the Index RPC for a node.
*/
Index: () => IndexAPI;
/**
* Returns a reference to the Info RPC for a node.
*/
Info: () => InfoAPI;
/**
* Returns a reference to the Metrics RPC.
*/
Metrics: () => MetricsAPI;
/**
* Returns a reference to the Keystore RPC for a node. We label it "NodeKeys" to reduce
* confusion about what it's accessing.
*/
NodeKeys: () => KeystoreAPI;
/**
* Returns a reference to the PlatformVM RPC pointed at the P-Chain.
*/
PChain: () => PlatformVMAPI;
/**
* Creates a new Avalanche instance. Sets the address and port of the main Avalanche Client.
*
* @param host The hostname to resolve to reach the Avalanche Client RPC APIs
* @param port The port to resolve to reach the Avalanche Client RPC APIs
* @param protocol The protocol string to use before a "://" in a request,
* ex: "http", "https", "git", "ws", etc. Defaults to http
* @param networkID Sets the NetworkID of the class. Default [[DefaultNetworkID]]
* @param XChainID Sets the blockchainID for the AVM. Will try to auto-detect,
* otherwise default "2eNy1mUFdmaxXNj1eQHUe7Np4gju9sJsEtWQ4MX3ToiNKuADed"
* @param CChainID Sets the blockchainID for the EVM. Will try to auto-detect,
* otherwise default "2CA6j5zYzasynPsFeNoqWkmTCt3VScMvXUZHbfDJ8k3oGzAPtU"
* @param hrp The human-readable part of the bech32 addresses
* @param skipinit Skips creating the APIs. Defaults to false
*/
constructor(host?: string, port?: number, protocol?: string, networkID?: number, XChainID?: string, CChainID?: string, hrp?: string, skipinit?: boolean);
}
export { Avalanche };
export { AvalancheCore };
export { BinTools };
export { BN };
export { Buffer };
export { DB };
export { HDNode };
export { GenesisAsset };
export { GenesisData };
export { Mnemonic };
export { PubSub };
export { Socket };
export * as admin from "./apis/admin";
export * as auth from "./apis/auth";
export * as avm from "./apis/avm";
export * as common from "./common";
export * as evm from "./apis/evm";
export * as health from "./apis/health";
export * as index from "./apis/index";
export * as info from "./apis/info";
export * as keystore from "./apis/keystore";
export * as metrics from "./apis/metrics";
export * as platformvm from "./apis/platformvm";
export * as utils from "./utils";
export * as networkIDs from './constants/networkIDs';
export * from './serializable';
export { Utxo } from './serializable/avax/utxo';
export * from './signer';
export * from './utils';
export * as utils from './utils';
export * from './vms';
export { Info } from './info/info';
//# sourceMappingURL=index.d.ts.map

@@ -1,46 +0,4 @@

/**
* @packageDocumentation
* @module Utils-Base58
*/
import BN from "bn.js";
import { Buffer } from "buffer/";
/**
* A Base58 class that uses the cross-platform Buffer module. Built so that Typescript
* will accept the code.
*
* ```js
* let b58:Base58 = new Base58();
* let str:string = b58.encode(somebuffer);
* let buff:Buffer = b58.decode(somestring);
* ```
*/
export declare class Base58 {
private static instance;
private constructor();
/**
* Retrieves the Base58 singleton.
*/
static getInstance(): Base58;
protected b58alphabet: string;
protected alphabetIdx0: string;
protected b58: number[];
protected big58Radix: BN;
protected bigZero: BN;
/**
* Encodes a {@link https://github.com/feross/buffer|Buffer} as a base-58 string
*
* @param buff A {@link https://github.com/feross/buffer|Buffer} to encode
*
* @returns A base-58 string.
*/
encode: (buff: Buffer) => string;
/**
* Decodes a base-58 into a {@link https://github.com/feross/buffer|Buffer}
*
* @param b A base-58 string to decode
*
* @returns A {@link https://github.com/feross/buffer|Buffer} from the decoded string.
*/
decode: (b: string) => Buffer;
}
import type { BytesCoder } from '@scure/base';
export declare const base58check: BytesCoder;
export { base58 } from '@scure/base';
//# sourceMappingURL=base58.d.ts.map

@@ -1,14 +0,18 @@

export * from "./base58";
export * from "./bintools";
export * from "./mnemonic";
export * from "./constants";
export * from "./db";
export * from "./errors";
export * from "./fetchadapter";
export * from "./hdnode";
export * from "./helperfunctions";
export * from "./payload";
export * from "./persistenceoptions";
export * from "./pubsub";
export * from "./serialization";
export * from './address';
export * from './addressesFromBytes';
export * from './base58';
export * from './buffer';
export * from './bytesCompare';
export * from './costs';
export * from './devutils';
export * from './secp256k1';
export * from './typeGuards';
export * from './UTXOSet';
export * from './addChecksum';
export * from './addressMap';
export * from './getTransferableInputsByTx';
export * from './getTransferableOutputsByTx';
export * from './getBurnedAmountByTx';
export * from './validateBurnedAmount';
export { unpackWithManager, getManagerForVM, packTx } from './packTx';
//# sourceMappingURL=index.d.ts.map
{
"name": "@avalabs/avalanchejs",
"version": "3.17.0",
"version": "3.18.0-alpha.1",
"description": "Avalanche Platform JS Library",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"typings": "dist/index.d.ts",
"type": "module",
"exports": {
"import": "./dist/es/index.js",
"require": "./dist/index.js"
},
"files": [
"dist",
"src"
],
"sideEffects": false,
"module": "dist/es/index.js",
"scripts": {
"build": "rm -rf dist/ && npx tsc -b",
"prebundle": "yarn build",
"bundle": "webpack --mode production",
"lint": "eslint ./ --ext js,ts --fix",
"prepublish": "yarn build",
"release:prepare": "rm -rf ./dist ./node_modules && yarn install && yarn test && yarn build && yarn bundle && git status",
"test": "jest",
"test-watch": "jest --watch",
"docs": "rm -rf docsMD && yarn build && npx typedoc --readme none --theme markdown --out docs",
"prettier": "npx prettier --write .",
"start": "rollup -c --watch",
"build": "rollup -c",
"build:prod": "rollup -c --environment BUILD:production",
"test": "NODE_OPTIONS=--experimental-vm-modules jest",
"test:path": "NODE_OPTIONS=--experimental-vm-modules jest --watch --testPathPattern",
"test:cov": "NODE_OPTIONS=--experimental-vm-modules jest --collect-coverage=true",
"test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch",
"lint": "eslint --fix --ignore-path .gitignore \"./**/*.ts*\"",
"lint:check": "eslint --ignore-path .gitignore \"./**/*.ts*\"",
"typecheck": "tsc --skipLibCheck --noEmit",
"example": "NODE_OPTIONS='--loader ts-node/esm' ts-node examples/c-chain/export.ts",
"prepare": "husky install"
},
"dependencies": {
"@noble/hashes": "1.3.3",
"@noble/secp256k1": "2.0.0",
"@scure/base": "1.1.5",
"micro-eth-signer": "0.7.2"
},
"devDependencies": {
"@commitlint/cli": "17.7.1",
"@commitlint/config-conventional": "17.7.0",
"@jest/globals": "29.7.0",
"@rollup/plugin-node-resolve": "15.2.3",
"@rollup/plugin-terser": "0.4.3",
"@rollup/plugin-typescript": "11.1.6",
"@semantic-release/changelog": "6.0.3",
"@semantic-release/commit-analyzer": "11.1.0",
"@semantic-release/git": "10.0.1",
"@semantic-release/github": "9.2.6",
"@semantic-release/npm": "11.0.2",
"@types/node": "20.11.10",
"@types/jest": "29.5.11",
"@typescript-eslint/eslint-plugin": "6.18.1",
"@typescript-eslint/parser": "6.18.1",
"commitizen": "4.3.0",
"cz-conventional-changelog": "3.3.0",
"dotenv": "16.4.2",
"eslint": "8.49.0",
"eslint-config-prettier": "9.1.0",
"eslint-plugin-prettier": "4.2.1",
"ethers": "6.11.0",
"husky": "8.0.3",
"jest": "29.7.0",
"jest-mock": "29.7.0",
"lint-staged": "15.2.2",
"node-fetch": "3.3.2",
"prettier": "2.8.7",
"rollup": "4.9.6",
"rollup-plugin-filesize": "10.0.0",
"semantic-release": "21.0.1",
"ts-jest": "29.1.2",
"ts-node": "10.9.2",
"typescript": "5.3.3"
},
"packageManager": "yarn@1.22.19",
"engines": {
"node": "^20"
},
"volta": {
"node": "20.11.0",
"yarn": "1.22.19"
},
"repository": {

@@ -28,11 +92,3 @@ "type": "git",

],
"author": "Gabriel Cardona <gabriel@avalabs.org>",
"contributors": [
"Evan Richard <evan@avalabs.org>",
"Paul Kim <paul.kim@avalabs.org>",
"Raj Ranjan <raj.ranjan@avalabs.org>",
"Gergely Lovas <gergely.lovas@avalabs.org>",
"Dhruba Basu <dhruba@avalabs.org>"
],
"license": "BSD-3-Clause",
"author": "",
"bugs": {

@@ -42,67 +98,9 @@ "url": "https://github.com/ava-labs/avalanchejs/issues"

"homepage": "https://github.com/ava-labs/avalanchejs#readme",
"devDependencies": {
"@semantic-release/changelog": "6.0.2",
"@semantic-release/git": "10.0.1",
"@types/bech32": "1.1.4",
"@types/bn.js": "5.1.1",
"@types/create-hash": "1.2.2",
"@types/hdkey": "2.0.1",
"@types/jest": "29.4.0",
"@types/node": "18.14.2",
"@typescript-eslint/eslint-plugin": "5.54.0",
"@typescript-eslint/parser": "5.54.0",
"clean-webpack-plugin": "4.0.0",
"eslint": "7.32.0",
"eslint-config-prettier": "8.6.0",
"eslint-plugin-prettier": "4.2.1",
"eslint-plugin-security": "1.7.1",
"git-revision-webpack-plugin": "5.0.0",
"html-webpack-plugin": "5.5.0",
"husky": "8.0.3",
"jest": "29.4.3",
"jest-mock-axios": "4.5.0",
"lint-staged": "13.1.2",
"prettier": "2.8.4",
"semantic-release": "19.0.5",
"terser-webpack-plugin": "5.3.6",
"ts-jest": "29.0.5",
"ts-loader": "9.4.2",
"typedoc": "0.23.26",
"typedoc-plugin-external-module-name": "4.0.6",
"typedoc-plugin-markdown": "3.14.0",
"typescript": "4.9.5",
"webpack": "5.74.0",
"webpack-cli": "4.10.0"
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
},
"engines": {
"node": ">=14.0.0"
},
"dependencies": {
"assert": "2.0.0",
"axios": "0.27.2",
"bech32": "2.0.0",
"bip39": "3.1.0",
"bn.js": "5.2.1",
"buffer": "6.0.3",
"create-hash": "1.2.0",
"crypto-browserify": "3.12.0",
"elliptic": "6.5.4",
"ethers": "6.0.8",
"hdkey": "2.1.0",
"isomorphic-ws": "5.0.0",
"randombytes": "^2.1.0",
"store2": "2.14.2",
"stream-browserify": "3.0.0",
"ws": "8.12.1",
"xss": "1.0.14"
},
"prettier": {
"tabWidth": 2,
"useTabs": false,
"semi": false,
"singleQuote": false,
"jsxBracketSameLine": false,
"trailingComma": "none"
},
"resolutions": {
"http-cache-semantics": "4.1.1",
"json5": "2.2.3"

@@ -109,0 +107,0 @@ },

# AvalancheJS - The Avalanche Platform JavaScript Library
## Deprecation of avalancheJS
The npm package `https://www.npmjs.com/package/avalanche` is being deprecated. For the latest version please use @avalabs/avalanchejs. We will no longer support the avalanche npm package.
## Overview

@@ -11,402 +7,68 @@

The APIs currently supported by default are:
Using AvalancheJS, developers can:
* Admin API
* Auth API
* AVM API (X-Chain)
* EVM API (C-Chain)
* Health API
* Index API
* Info API
* Keystore API
* Metrics API
* PlatformVM API (P-Chain)
* Socket
- Retrieve balances on addresses
- Get UTXOs for addresses
- Build and sign transactions
- Issue signed transactions to the X-Chain, P-Chain, and C-Chain
- Perform cross-chain swaps between the X, P and C chains
- Add Validators and Delegators
- Create Subnets and Blockchains
We built AvalancheJS with ease of use in mind. With this library, any Javascript developer is able to interact with a node on the Avalanche Platform who has enabled their API endpoints for the developer's consumption. We keep the library up-to-date with the latest changes in the [Avalanche Platform Specification](https://docs.avax.network).
Using AvalancheJS, developers can:
* Locally manage private keys
* Retrieve balances on addresses
* Get UTXOs for addresses
* Build and sign transactions
* Issue signed transactions to the X-Chain, P-Chain, and C-Chain
* Perform cross-chain swaps between the X-Chain<->P-Chain and between the X-Chain<->C-Chain
* Add Validators and Delegators to the Primary Subnetwork by staking AVAX
* Create a Subnetwork
* Administer a local node
* Retrieve Avalanche network information from a node
### Requirements
AvalancheJS requires Node.js LTS version 14.16.0 or higher to compile.
AvalancheJS requires Node.js LTS version 20.11.1 or higher to compile.
### Installation
## Installation
Avalanche is available for install via `yarn`:
### Using the NPM Package
`yarn add avalanche`
Add AvalancheJS to your project via `npm` or `yarn`.
You can also pull the repo down directly and build it from scratch:
For installing via `npm`:
`yarn build`
`npm install --save @avalabs/avalanchejs`
This will generate a pure Javascript library and place it in a folder named "web" in the project root. The "avalanche.js" file can then be dropped into any project as a pure javascript implementation of Avalanche.
For installing via `yarn`:
The AvalancheJS library can be imported into your existing Node.js project as follows:
`yarn add @avalabs/avalanchejs`
```js
const avalanche = require("avalanche")
```
### Build from Repository
Or into your TypeScript project like this:
You can also pull the repo down directly and build it from scratch.
```js
import { Avalanche } from "avalanche"
```
Clone the AvalancheJS repository:
### Importing essentials
`git clone https://github.com/ava-labs/avalanchejs.git`
```js
import { Avalanche, BinTools, BN, Buffer } from "avalanche"
Then build it:
const bintools = BinTools.getInstance()
```
`npm run build`
The above lines import the libraries used in the tutorials. The libraries include:
or
* Avalanche: Our javascript module.
* BinTools: A singleton built into AvalancheJS that is used for dealing with binary data.
* [BN](https://www.npmjs.com/package/bn.js): A bignumber module use by AvalancheJS.
* [Buffer](https://www.npmjs.com/package/buffer): A Buffer library.
`yarn build`
## Example 1 &mdash; Managing X-Chain Keys
## Use AvalancheJS in Projects
AvalancheJS comes with its own AVM Keychain. This KeyChain is used in the functions of the API, enabling them to sign using keys it's registered. The first step in this process is to create an instance of AvalancheJS connected to our Avalanche Platform endpoint of choice.
The AvalancheJS library can be imported into your existing project as follows:
```js
import { Avalanche, BinTools, Buffer, BN } from "avalanche"
const bintools = BinTools.getInstance()
const myNetworkID = 12345 //default is 1, we want to override that for our local network
const avalanche = new Avalanche("localhost", 9650, "http", myNetworkID)
const xchain = avalanche.XChain() //returns a reference to the X-Chain used by AvalancheJS
```ts
import { avm, pvm, evm } from '@avalabs/avalanchejs';
```
### Accessing the KeyChain
## Importing Essentials
The KeyChain is accessed through the X-Chain and can be referenced directly or through a reference variable.
```ts
import { avm /** X-chain */, pvm /** P-chain */, evm /** C-chain */, utils } from "@avalabs/avalanchejs"
```js
const myKeychain = xchain.keyChain()
```
// example calls
const exportTx = avm.newExportTx(...) // constructs a new export tx from X
const addValidatorTx = pvm.newAddPermissionlessValidatorTx(...) // constructs a new add validator tx on P
const importTx = evm.newImportTx(...) // constructs a new import tx to C
This exposes the instance of the class AVMKeyChain which is created when the X-Chain API is created. At present, this supports secp256k1 curve for ECDSA key pairs.
### Creating X-Chain key pairs
The KeyChain has the ability to create new KeyPairs for you and return the address associated with the key pair.
```js
const newAddress1 = myKeychain.makeKey() // returns an instance of the KeyPair class
const publicKeyBytes = utils.hexToBuffer(publicKeyHex)
const signature = utils.signHash(bytes, privateKeyBytes)
```
You may also import your existing private key into the KeyChain using either a Buffer...
```js
const mypk = bintools.cb58Decode(
"JaCCSxdoWfo3ao5KwenXrJjJR7cBTQ287G1C5qpv2hr2tCCdb"
) // returns a Buffer
const newAddress2 = myKeychain.importKey(mypk) // returns an instance of the KeyPair class
```
... or an CB58 string works, too:
```js
const mypk = "PrivateKey-JaCCSxdoWfo3ao5KwenXrJjJR7cBTQ287G1C5qpv2hr2tCCdb"
const newAddress2 = myKeychain.importKey(mypk) // returns an instance of the KeyPair class
```
### Working with KeyChains
The X-Chains's KeyChain has standardized key management capabilities. The following functions are available on any KeyChain that implements this interface.
```js
const addresses = myKeychain.getAddresses() // returns an array of Buffers for the addresses
const addressStrings = myKeychain.getAddressStrings() // returns an array of strings for the addresses
const exists = myKeychain.hasKey(addresses[0]) // returns true if the address is managed
const keypair = myKeychain.getKey(addresses[0]) // returns the KeyPair class
```
### Working with KeyPairs
The X-Chain's KeyPair has standardized KeyPair functionality. The following operations are available on any KeyPair that implements this interface.
```js
const address = keypair.getAddress() // returns Buffer
const addressString = keypair.getAddressString() // returns string
const pubk = keypair.getPublicKey() // returns Buffer
const pubkstr = keypair.getPublicKeyString() // returns a CB58 encoded string
const privk = keypair.getPrivateKey() //returns Buffer
const privkstr = keypair.getPrivateKeyString() //returns a CB58 encoded string
keypair.generateKey() // creates a new random KeyPair
const mypk = bintools.cb58Decode(
"24jUJ9vZexUM6expyMcT48LBx27k1m7xpraoV62oSQAHdziao5"
)
const successful = keypair.importKey(mypk) // returns boolean if private key imported successfully
const message = Buffer.from("Through consensus to the stars")
const signature = keypair.sign(message) // returns a Buffer with the signature
const signerPubk = keypair.recover(message, signature) // returns a Buffer
const isValid = keypair.verify(message, signature) // returns a boolean
```
## Example 2 &mdash; Creating An Asset
This example creates an asset in the X-Chain and publishes it to the Avalanche Platform. The first step in this process is to create an instance of AvalancheJS connected to our Avalanche Platform endpoint of choice.
```js
import { Avalanche, BinTools, Buffer, BN } from "avalanche"
import { InitialStates, SECPTransferOutput } from "avalanche/dist/apis/avm"
const myNetworkID = 12345 // default is 1, we want to override that for our local network
const avalanche = new Avalanche("localhost", 9650, "http", myNetworkID)
const xchain = avalanche.XChain() // returns a reference to the X-Chain used by AvalancheJS
```
### Describe the new asset
The first steps in creating a new asset using AvalancheJS is to determine the qualities of the asset. We will give the asset a name, a ticker symbol, as well as a denomination.
```js
// Name our new coin and give it a symbol
const name = "TeamRocket"
const symbol = "ROKT"
// Where is the decimal point indicate what 1 asset is and where fractional assets begin
// Ex: 1 AVAX is denomination 9, so the smallest unit of AVAX is nanoAVAX (nAVAX) at 10^-9 AVAX
const denomination = 9
```
### Creating the initial state
We want to mint an asset with 400 coins to all of our managed keys, 500 to the second address we know of, and 600 to the second and third address. This sets up the state that will result from the Create Asset transaction.
_Note: This example assumes we have the keys already managed in our X-Chain's Keychain._
```js
const addresses = xchain.keyChain().getAddresses()
// Create outputs for the asset's initial state
const secpOutput1 = new SECPTransferOutput(
new BN(400),
new BN(400),
1,
addresses
)
const secpOutput2 = new SECPTransferOutput(new BN(500), new BN(400), 1, [
addresses[1],
])
const secpOutput3 = new SECPTransferOutput(new BN(600), new BN(400), 1, [
addresses[1],
addresses[2],
])
// Populate the initialStates with the outputs
const initialState = new InitialStates()
initialState.addOutput(secpOutput1)
initialState.addOutput(secpOutput2)
initialState.addOutput(secpOutput3)
```
### Creating the signed transaction
Now that we know what we want an asset to look like, we create an output to send to the network. There is an AVM helper function `buildCreateAssetTx()` which does just that.
```js
// Fetch the UTXOSet for our addresses
const utxos = await xchain.getUTXOs(addresses)
// Make an unsigned Create Asset transaction from the data compiled earlier
const unsigned = await xchain.buildCreateAssetTx(
utxos, // the UTXOSet containing the UTXOs we're going to spend
addresses, // the addresses which will pay the fees
addresses, // the addresses which recieve the change from the spent UTXOs
initialState, // the initial state to be created for this new asset
name, // the full name of the asset
symbol, // a short ticker symbol for the asset
denomination // the asse's denomination
)
const signed = unsigned.sign(xchain) // returns a Tx class
```
### Issue the signed transaction
Now that we have a signed transaction ready to send to the network, let's issue it!
Using the AvalancheJS X-Chain API, we going to call the `issueTx` function. This function can take either the Tx class returned in the previous step, a CB58 representation of the transaction, or a raw Buffer class with the data for the transaction. Examples of each are below:
```js
// using the Tx class
const txid = await xchain.issueTx(signed) // returns a CB58 serialized string for the TxID
```
```js
// using the base-58 representation
const txid = await xchain.issueTx(signed.toString()) // returns a CB58 serialized string for the TxID
```
```js
// using the transaction Buffer
const txid = await xchain.issueTx(signed.toBuffer()) // returns a CB58 serialized string for the TxID
```
We assume ONE of those methods are used to issue the transaction.
### Get the status of the transaction
Now that we sent the transaction to the network, it takes a few seconds to determine if the transaction has gone through. We can get an updated status on the transaction using the TxID through the AVM API.
```js
// returns one of: "Accepted", "Processing", "Unknown", and "Rejected"
const status = await xchain.getTxStatus(txid)
```
The statuses can be one of "Accepted", "Processing", "Unknown", and "Rejected":
* "Accepted" indicates that the transaction has been accepted as valid by the network and executed
* "Processing" indicates that the transaction is being voted on.
* "Unknown" indicates that node knows nothing about the transaction, indicating the node doesn't have it
* "Rejected" indicates the node knows about the transaction, but it conflicted with an accepted transaction
### Identifying the newly created asset
The X-Chain uses the TxID of the transaction which created the asset as the unique identifier for the asset. This unique identifier is henceforth known as the "AssetID" of the asset. When assets are traded around the X-Chain, they always reference the AssetID that they represent.
## Example 3 &mdash; Sending An Asset
This example sends an asset in the X-Chain to a single recipient. The first step in this process is to create an instance of Avalanche connected to our Avalanche Platform endpoint of choice.
```js
import { Avalanche, BinTools, Buffer, BN } from "avalanche"
const myNetworkID = 12345 // default is 1, we want to override that for our local network
const avalanche = new avalanche.Avalanche(
"localhost",
9650,
"http",
myNetworkID
)
const xchain = avalanche.XChain() // returns a reference to the X-Chain used by AvalancheJS
```
We're also assuming that the keystore contains a list of addresses used in this transaction.
### Getting the UTXO Set
The X-Chain stores all available balances in a datastore called Unspent Transaction Outputs (UTXOs). A UTXO Set is the unique list of outputs produced by transactions, addresses that can spend those outputs, and other variables such as lockout times (a timestamp after which the output can be spent) and thresholds (how many signers are required to spend the output).
For the case of this example, we're going to create a simple transaction that spends an amount of available coins and sends it to a single address without any restrictions. The management of the UTXOs will mostly be abstracted away.
However, we do need to get the UTXO Set for the addresses we're managing.
```js
const myAddresses = xchain.keyChain().getAddresses() // returns an array of addresses the KeyChain manages as buffers
const addressStrings = xchain.keyChain().getAddressStrings() // returns an array of addresses the KeyChain manages as strings
const u = await xchain.getUTXOs(myAddresses)
const utxos = u.utxos
```
### Spending the UTXOs
The `buildBaseTx()` helper function sends a single asset type. We have a particular assetID whose coins we want to send to a recipient address. This is an imaginary asset for this example which we believe to have 400 coins. Let's verify that we have the funds available for the transaction.
```js
const assetID = "8pfG5CTyL5KBVaKrEnCvNJR95dUWAKc1hrffcVxfgi8qGhqjm" // cb58 string
const mybalance = utxos.getBalance(myAddresses, assetID) // returns 400 as a BN
```
We have 400 coins! We're going to now send 100 of those coins to our friend's address.
```js
const sendAmount = new BN(100) // amounts are in BN format
const friendsAddress = "X-avax1k26jvfdzyukms95puxcceyzsa3lzwf5ftt0fjk" // address format is Bech32
// The below returns a UnsignedTx
// Parameters sent are (in order of appearance):
// * The UTXO Set
// * The amount being sent as a BN
// * An array of addresses to send the funds
// * An array of addresses sending the funds
// * An array of addresses any leftover funds are sent
// * The AssetID of the funds being sent
const unsignedTx = await xchain.buildBaseTx(
utxos,
sendAmount,
[friendsAddress],
addressStrings,
addressStrings,
assetID
)
const signedTx = xchain.signTx(unsignedTx)
const txid = await xchain.issueTx(signedTx)
```
And the transaction is sent!
### Get the status of the transaction
Now that we sent the transaction to the network, it takes a few seconds to determine if the transaction has gone through. We can get an updated status on the transaction using the TxID through the X-Chain.
```js
// returns one of: "Accepted", "Processing", "Unknown", and "Rejected"
const status = await xchain.getTxStatus(txid)
```
The statuses can be one of "Accepted", "Processing", "Unknown", and "Rejected":
* "Accepted" indicates that the transaction has been accepted as valid by the network and executed
* "Processing" indicates that the transaction is being voted on.
* "Unknown" indicates that node knows nothing about the transaction, indicating the node doesn't have it
* "Rejected" indicates the node knows about the transaction, but it conflicted with an accepted transaction
### Check the results
The transaction finally came back as "Accepted", now let's update the UTXOSet and verify that the transaction balance is as we expected.
*Note: In a real network the balance isn't guaranteed to match this scenario. Transaction fees or additional spends may vary the balance. For the purpose of this example, we assume neither of those cases.*
```js
const updatedU = await xchain.getUTXOs()
const updatedUTXOs = updatedU.utxos
const newBalance = updatedUTXOs.getBalance(myAddresses, assetID)
if (newBalance.toNumber() != mybalance.sub(sendAmount).toNumber()) {
throw Error("heyyy these should equal!")
}
```
### Repo Dependency Updates
Dependabot will make pull requests against the development branch. If all tests pass, it is safe to merge into development, but for redundancy you want to try to build it locally.
```zsh
git fetch origin
git checkout -b <branchName>
git merge development
yarn build && yarn test
```
If the E2E check does not pass, go into the 'checks' section of the PR.
`https://github.com/ava-labs/avalanchejs/pull/<PR number>/checks`
* Click on the `> E2E` tab on the left
* Click 'Re-run jobs' on the right
Please check out the `examples` folder for more info.

@@ -1,191 +0,8 @@

/**
* @packageDocumentation
* @module Avalanche
*/
import AvalancheCore from "./avalanche"
import { AdminAPI } from "./apis/admin/api"
import { AuthAPI } from "./apis/auth/api"
import { AVMAPI } from "./apis/avm/api"
import { EVMAPI } from "./apis/evm/api"
import { GenesisAsset } from "./apis/avm/genesisasset"
import { GenesisData } from "./apis/avm/genesisdata"
import { HealthAPI } from "./apis/health/api"
import { IndexAPI } from "./apis/index/api"
import { InfoAPI } from "./apis/info/api"
import { KeystoreAPI } from "./apis/keystore/api"
import { MetricsAPI } from "./apis/metrics/api"
import { PlatformVMAPI } from "./apis/platformvm/api"
import { Socket } from "./apis/socket/socket"
import { DefaultNetworkID, Defaults } from "./utils/constants"
import { getPreferredHRP } from "./utils/helperfunctions"
import BinTools from "./utils/bintools"
import DB from "./utils/db"
import Mnemonic from "./utils/mnemonic"
import PubSub from "./utils/pubsub"
import HDNode from "./utils/hdnode"
import BN from "bn.js"
import { Buffer } from "buffer/"
/**
* AvalancheJS is middleware for interacting with Avalanche node RPC APIs.
*
* Example usage:
* ```js
* const avalanche: Avalanche = new Avalanche("127.0.0.1", 9650, "https")
* ```
*
*/
export default class Avalanche extends AvalancheCore {
/**
* Returns a reference to the Admin RPC.
*/
Admin = () => this.apis.admin as AdminAPI
/**
* Returns a reference to the Auth RPC.
*/
Auth = () => this.apis.auth as AuthAPI
/**
* Returns a reference to the EVMAPI RPC pointed at the C-Chain.
*/
CChain = () => this.apis.cchain as EVMAPI
/**
* Returns a reference to the AVM RPC pointed at the X-Chain.
*/
XChain = () => this.apis.xchain as AVMAPI
/**
* Returns a reference to the Health RPC for a node.
*/
Health = () => this.apis.health as HealthAPI
/**
* Returns a reference to the Index RPC for a node.
*/
Index = () => this.apis.index as IndexAPI
/**
* Returns a reference to the Info RPC for a node.
*/
Info = () => this.apis.info as InfoAPI
/**
* Returns a reference to the Metrics RPC.
*/
Metrics = () => this.apis.metrics as MetricsAPI
/**
* Returns a reference to the Keystore RPC for a node. We label it "NodeKeys" to reduce
* confusion about what it's accessing.
*/
NodeKeys = () => this.apis.keystore as KeystoreAPI
/**
* Returns a reference to the PlatformVM RPC pointed at the P-Chain.
*/
PChain = () => this.apis.pchain as PlatformVMAPI
/**
* Creates a new Avalanche instance. Sets the address and port of the main Avalanche Client.
*
* @param host The hostname to resolve to reach the Avalanche Client RPC APIs
* @param port The port to resolve to reach the Avalanche Client RPC APIs
* @param protocol The protocol string to use before a "://" in a request,
* ex: "http", "https", "git", "ws", etc. Defaults to http
* @param networkID Sets the NetworkID of the class. Default [[DefaultNetworkID]]
* @param XChainID Sets the blockchainID for the AVM. Will try to auto-detect,
* otherwise default "2eNy1mUFdmaxXNj1eQHUe7Np4gju9sJsEtWQ4MX3ToiNKuADed"
* @param CChainID Sets the blockchainID for the EVM. Will try to auto-detect,
* otherwise default "2CA6j5zYzasynPsFeNoqWkmTCt3VScMvXUZHbfDJ8k3oGzAPtU"
* @param hrp The human-readable part of the bech32 addresses
* @param skipinit Skips creating the APIs. Defaults to false
*/
constructor(
host?: string,
port?: number,
protocol: string = "http",
networkID: number = DefaultNetworkID,
XChainID: string = undefined,
CChainID: string = undefined,
hrp: string = undefined,
skipinit: boolean = false
) {
super(host, port, protocol)
let xchainid: string = XChainID
let cchainid: string = CChainID
if (
typeof XChainID === "undefined" ||
!XChainID ||
XChainID.toLowerCase() === "x"
) {
if (networkID.toString() in Defaults.network) {
xchainid = Defaults.network[`${networkID}`].X.blockchainID
} else {
xchainid = Defaults.network[12345].X.blockchainID
}
}
if (
typeof CChainID === "undefined" ||
!CChainID ||
CChainID.toLowerCase() === "c"
) {
if (networkID.toString() in Defaults.network) {
cchainid = Defaults.network[`${networkID}`].C.blockchainID
} else {
cchainid = Defaults.network[12345].C.blockchainID
}
}
if (typeof networkID === "number" && networkID >= 0) {
this.networkID = networkID
} else if (typeof networkID === "undefined") {
networkID = DefaultNetworkID
}
if (typeof hrp !== "undefined") {
this.hrp = hrp
} else {
this.hrp = getPreferredHRP(this.networkID)
}
if (!skipinit) {
this.addAPI("admin", AdminAPI)
this.addAPI("auth", AuthAPI)
this.addAPI("xchain", AVMAPI, "/ext/bc/X", xchainid)
this.addAPI("cchain", EVMAPI, "/ext/bc/C/avax", cchainid)
this.addAPI("health", HealthAPI)
this.addAPI("info", InfoAPI)
this.addAPI("index", IndexAPI)
this.addAPI("keystore", KeystoreAPI)
this.addAPI("metrics", MetricsAPI)
this.addAPI("pchain", PlatformVMAPI)
}
}
}
export { Avalanche }
export { AvalancheCore }
export { BinTools }
export { BN }
export { Buffer }
export { DB }
export { HDNode }
export { GenesisAsset }
export { GenesisData }
export { Mnemonic }
export { PubSub }
export { Socket }
export * as admin from "./apis/admin"
export * as auth from "./apis/auth"
export * as avm from "./apis/avm"
export * as common from "./common"
export * as evm from "./apis/evm"
export * as health from "./apis/health"
export * as index from "./apis/index"
export * as info from "./apis/info"
export * as keystore from "./apis/keystore"
export * as metrics from "./apis/metrics"
export * as platformvm from "./apis/platformvm"
export * as utils from "./utils"
export * as networkIDs from './constants/networkIDs';
export * from './serializable';
export { Utxo } from './serializable/avax/utxo';
export * from './signer';
export * from './utils';
export * as utils from './utils';
export * from './vms';
export { Info } from './info/info';

@@ -1,133 +0,15 @@

/**
* @packageDocumentation
* @module Utils-Base58
*/
import BN from "bn.js"
import { Buffer } from "buffer/"
import { Base58Error } from "../utils/errors"
import { base58 } from '@scure/base';
import type { BytesCoder } from '@scure/base';
import { sha256 } from '@noble/hashes/sha256';
import { concatBytes } from './buffer';
/**
* A Base58 class that uses the cross-platform Buffer module. Built so that Typescript
* will accept the code.
*
* ```js
* let b58:Base58 = new Base58();
* let str:string = b58.encode(somebuffer);
* let buff:Buffer = b58.decode(somestring);
* ```
*/
export class Base58 {
private static instance: Base58
export const base58check: BytesCoder = {
encode(data) {
return base58.encode(concatBytes(data, sha256(data).subarray(-4)));
},
decode(string) {
return base58.decode(string).subarray(0, -4);
},
};
private constructor() {}
/**
* Retrieves the Base58 singleton.
*/
static getInstance(): Base58 {
if (!Base58.instance) {
Base58.instance = new Base58()
}
return Base58.instance
}
protected b58alphabet: string =
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
protected alphabetIdx0 = "1"
protected b58 = [
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 255, 255, 255, 255, 255, 255,
255, 9, 10, 11, 12, 13, 14, 15, 16, 255, 17, 18, 19, 20, 21, 255, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31, 32, 255, 255, 255, 255, 255, 255, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 255, 44, 45, 46, 47, 48, 49, 50, 51, 52,
53, 54, 55, 56, 57, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255
]
protected big58Radix: BN = new BN(58)
protected bigZero: BN = new BN(0)
/**
* Encodes a {@link https://github.com/feross/buffer|Buffer} as a base-58 string
*
* @param buff A {@link https://github.com/feross/buffer|Buffer} to encode
*
* @returns A base-58 string.
*/
encode = (buff: Buffer): string => {
let x: BN = new BN(buff.toString("hex"), "hex", "be")
let answer: string = "" // = Buffer.alloc(buff.length*136/100, 0);
while (x.cmp(this.bigZero) > 0) {
const mod: BN = x.mod(this.big58Radix)
x = x.div(this.big58Radix)
answer += this.b58alphabet[mod.toNumber()]
}
for (let i: number = 0; i < buff.length; i++) {
if (buff.readUInt8(i) !== 0) {
break
}
answer += this.alphabetIdx0
}
return answer.split("").reverse().join("")
}
/**
* Decodes a base-58 into a {@link https://github.com/feross/buffer|Buffer}
*
* @param b A base-58 string to decode
*
* @returns A {@link https://github.com/feross/buffer|Buffer} from the decoded string.
*/
decode = (b: string): Buffer => {
const answer: BN = new BN(0)
const j: BN = new BN(1)
for (let i: number = b.length - 1; i >= 0; i--) {
const tmp: number = this.b58[b.charCodeAt(i)]
if (tmp === 255) {
throw new Base58Error(
"Error - Base58.decode: not a valid base58 string"
)
}
const scratch: BN = new BN(tmp)
scratch.imul(j)
answer.iadd(scratch)
j.imul(this.big58Radix)
}
/* we need to make sure the prefaced 0's are put back to be even in this string */
let anshex = answer.toString("hex")
anshex = anshex.length % 2 ? `0${anshex}` : anshex
/**
* We need to replace all zeros that were removed during our conversation process.
* This ensures the buffer returns is the appropriate length.
*/
const tmpval: Buffer = Buffer.from(anshex, "hex")
let numZeros: number
for (numZeros = 0; numZeros < b.length; numZeros++) {
if (b[`${numZeros}`] !== this.alphabetIdx0) {
break
}
}
const xlen: number = numZeros + tmpval.length
const result: Buffer = Buffer.alloc(xlen, 0)
tmpval.copy(result, numZeros)
return result
}
}
export { base58 } from '@scure/base';

@@ -1,13 +0,17 @@

export * from "./base58"
export * from "./bintools"
export * from "./mnemonic"
export * from "./constants"
export * from "./db"
export * from "./errors"
export * from "./fetchadapter"
export * from "./hdnode"
export * from "./helperfunctions"
export * from "./payload"
export * from "./persistenceoptions"
export * from "./pubsub"
export * from "./serialization"
export * from './address';
export * from './addressesFromBytes';
export * from './base58';
export * from './buffer';
export * from './bytesCompare';
export * from './costs';
export * from './devutils';
export * from './secp256k1';
export * from './typeGuards';
export * from './UTXOSet';
export * from './addChecksum';
export * from './addressMap';
export * from './getTransferableInputsByTx';
export * from './getTransferableOutputsByTx';
export * from './getBurnedAmountByTx';
export * from './validateBurnedAmount';
export { unpackWithManager, getManagerForVM, packTx } from './packTx';

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc