Giter VIP home page Giter VIP logo

dag4.js's Introduction

DAG4 - DAG JavaScript SDK

This is the DAG [JavaScript SDK][docs] for Constellation Network.

Please read the [documentation][docs] for more detailed instructions. The following includes basic install and configuration.

Installation

Node

npm install @stardust-collective/dag4

Yarn

yarn add @stardust-collective/dag4

Usage

Interacting with wallets

Create a private key

const pk = dag4.keyStore.generatePrivateKey();

Login with the private key

dag4.account.loginPrivateKey(pk);

Check DAG address

const address = dag4.account.address;

Connecting to the network

import { dag4 } from '@stardust-collective/dag4';

// Connect to default network endpoints
dag4.account.connect({
    networkVersion: '2.0',
    testnet: true
})

// Or provide specific configuration
// L0/L1 urls can point to a specific node
dag4.account.connect({
    networkVersion: '2.0',
    beUrl: 'https://be-testnet.constellationnetwork.io',
    l0Url: 'http://13.52.246.74:9000',
    l1Url: 'http://13.52.246.74:9010'
})

Check address balance

// Get an address balance
const balance = await dag4.network.getAddressBalance('DAGabc123...');

Get address last reference

dag4.network.getAddressLastAcceptedTransactionRef('DAGabc123...');

Sending transactions

Dag4.js supports both online and offline transaction signing as well as bulk transaction sending. You must be logged in with a pk and connected to the network to send transactions.

Send a single transaction

const toAddress = 'DAGabc123...';
const amount = 25.551;
const fee = 0;

dag4.account.transferDag(toAddress, amount, fee);

Send bulk transactions

const transfers = [
    {address: 'DAGabc123...', amount: 0.000123, fee: 0},
    {address: 'DAGabc124...', amount: 0.000124, fee: 0},
    {address: 'DAGabc125...', amount: 0.000125, fee: 0},
    {address: 'DAGabc126...', amount: 0.000126, fee: 0},
    {address: 'DAGabc127...', amount: 0.000127, fee: 0},
    {address: 'DAGabc128...', amount: 0.000128, fee: 0.00000001}
];

  const hashes = await dag4.account.transferDagBatch(transfers);

Sign transactions offline, then send online

// First get the last txn reference, this can also be retrieved from an offline source
const lastRef = await dag4.network.getAddressLastAcceptedTransactionRef('DAGWalletSendingAddress');

const transfers = [
    {address: 'DAGabc123...', amount: 0.000123, fee: 0},
    {address: 'DAGabc124...', amount: 0.000124, fee: 0}
];

const txns = await dag4.account.generateBatchTransactions(transfers, lastRef);

// Send online when ready
const hashes = await dag4.account.sendBatchTransactions(txns);

Checking transaction status

When a transaction is sent to the network and is accepted, the response will return a hash that can be used to monitor the status of the transaction.

The transaction will initially be in a "waiting" state before it's included in a block and sent to a snapshot. While in this state you can check its status with the L1 API. Once processed by the network, the transaction will no longer be found via the L1 API and will be found in the block explorer API. At this point the transaction is considered final.

The following process can be used to confirm a transaction has been processed and reached a successful final state.

// Send transaction
const hash = await dag4.network.postTransaction(txn);

// Keep checking the transaction status until this returns null
const pendingTx = await dag4.network.getPendingTransaction(txHash);

// Check that the transaction has registered on the block explore API
if (pendingTx === null) {
  const confirmedTx = await dag4.network.getTransaction(txHash);

  if (confirmedTx) {
    // Txn is confirmed - from this point the state cannot be changed
    console.log('Transaction confirmed');
  } else {
    // The txn cannot be found on block explorer. It's a good idea to wait several seconds and try again to confirm the txn has actually been dropped
    console.log('Transaction dropped - not confirmed');
  }
}

Upgrading from networkVersion 1.0

v1.2.0 of the dag4 package introduces support for Constellation mainnet 2.0 and a number of new features specific to the new network version. It is also 100% backwards compatible with existing mainnet 1.0 integrations from earlier versions (1.1.x) of the package. Not all endpoints relevant to mainnet 1.0 are used in 2.0 though so there is a migration process to prepare for the switchover in networks.

Migrate all calls to specific APIs to use dag4.network

// Mainnet 1.0
await dag4.network.loadBalancerApi.getAddressLastAcceptedTransactionRef('DAGabc123');

// Mainnet 1.0 and 2.0 support based on configured network version
await dag4.network.getAddressLastAcceptedTransactionRef('DAGabc123');

Use dag4.account as much as possible

// mainnet 1.0
await dag4.keyStore.generateTransaction(...);

// mainnet 1.0 and 2.0 support based on configured network version
await dag4.account.generateSignedTransaction(...);

After the above changes, both versions of the network are supported with a configuration change

// mainnent 1.0 support
dag4.account.connect({
    networkVersion: '1.0'
});

// mainnet 2.0 support
dag4.account.connect({
    networkVersion: '2.0'
});

Documentation

Documentation can be found at [Wiki][docs].

Building

Build the dag4.js package:

npm run build

Testing (mocha)

npm test --workspaces

Community


License

License: GPL v3 This project is licensed under the terms of the MIT license.

dag4.js's People

Contributors

ffox77 avatar alexbrandes avatar juandavidkincaid avatar cmirandac665 avatar juanolmedo1 avatar fmfmartins avatar

Stargazers

 avatar Scott Muangsrichan avatar  avatar Stoyan Zhekov avatar Crystal_Alchemist avatar David Bonachera avatar  avatar Hoàng Đức Trí avatar JuliusHimself avatar  avatar  avatar Itamar Peretz avatar dewyze avatar christy lai avatar Jon Greenwood avatar Filip Macek avatar

Watchers

James Cloos avatar Nick Meessen - de Wit avatar Brian Thamm avatar  avatar João Carvalho avatar VJ avatar  avatar

dag4.js's Issues

Transaction hash offline

Hi, is it possible to generate transaction hash before posting it to the network? Not DAG but when working with other blockchains, I sometimes encounter network error when submitting transactions. When that happens, I couldn't track if the transaction was included in the block without the offline txHash.

Tx never goes through

Hi!

When trying to send a single Tx or batch Tx to the integrationnet 2.0, I get a tx hash in return but the tx is never pushed to the chain.

Tx hash: 9ff4ced96314104929fb8051a377502dc30e53cbe892022cdc42410976cfebfb

I have been following the documentations and this code used to work before. Could you help here? Please

  • Package: "@stardust-collective/dag4": "^2.2.0"

Chain configuration:

  dag4.account.connect({
    networkVersion: "2.0",
    beUrl: "https://be-integrationnet.constellationnetwork.io",
    l0Url: "https://l0-lb-integrationnet.constellationnetwork.io",
    l1Url: "https://l1-lb-integrationnet.constellationnetwork.io",
  });

Script:

async function simpleTransfer(to: string, amount: number) {
  const address = dag4.account.address;

  console.log("sending from :", address);

  const res = await dag4.account.transferDag(
    to,
    amount, 
    0 
  );

  console.log(res);
}

simpleTransfer("DAG7sx7SSuGNeM88qm4hdpoCnveQE9QCraf4Mj3C", 10);

Error when sending Transaction

Hello,

I have been reading all the documentation and following the steps to create a wallet, check balances and send a transaction. But I have not been able to execute the transaction as I always get the same error when executing a simple transaction or even a transferDagBatch. Could you help here? Please

- Error:

[Running] ts-node "c:\Users\elric\dev\DAG-Bridge\src\utils\dagMethods.ts"
- Transfering from Signer:  DAG1x6erYwDLvt3zXxZvdHaZcNVhWfFFVC1Qunjd
   - Balance: 5 DAGs

c:\Users\elric\dev\DAG-Bridge\node_modules\@stardust-collective\dag4-core\src\cross-platform\clients\fetch.http.ts:70
            throw new Error(text);
                  ^
Error
    at FetchRestService.<anonymous> (c:\Users\elric\dev\DAG-Bridge\node_modules\@stardust-collective\dag4-core\src\cross-platform\clients\fetch.http.ts:70:19)
    at Generator.next (<anonymous>)
    at fulfilled (c:\Users\elric\dev\DAG-Bridge\node_modules\@stardust-collective\dag4-core\dist\cjs\cross-platform\clients\fetch.http.js:5:58)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)

- Script as proof of concept:

import { dag4 } from "@stardust-collective/dag4";

dag4.account.connect({
  networkVersion: "2.0",
  testnet: true,
});

dag4.account.loginPrivateKey(DAG_PRIVATE_KEY);
const address = dag4.account.address;

// GET Balance of a Wallet
export async function getBalance(dagAddress: string) {
  const { balance } = await dag4.network.getAddressBalance(dagAddress);
  return balance;
}

// Send Transaction from wallet to wallet
async function simpleTx() {
  const balance = await getBalance(address);

  console.log(`- Transfering from Signer:  ${address}`);
  console.log(`   - Balance: ${Number(balance) / 10 ** 8} DAGs\n`);

  const toAddress = "DAG6i1i79c56DATYAxzRoynRaLmCG7mWwj7jTXzo";
  const amount = 1;
  const fee = 0;

  await dag4.account.transferDag(toAddress, amount, fee);
}

simpleTx();

SDK Version: "@stardust-collective/dag4": "^2.2.0"

Unsafe to use Amount as number

Hi, according to CoinMarketCap your total supply is 3,711,998,690 DAG. If convert to the smallest unit it is 3,711,998,690 x 1e8, this value is greatly bigger than Javascript MAX_SAFE_INTEGER. It is unsafe to use number bigger than MAX_SAFE_INTEGER

Non-200 network errors are not well described in cross platform client

When a network request receives a non-200 response from the cross-platform client, the error returned is not helpful and doesn't indicate the response code that was received. Debugging these issues would be much easier if we returned the response code.

Error thrown at:
https://github.com/StardustCollective/dag4.js/blob/main/packages/dag4-core/src/cross-platform/clients/fetch.http.ts#L62

Example current error output:

/project/node_modules/@stardust-collective/dag4-core/src/cross-platform/clients/fetch.http.ts:70
            throw new Error(text);
                  ^
Error
    at FetchRestService.<anonymous> (/project/node_modules/@stardust-collective/dag4-core/src/cross-platform/clients/fetch.http.ts:70:19)
    at Generator.next (<anonymous>)
    at fulfilled (/project/node_modules/@stardust-collective/dag4-core/dist/cjs/cross-platform/clients/fetch.http.js:5:58)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Expected output example:

/project/node_modules/@stardust-collective/dag4-core/src/cross-platform/clients/fetch.http.ts:70
            throw new Error(text);
                  ^
Network Error Response
  url: https://be-mainnet.constellationnetwork.io/cluster/info
  responseCode: 400
  message: Invalid parameter
    at FetchRestService.<anonymous> (/project/node_modules/@stardust-collective/dag4-core/src/cross-platform/clients/fetch.http.ts:70:19)
    at Generator.next (<anonymous>)
    at fulfilled (/project/node_modules/@stardust-collective/dag4-core/dist/cjs/cross-platform/clients/fetch.http.js:5:58)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Is it able to chain pending transaction?

Hi, is it able to chain pending or future transactions? For example, I want to send Dag from my address to 3 different addresses, I don't want to wait for each transaction to finalize before creating a new one, can I create 3 transactions at the same time which the next tx chaining from the previous and submit all of them to the network?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.