
Security News
Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
The algosdk npm package is a JavaScript library for interacting with the Algorand blockchain. It provides tools for building applications on Algorand, including creating and managing accounts, sending transactions, and interacting with smart contracts.
Account Management
This feature allows you to create and manage Algorand accounts. The code sample demonstrates how to generate a new account and retrieve its address and mnemonic.
const algosdk = require('algosdk');
const account = algosdk.generateAccount();
console.log('Address:', account.addr);
console.log('Mnemonic:', algosdk.secretKeyToMnemonic(account.sk));
Transaction Handling
This feature enables the creation and submission of transactions on the Algorand blockchain. The code sample shows how to create a payment transaction, sign it, and send it to the network.
const algosdk = require('algosdk');
const algodClient = new algosdk.Algodv2(token, server, port);
const txn = algosdk.makePaymentTxnWithSuggestedParamsFromObject({
from: senderAddress,
to: receiverAddress,
amount: 1000000,
suggestedParams: await algodClient.getTransactionParams().do()
});
const signedTxn = txn.signTxn(senderPrivateKey);
const sendTx = await algodClient.sendRawTransaction(signedTxn).do();
console.log('Transaction ID:', sendTx.txId);
Smart Contract Interaction
This feature allows interaction with Algorand smart contracts. The code sample demonstrates how to call a smart contract with arguments using a NoOp transaction.
const algosdk = require('algosdk');
const algodClient = new algosdk.Algodv2(token, server, port);
const appArgs = [algosdk.encodeUint64(123)];
const txn = algosdk.makeApplicationNoOpTxn(senderAddress, await algodClient.getTransactionParams().do(), appId, appArgs);
const signedTxn = txn.signTxn(senderPrivateKey);
const sendTx = await algodClient.sendRawTransaction(signedTxn).do();
console.log('Transaction ID:', sendTx.txId);
Web3.js is a JavaScript library for interacting with the Ethereum blockchain. It provides similar functionalities to algosdk, such as account management, transaction handling, and smart contract interaction, but is specific to Ethereum.
Ethers.js is another JavaScript library for Ethereum, offering a more lightweight and modular approach compared to web3.js. Like algosdk, it provides tools for managing accounts, sending transactions, and interacting with smart contracts, but is focused on the Ethereum ecosystem.
AlgoSDK is a javascript library for communicating with the Algorand network for modern browsers and node.js.
$ npm install algosdk
The dist
directory contains a minified version of the library - algosdk.min.js
.
Include this line in your HTML.
<script src="algosdk.min.js"/>
const token = "Your algod API token";
const server = "http://127.0.0.1";
const port = 8080;
const client = new algosdk.Algod(token, server, port);
(async () => {
console.log(await client.status());
})().catch(e => {
console.log(e);
});
For detailed information about the different API calls in client
, visit https://developer.algorand.org
var keys = algosdk.generateAccount();
Example result
{addr: "IB3NJALXLDX5JLYCD4TMTMLVCKDRZNS4JONHMIWD6XM7DSKYR7MWHI6I7U", sk: Uint8Array(64)}
var mnemonic = algosdk.secretKeyToMnemonic(keys.sk);
Example result
"gorilla fortune learn marble essay uphold defense hover index effort ice atom figure will improve mom indoor mansion people elder hill material donkey abandon gown"
var secret_key = algosdk.mnemonicToSecretKey(mnemonic);
Example result
{addr: "IB3NJALXLDX5JLYCD4TMTMLVCKDRZNS4JONHMIWD6XM7DSKYR7MWHI6I7U", sk: Uint8Array(64)}
var isValid = algosdk.isValidAddress("IB3NJALXLDX5JLYCD4TMTMLVCKDRZNS4JONHMIWD6XM7DSKYR7MWHI6I7U");
Example result
true
In order to create and sign a transaction, create first an object with the relevant properties.
There is no need to specify the from
address, it is computed directly from the secretKey.
Note -- The fields names must be identical to the following example's.
Note 2 -- In order to encode data into the note field, simply encode any JavaScript object using algosdk.encodeObj(o)
.
var txn = {
"to": "7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q",
"fee": 10,
"amount": 847,
"firstRound": 51,
"lastRound": 61,
"genesisID": "devnet-v33.0",
"genesisHash": "JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI=",
"closeRemainderTo": "IDUTJEUIEVSMXTU4LGTJWZ2UE2E6TIODUKU6UW3FU3UKIQQ77RLUBBBFLA",
"note": new Uint8Array(Buffer.from("6gAVR0Nsv5Y=", "base64"))
};
Then, call signTransaction
and pass the transaction along with relevant private key.
var signedTxn = algosdk.signTransaction(txn, keys.sk);
Now signedTxn
can be posted to the network via algod.sendRawTransaction()
.
var mnemonic = algosdk.masterDerivationKeyToMnemonic(mdk);
Example result
label danger traffic dream path boss runway worry awful abuse stairs spare wasp clock steel impact swear eagle canal diagram nation upon creek abstract pride
var mdk = algosdk.mnemonicToMasterDerivationKey(mnemonic);
Example result
Uint8Array(32)
Bids have similar pattern to a transaction. First, create an object with the bid's information
var bid = {
"bidderKey": "IB3NJALXLDX5JLYCD4TMTMLVCKDRZNS4JONHMIWD6XM7DSKYR7MWHI6I7U",
"auctionKey": "7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q",
"bidAmount": 1000,
"maxPrice": 10,
"bidID": 2,
"auctionID": 56
};
Then, call signBid
and pass the bid and information along with the private key.
var signedBid = algosdk.signBid(bid, keys.sk);
In order to send a bid to the network. Embbed the output of algosdk.signBid
to a transaction note
's field.
For example,
var txn = {
"to": "7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q",
"fee": 10,
"amount": 0,
"firstRound": 51,
"lastRound": 61,
"note": <signedBid>
};
This SDK also supports manipulating multisignature payment and keyreg transactions.
To create a multisignature transaction, first set up the multisignature identity:
const params = {
version: 1,
threshold: 2,
addrs: [
"DN7MBMCL5JQ3PFUQS7TMX5AH4EEKOBJVDUF4TCV6WERATKFLQF4MQUPZTA",
"BFRTECKTOOE7A5LHCF3TTEOH2A7BW46IYT2SX5VP6ANKEXHZYJY77SJTVM",
"47YPQTIGQEO7T4Y4RWDYWEKV6RTR2UNBQXBABEEGM72ESWDQNCQ52OPASU",
],
};
With these multisignature parameters, we can now create a (partially) signed multisignature transaction:
// sk that matches "47YPQTIGQEO7T4Y4RWDYWEKV6RTR2UNBQXBABEEGM72ESWDQNCQ52OPASU"
let mnem3 = "advice pudding treat near rule blouse same whisper inner electric quit surface sunny dismiss leader blood seat clown cost exist hospital century reform able sponsor";
let seed = passphrase.seedFromMnemonic(mnem3);
let sk = nacl.keyPairFromSeed(seed).secretKey;
let txn = {
"to": "47YPQTIGQEO7T4Y4RWDYWEKV6RTR2UNBQXBABEEGM72ESWDQNCQ52OPASU",
"fee": 10,
"amount": 10000,
"firstRound": 1000,
"lastRound": 1000,
"genesisID": "devnet-v33.0",
"genesisHash": "JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI=",
"closeRemainderTo": "IDUTJEUIEVSMXTU4LGTJWZ2UE2E6TIODUKU6UW3FU3UKIQQ77RLUBBBFLA",
"note": new Uint8Array(Buffer.from("6gAVR0Nsv5Y=", "base64")),
};
let rawSignedTxn = algosdk.signMultisigTransaction(txn, params, sk).blob;
Now, we can broadcast this raw partially signed transaction to the network, which is valid if the threhsold is 1. We can also write it to a file (in node):
const fs = require('fs');
fs.writeFile("/tmp/example_multisig.tx", Buffer.from(rawSignedTxn), function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
We can import multiple files or raw signed transactions, and merge the multisignature transactions:
let partialTxn1 = new Uint8Array(fs.readFileSync('/tmp/example_multisig.tx'));
let partialTxn2 = new Uint8Array(fs.readFileSync('/tmp/example_multisig_two.tx'));
let mergedTsigTxn = algosdk.mergeMultisigTransactions([partialTxn1, partialTxn2]);
We can also append our own signature, with knowledge of the public identity (params):
let partialTxn1 = new Uint8Array(fs.readFileSync('/tmp/example_multisig.tx'));
const params = {
version: 1,
threshold: 2,
addrs: [
"DN7MBMCL5JQ3PFUQS7TMX5AH4EEKOBJVDUF4TCV6WERATKFLQF4MQUPZTA",
"BFRTECKTOOE7A5LHCF3TTEOH2A7BW46IYT2SX5VP6ANKEXHZYJY77SJTVM",
"47YPQTIGQEO7T4Y4RWDYWEKV6RTR2UNBQXBABEEGM72ESWDQNCQ52OPASU",
],
};
// sk corresponding to "DN7MBMCL5JQ3PFUQS7TMX5AH4EEKOBJVDUF4TCV6WERATKFLQF4MQUPZTA"
let mnem1 = "auction inquiry lava second expand liberty glass involve ginger illness length room item discover ahead table doctor term tackle cement bonus profit right above catch";
let seed = passphrase.seedFromMnemonic(mnem1);
let sk = nacl.keyPairFromSeed(seed).secretKey;
let appendedMsigTxn = algosdk.appendSignMultisigTransaction(partialTxn1, params, sk).blob;
Any transaction blob returned by the multisignature API can be submitted to the network:
let algodclient = new algosdk.Algod(atoken, aserver, aport);
//submit the transaction
(async () => {
let tx = (await algodclient.sendRawTransaction(appendedMsigTxn));
console.log(tx);
})().catch(e => {
console.log(e.error);
});
js-algorand-sdk is licensed under a MIT license. See the LICENSE file for details.
FAQs
The official JavaScript SDK for Algorand
The npm package algosdk receives a total of 105,869 weekly downloads. As such, algosdk popularity was classified as popular.
We found that algosdk demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Security News
React's CRA deprecation announcement sparked community criticism over framework recommendations, leading to quick updates acknowledging build tools like Vite as valid alternatives.
Security News
Ransomware payment rates hit an all-time low in 2024 as law enforcement crackdowns, stronger defenses, and shifting policies make attacks riskier and less profitable.