LimitOrder Contract with JavaScript
This tutorial is intended to help you call a Limit Order Contract using JavaScript. Templates are prebuilt TEAL programs that allow parameters to be injected into them from the SDKs that configure the contract. In this example, we are going to instantiate the LimitOrder Template and show how it can be used with a transaction.
Requirements
- Algorand JavaScript SDK
- Access to an Algorand node
- an Algorand asset to use in the contract
Background
Algorand provides many templates for Smart Contract implementation in the SDKs. The LimitOrder Contract is just one of the templates and is described in the reference documentation. Limit Order Contracts are contract accounts that can disburse Algos for Algorand Assets in a defined ratio. Additionally, a minimum withdrawal amount can be set. If the funds are not claimed after a certain period of time, the original owner can reclaim the remaining funds.
Steps
1. Get Asset Owner and the Contract Owner Accounts
The Limit Order template can be instantiated with a set of predefined parameters that configure the Limit Order contract. These parameters should not be confused with Transaction parameters that are passed into the contract when using the Limit Order. These parameters configure how the Limit Order will function:
TMPL_ASSET
: Integer ID of the assetTMPL_SWAPN
: Numerator of the exchange rate (TMPL_SWAPN assets per TMPL_SWAPD microAlgos, or better)TMPL_SWAPD
: Denominator of the exchange rate (TMPL_SWAPN assets per TMPL_SWAPD microAlgos, or better)TMPL_TIMEOUT
: The round after which all of the algos in this contract may be closed back to TMPL_OWNTMPL_OWN
: The recipient of the asset (if the order is filled), or of the contract’s algo balance (after TMPL_TIMEOUT)TMPL_FEE
: The maximum fee used in any transaction spending out of this contractTMPL_MINTRD
: The minimum number of microAlgos that may be spent out of this contract as part of a trade
So for example, If you want to specify that the contact will approve a transaction where it is willing to spend 3000 microAlgos for 1 Asset with id of TMPL_ASSET
, you would set the TMPL_SWAPN
parameter to 1 and the TMPL_SWAPD
to 3000. The TMPL_MINTRD
should be set to 2999 in this example as it must be less than the amount of microAlgos for the one asset.
For this tutorial, we first need to define, the owner of the contract, and the owner of the asset with asset id = TMPL_ASSET
.
// Handle importing needed modules
const algosdk = require('algosdk');
const fs = require('fs');
const limitTemplate = require("algosdk/src/logicTemplates/limitorder");
// Retrieve the token, server and port values for your installation in the algod.net
// and algod.token files within the data directory
const token = "<your-api-token>";
const server = "http://<your-algod-host>";
const port = //<your-algod-port>;
// Instantiate the algod wrapper
let algodclient = new algosdk.Algod(token, server, port);
(async() => {
// Recover accounts used in example
// Account 1 is the asset owner
// Used later in the example
var account1_mnemonic = "portion never forward pill lunch organ biology" +
" weird catch curve isolate plug innocent skin grunt" +
" bounce clown mercy hole eagle soul chunk type absorb trim";
var assetOwner = algosdk.mnemonicToSecretKey(account1_mnemonic);
console.log(assetOwner.addr);
// Owner is the owner of the contract
let owner = "AJNNFQN7DSR7QEY766V7JDG35OPM53ZSNF7CU264AWOOUGSZBMLMSKCRIU";
})().catch(e => {
console.log(e);
});
2. Create Limit Order Template
The template can now be created with the correct ratio for assets to microAlgos.
// Handle importing needed modules
const algosdk = require('algosdk');
const fs = require('fs');
const limitTemplate = require("algosdk/src/logicTemplates/limitorder");
// Retrieve the token, server and port values for your installation in the algod.net
// and algod.token files within the data directory
const token = "<your-api-token>";
const server = "http://<your-algod-host>";
const port = //<your-algod-port>;
// Instantiate the algod wrapper
let algodclient = new algosdk.Algod(token, server, port);
(async() => {
// Recover accounts used in example
// Account 1 is the asset owner
// Used later in the example
var account1_mnemonic = "portion never forward pill lunch organ biology" +
" weird catch curve isolate plug innocent skin grunt" +
" bounce clown mercy hole eagle soul chunk type absorb trim";
var assetOwner = algosdk.mnemonicToSecretKey(account1_mnemonic);
console.log(assetOwner.addr);
// Owner is the owner of the contract
let owner = "AJNNFQN7DSR7QEY766V7JDG35OPM53ZSNF7CU264AWOOUGSZBMLMSKCRIU";
// Inputs
// Limit contract should be two receivers in an
// ratn/ratd ratio of assetid to microalgos
// ratn is the number of assets
// ratd is the number of microAlgos
let ratn = parseInt(1);
let ratd = parseInt(3000);
// assetID is the asset id number
// of the asset to be traded
// This must be created by asset owner
let assetID = 316084;
// At what round the contract expires
// The ower can retreive leftover funds after this round
let expiryRound = 5000000;
// The minimum number of microAlgos that may be spent
// out of this contract as part of a trade
let minTrade = 2999;
// protect the account so its not drained
// with an excessive fee
let maxFee = 2000;
// Instaniate the template
let limit = new limitTemplate.LimitOrder(owner, assetID, ratn,ratd, expiryRound, minTrade, maxFee);
// Outputs
// At this point you can write the program to file to be used
// by someone who wants to sumbit a transaction against it
let program = limit.getProgram();
console.log("limit order addr: " + limit.getAddress());
})().catch(e => {
console.log(e);
});
At this point, the Limit Order contract account must be funded before any transactions can be issued against it. Use the dispenser to do this now. Also, note that program bytes can be saved to use at a later time or in another application at this point.
Learn More
- Add Funds using Dispenser
- Smart Contracts - Contract Accounts
3. Create and Submit Transaction against Contract
The Limit Order contract template offers a helper method to create the proper transactions against the contract called getSwapAssetsTransaction
. This function takes an assetAmount
and a microAlgoAmount
for the total transaction and creates two transactions, one for each receiver and then groups these two transactions into an atomic transfer. The first transaction is signed with the program logic and the second transaction is signed with the secret key of the asset owner. The bytes of the grouped transactions to submit are returned. These bytes can then be submitted to the blockchain.
// Handle importing needed modules
const algosdk = require('algosdk');
const fs = require('fs');
const limitTemplate = require("algosdk/src/logicTemplates/limitorder");
// Retrieve the token, server and port values for your installation in the algod.net
// and algod.token files within the data directory
const token = "<your-api-token>";
const server = "http://<your-algod-host>";
const port = //<your-algod-port>;
// Instantiate the algod wrapper
let algodclient = new algosdk.Algod(token, server, port);
(async() => {
// Recover accounts used in example
// Account 1 is the asset owner
// Used later in the example
var account1_mnemonic = "portion never forward pill lunch organ biology" +
" weird catch curve isolate plug innocent skin grunt" +
" bounce clown mercy hole eagle soul chunk type absorb trim";
var assetOwner = algosdk.mnemonicToSecretKey(account1_mnemonic);
console.log(assetOwner.addr);
// Owner is the owner of the contract
let owner = "AJNNFQN7DSR7QEY766V7JDG35OPM53ZSNF7CU264AWOOUGSZBMLMSKCRIU";
// Inputs
// Limit contract should be two receivers in an
// ratn/ratd ratio of assetid to microalgos
// ratn is the number of assets
// ratd is the number of microAlgos
let ratn = parseInt(1);
let ratd = parseInt(3000);
// assetID is the asset id number
// of the asset to be traded
// This must be created by asset owner
let assetID = 316084;
// At what round the contract expires
// The ower can retreive leftover funds after this round
let expiryRound = 5000000;
// The minimum number of microAlgos that may be spent
// out of this contract as part of a trade
let minTrade = 2999;
// protect the account so its not drained
// with an excessive fee
let maxFee = 2000;
// Instaniate the template
let limit = new limitTemplate.LimitOrder(owner, assetID, ratn,ratd, expiryRound, minTrade, maxFee);
// Outputs
// At this point you can write the program to file to be used
// by someone who wants to sumbit a transaction against it
let program = limit.getProgram();
console.log("limit order addr: " + limit.getAddress());
// Get the relevant params from the algod for the network
let params = await algodclient.getTransactionParams();
let endRound = params.lastRound + parseInt(1000);
// create an atomic transfer based on the two recipients
// which can be submitted in one operation
// The program can be read from a file if this is done
// in a separate application
// The assetAmount and microAlgoAmounts are what is wanting to be
// be traded.
let assetAmount = parseInt(1);
let microAlgoAmount = parseInt(3000);
// The secrete key is the spending key of the asset owner not the microAlgo owner
let secretKey = assetOwner.sk;
let txnBytes = limitTemplate.getSwapAssetsTransaction(program, assetAmount,
microAlgoAmount, secretKey, params.fee, params.lastRound, endRound, params.genesishashb64);
// Submit the transaction
let tx = (await algodclient.sendRawTransaction(txnBytes));
console.log( "txId: " + tx.txId );
})().catch(e => {
console.log(e);
});
Learn More
- Atomic Transfers