diff --git a/lib/order/__tests__/GenerateTransactionTypes.js b/lib/order/__tests__/GenerateTransactionTypes.js new file mode 100644 index 00000000..8784fe56 --- /dev/null +++ b/lib/order/__tests__/GenerateTransactionTypes.js @@ -0,0 +1,66 @@ +const withPlaceAssetTxns = require('../txns/sell/withPlaceAssetTxns'); +const makePlaceAlgoTxns = require('../txns/buy/makePlaceAlgoTxns'); +const compile = require('../compile/compile'); +const AlgodexApi = require('../../AlgodexApi'); + +const tesnet = { + config: { + algod: { + uri: 'https://node.testnet.algoexplorerapi.io', + token: '', + }, + indexer: { + uri: 'https://algoindexer.testnet.algoexplorerapi.io', + token: '', + }, + explorer: { + uri: 'https://indexer.testnet.algoexplorerapi.io', + port: '', + }, + dexd: { + uri: 'https://api-testnet-public.algodex.com/algodex-backend', + token: '', + }, + }, +}; + +const algodexApi = new AlgodexApi(tesnet); + +const TransactionGenerator = { + getPlaceASAEscrowOrderTxns: async function (order, optIn) { + return await withPlaceAssetTxns( + await compile({ + ...order, + appId: + typeof order.appId === 'undefined' + ? await algodexApi.getAppId(order) + : order.appId, + version: 6, + indexer: algodexApi.indexer, + wallet: { + ...order.wallet, + ...(await algodexApi.http.indexer.fetchAccountInfo(order.wallet)), + }, + }) + ); + }, + getPlaceAlgoEscrowOrderTxns: async function (order, optIn) { + return await makePlaceAlgoTxns( + await compile({ + ...order, + appId: + typeof order.appId === 'undefined' + ? await algodexApi.getAppId(order) + : order.appId, + version: 6, + indexer: algodexApi.indexer, + wallet: { + ...order.wallet, + ...(await algodexApi.http.indexer.fetchAccountInfo(order.wallet)), + }, + }) + ); + }, +}; + +module.exports = TransactionGenerator; diff --git a/lib/order/__tests__/TealAsaEscrowPlace.spec.js b/lib/order/__tests__/TealAsaEscrowPlace.spec.js index fc3357f5..87dff7c2 100644 --- a/lib/order/__tests__/TealAsaEscrowPlace.spec.js +++ b/lib/order/__tests__/TealAsaEscrowPlace.spec.js @@ -1,14 +1,16 @@ -it('should fix these tests', ()=>{ +it('should fix these tests', () => { const isBroken = true; expect(isBroken).toEqual(true); }); const testHelper = require('./setup.js'); -const createAppTest = require('./teal_tests/createAppTest.js'); -const deleteAppTest = require('./teal_tests/deleteAppTest.js'); -const executeAlgoOrderTest = require('./teal_tests/executeAlgoEscrowOrder.js'); +const connector = require('../../wallet/connectors/AlgoSDK'); + +// const deleteAppTest = require('./teal_tests/deleteAppTest.js'); + const placeASAOrderTest = require('./teal_tests/placeASAEscrowOrder.js'); -const closeASAOrderTest = require('./teal_tests/closeASAEscrowOrder.js'); +// const closeASAOrderTest = require('./teal_tests/closeASAEscrowOrder.js'); const constants = require('./constants.js'); +const setup = require('./beforeAll.js'); const JEST_MINUTE_TIMEOUT = 60 * 1000; const config = { @@ -18,12 +20,15 @@ const config = { openAccount: testHelper.getOpenAccount(), maliciousAccount: testHelper.getRandomAccount(), client: testHelper.getLocalClient(), + connector: connector, assetId: 66711302, }; -console.log('DEBUG_SMART_CONTRACT_SOURCE is: ' + constants.DEBUG_SMART_CONTRACT_SOURCE); +console.log( + 'DEBUG_SMART_CONTRACT_SOURCE is: ' + constants.DEBUG_SMART_CONTRACT_SOURCE +); + -const textEncoder = new TextEncoder(); // // // TODO: The negative tests need to be implemented. The commented ones out are examples but will not work with // // this transaction type. @@ -54,48 +59,72 @@ const textEncoder = new TextEncoder(); // // describe('ASA ESCROW ORDER BOOK', () => { - test('Create asa escrow order book', async () => { - config.creatorAccount = testHelper.getRandomAccount(); - config.executorAccount = testHelper.getRandomAccount(); - config.maliciousAccount = testHelper.getRandomAccount(); - config.appId = await createAppTest.runTest(config, false); - global.ASA_ESCROW_APP_ID = config.appId; - expect(config.appId).toBeGreaterThan(0); + function timeout(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} + beforeAll(async () => { + await setup(config, 'sell', true) + await timeout(7000) // Eliminates race condition where future indexer calls occur before setUp step fully propogates but after it succeeds + }, JEST_MINUTE_TIMEOUT); + // test( + // 'Create asa escrow order book', + // async () => { + // config.creatorAccount = testHelper.getRandomAccount(); + // config.executorAccount = testHelper.getRandomAccount(); + // config.maliciousAccount = testHelper.getRandomAccount(); + // config.appId = await createAppTest.runTest(config, false); + // global.ASA_ESCROW_APP_ID = config.appId; + // expect(config.appId).toBeGreaterThan(0); + // }, + // JEST_MINUTE_TIMEOUT, + // ); - test('Place asa escrow order', async () => { - const asaAmount = 400000; - const price = 1.25; - const result = await placeASAOrderTest.runTest(config, asaAmount, price); - expect(result).toBeTruthy(); - }, JEST_MINUTE_TIMEOUT); -// -// negTests.map( (negTestTxnConfig) => { -// const testName = `Negative algo full execution order test: txnNum: ${negTestTxnConfig.txnNum} field: ${negTestTxnConfig.field} val: ${negTestTxnConfig.val}`; -// test(testName, async () => { -// if (negTestTxnConfig.negTxn) { -// negTestTxnConfig.negTxn.unsignedTxn = await negTestTxnConfig.negTxn.unsignedTxnPromise; -// } -// const outerTxns = await executeAlgoOrderTest.runFullExecTest(config, true); -// outerTxns.map( (txn) => { -// const unsignedTxn = txn.unsignedTxn; -// // console.log({unsignedTxn}); -// }); -// const result = await testHelper.runNegativeTest(config, config.client, outerTxns, negTestTxnConfig); -// expect(result).toBeTruthy(); -// }, JEST_MINUTE_TIMEOUT); -// }); -// -// - test('Close asa escrow order', async () => { - const price = 1.25; - const result = await closeASAOrderTest.runTest(config, price); - expect(result).toBeTruthy(); - }, JEST_MINUTE_TIMEOUT); + test( + 'Place asa escrow order', + async () => { + const asaAmount = 0.4; + const price = 1.25; + const result = await placeASAOrderTest.runTest(config, asaAmount, price); + expect(result).toBeTruthy(); + }, + JEST_MINUTE_TIMEOUT + ); + // + // negTests.map( (negTestTxnConfig) => { + // const testName = `Negative algo full execution order test: txnNum: ${negTestTxnConfig.txnNum} field: ${negTestTxnConfig.field} val: ${negTestTxnConfig.val}`; + // test(testName, async () => { + // if (negTestTxnConfig.negTxn) { + // negTestTxnConfig.negTxn.unsignedTxn = await negTestTxnConfig.negTxn.unsignedTxnPromise; + // } + // const outerTxns = await executeAlgoOrderTest.runFullExecTest(config, true); + // outerTxns.map( (txn) => { + // const unsignedTxn = txn.unsignedTxn; + // // console.log({unsignedTxn}); + // }); + // const result = await testHelper.runNegativeTest(config, config.client, outerTxns, negTestTxnConfig); + // expect(result).toBeTruthy(); + // }, JEST_MINUTE_TIMEOUT); + // }); + // + // + // test( + // 'Close asa escrow order', + // async () => { + // const price = 1.25; + // const result = await closeASAOrderTest.runTest(config, price); + // expect(result).toBeTruthy(); + // }, + // JEST_MINUTE_TIMEOUT + // ); - test('Delete asa escrow order book', async () => { - const result = await deleteAppTest.runTest(config); - expect(result).toBeTruthy(); - }, JEST_MINUTE_TIMEOUT); + // test( + // 'Delete asa escrow order book', + // async () => { + // const result = await deleteAppTest.runTest(config); + // expect(result).toBeTruthy(); + // }, + // JEST_MINUTE_TIMEOUT + // ); }); // diff --git a/lib/order/__tests__/asa_dex_teal.js b/lib/order/__tests__/asa_dex_teal.js index 388d2e61..b13bf7a8 100644 --- a/lib/order/__tests__/asa_dex_teal.js +++ b/lib/order/__tests__/asa_dex_teal.js @@ -1,14 +1,14 @@ -///////////////////////////// +// /////////////////////////// // Alexander Trefonas // // 7/9/2021 // // Copyright Algodev Inc // // All Rights Reserved. // -///////////////////////////// +// /////////////////////////// const AsaOrderbookTeal = { - getClearProgram : function getClearProgram() { - const clearProgram = + getClearProgram: function getClearProgram() { + const clearProgram = ` #pragma version 2 // This program clears program state. @@ -19,12 +19,12 @@ const AsaOrderbookTeal = { ` ; return clearProgram; - }, - - getASAOrderBookApprovalProgram : function getASAOrderBookApprovalProgram() { - // stateful DEX contract - // This is for the order book - return ` + }, + + getASAOrderBookApprovalProgram: function getASAOrderBookApprovalProgram() { + // stateful DEX contract + // This is for the order book + return ` //////////////////////////////////////////////// // STATEFUL CONTRACT / // ORDER BOOK FOR ASA ESCROWS (SELL ORDERS) / @@ -327,8 +327,7 @@ const AsaOrderbookTeal = { `; - - } - }; - - module.exports = AsaOrderbookTeal; \ No newline at end of file + }, +}; + +module.exports = AsaOrderbookTeal; diff --git a/lib/order/__tests__/beforeAll.js b/lib/order/__tests__/beforeAll.js index df3982bb..8dbebcde 100644 --- a/lib/order/__tests__/beforeAll.js +++ b/lib/order/__tests__/beforeAll.js @@ -4,6 +4,9 @@ const AlgodexApi = require('../../AlgodexApi'); const apiConfig = require('../../../config.json'); const initAccounts = require('../../teal/test/initAccounts'); const logger = require('../../logger'); + + + /** * * @param {TestConfig} config Test Configuration @@ -19,31 +22,32 @@ async function beforeAll(config, type, optIn = false, newCreator = false) { } // Initalize API Client - await config.init(AlgodexApi, [apiConfig]); + // await config.init(AlgodexApi, [apiConfig]); + const api = new AlgodexApi(apiConfig) // Initialize Accounts and Configuration await initAccounts(config, optIn, newCreator); - const {client, creatorAccount} = config; - const createTxn = await txns.makeApplicationCreateTxn( - client, - type, - creatorAccount, - config.suggestedParams, - ); - const txId = createTxn.txID().toString(); + // const {client, creatorAccount} = config; + // const createTxn = await txns.makeApplicationCreateTxn( + // client, + // type, + // creatorAccount, + // config.suggestedParams, + // ); + // const txId = createTxn.txID().toString(); - const signedTxn = createTxn.signTxn(creatorAccount.sk); + // const signedTxn = createTxn.signTxn(creatorAccount.sk); - await client.sendRawTransaction(signedTxn).do(); + // await client.sendRawTransaction(signedTxn).do(); - // Wait for confirmation - await algosdk.waitForConfirmation(client, txId, 10); + // // Wait for confirmation + // await algosdk.waitForConfirmation(client, txId, 10); - // display results - const transactionResponse = await client.pendingTransactionInformation(txId).do(); + // // display results + // const transactionResponse = await client.pendingTransactionInformation(txId).do(); - config.setAppIndex(transactionResponse['application-index']); + // config.setAppIndex(transactionResponse['application-index']); } module.exports = beforeAll; diff --git a/lib/order/__tests__/constants.js b/lib/order/__tests__/constants.js index 620665a0..0eb5ed6b 100644 --- a/lib/order/__tests__/constants.js +++ b/lib/order/__tests__/constants.js @@ -1,61 +1,61 @@ -///////////////////////////// +// /////////////////////////// // Alexander Trefonas // // 7/9/2021 // // Copyright Algodev Inc // // All Rights Reserved. // -///////////////////////////// +// /////////////////////////// module.exports = { - DEBUG: 1, - DEBUG_SMART_CONTRACT_SOURCE: !!process.env.NEXT_PUBLIC_DEBUG_SMART_CONTRACT_SOURCE ? parseInt(process.env.NEXT_PUBLIC_DEBUG_SMART_CONTRACT_SOURCE) : 0, - INFO_SERVER: process.env.ALGODEX_INFO_HOST, + DEBUG: 1, + DEBUG_SMART_CONTRACT_SOURCE: process.env.NEXT_PUBLIC_DEBUG_SMART_CONTRACT_SOURCE ? parseInt(process.env.NEXT_PUBLIC_DEBUG_SMART_CONTRACT_SOURCE) : 0, + INFO_SERVER: process.env.ALGODEX_INFO_HOST, - ESCROW_CONTRACT_VERSION: 6, - ORDERBOOK_CONTRACT_VERSION: 5, - MIN_ESCROW_BALANCE: 500000, - MIN_ASA_ESCROW_BALANCE: 500000, + ESCROW_CONTRACT_VERSION: 6, + ORDERBOOK_CONTRACT_VERSION: 5, + MIN_ESCROW_BALANCE: 500000, + MIN_ASA_ESCROW_BALANCE: 500000, - LOCAL_ALGOD_SERVER: process.env.ALGODEX_ALGOD_SERVER || process.env.NEXT_PUBLIC_ALGODEX_ALGOD_SERVER || "https://node.testnet.algoexplorerapi.io", - LOCAL_ALGOD_PORT: process.env.ALGODEX_ALGOD_PORT || process.env.NEXT_PUBLIC_ALGODEX_ALGOD_PORT || "", - LOCAL_ALGOD_TOKEN: process.env.ALGODEX_ALGOD_TOKEN || process.env.NEXT_PUBLIC_ALGODEX_ALGOD_TOKEN || "", - LOCAL_BACKEND_API: "http://localhost/algodex-backend", - LOCAL_INDEXER_SERVER: "https://algoindexer.testnet.algoexplorerapi.io", - LOCAL_INDEXER_PORT: "", - LOCAL_INDEXER_TOKEN: "", - //intentionally same as test, assuming testnet being used on local setup - LOCAL_ALGO_ORDERBOOK_APPID: 18988007, - LOCAL_ASA_ORDERBOOK_APPID: 18988134, - //const indexer_server = "http://localhost"; - //const indexer_port = "8980"; + LOCAL_ALGOD_SERVER: process.env.ALGODEX_ALGOD_SERVER || process.env.NEXT_PUBLIC_ALGODEX_ALGOD_SERVER || 'https://node.testnet.algoexplorerapi.io', + LOCAL_ALGOD_PORT: process.env.ALGODEX_ALGOD_PORT || process.env.NEXT_PUBLIC_ALGODEX_ALGOD_PORT || '', + LOCAL_ALGOD_TOKEN: process.env.ALGODEX_ALGOD_TOKEN || process.env.NEXT_PUBLIC_ALGODEX_ALGOD_TOKEN || '', + LOCAL_BACKEND_API: 'http://localhost/algodex-backend', + LOCAL_INDEXER_SERVER: 'https://algoindexer.testnet.algoexplorerapi.io', + LOCAL_INDEXER_PORT: '', + LOCAL_INDEXER_TOKEN: '', + // intentionally same as test, assuming testnet being used on local setup + LOCAL_ALGO_ORDERBOOK_APPID: 18988007, + LOCAL_ASA_ORDERBOOK_APPID: 18988134, + // const indexer_server = "http://localhost"; + // const indexer_port = "8980"; - TEST_ALGOD_SERVER: ("ALGODEX_ALGOD_SERVER" in process.env) ? process.env.ALGODEX_ALGOD_SERVER : "https://node.testnet.algoexplorerapi.io", - TEST_ALGOD_PORT: ("ALGODEX_ALGOD_PORT" in process.env) ? process.env.ALGODEX_ALGOD_PORT : "", - TEST_ALGOD_TOKEN: ("ALGODEX_ALGOD_TOKEN" in process.env) ? process.env.ALGODEX_ALGOD_TOKEN : "", - TEST_BACKEND_API: "https://api-testnet.algodex.com/algodex-backend", - TEST_INDEXER_SERVER: "https://algoindexer.testnet.algoexplorerapi.io", - TEST_INDEXER_PORT: "", - TEST_INDEXER_TOKEN: "", - TEST_ALGO_ORDERBOOK_APPID: 16021155, - TEST_ASA_ORDERBOOK_APPID: 16021157, + TEST_ALGOD_SERVER: ('ALGODEX_ALGOD_SERVER' in process.env) ? process.env.ALGODEX_ALGOD_SERVER : 'https://node.testnet.algoexplorerapi.io', + TEST_ALGOD_PORT: ('ALGODEX_ALGOD_PORT' in process.env) ? process.env.ALGODEX_ALGOD_PORT : '', + TEST_ALGOD_TOKEN: ('ALGODEX_ALGOD_TOKEN' in process.env) ? process.env.ALGODEX_ALGOD_TOKEN : '', + TEST_BACKEND_API: 'https://api-testnet.algodex.com/algodex-backend', + TEST_INDEXER_SERVER: 'https://algoindexer.testnet.algoexplorerapi.io', + TEST_INDEXER_PORT: '', + TEST_INDEXER_TOKEN: '', + TEST_ALGO_ORDERBOOK_APPID: 16021155, + TEST_ASA_ORDERBOOK_APPID: 16021157, - PUBLIC_TEST_ALGOD_SERVER: ("ALGODEX_ALGOD_SERVER" in process.env) ? process.env.ALGODEX_ALGOD_SERVER : "https://node.testnet.algoexplorerapi.io", - PUBLIC_TEST_ALGOD_PORT: ("ALGODEX_ALGOD_PORT" in process.env) ? process.env.ALGODEX_ALGOD_PORT : "", - PUBLIC_TEST_ALGOD_TOKEN: ("ALGODEX_ALGOD_TOKEN" in process.env) ? process.env.ALGODEX_ALGOD_TOKEN : "", - PUBLIC_TEST_BACKEND_API: "https://api-testnet-public.algodex.com/algodex-backend", - PUBLIC_TEST_INDEXER_SERVER: "https://algoindexer.testnet.algoexplorerapi.io", - PUBLIC_TEST_INDEXER_PORT: "", - PUBLIC_TEST_INDEXER_TOKEN: "", - PUBLIC_TEST_ALGO_ORDERBOOK_APPID: 22045503, - PUBLIC_TEST_ASA_ORDERBOOK_APPID: 22045522, + PUBLIC_TEST_ALGOD_SERVER: ('ALGODEX_ALGOD_SERVER' in process.env) ? process.env.ALGODEX_ALGOD_SERVER : 'https://node.testnet.algoexplorerapi.io', + PUBLIC_TEST_ALGOD_PORT: ('ALGODEX_ALGOD_PORT' in process.env) ? process.env.ALGODEX_ALGOD_PORT : '', + PUBLIC_TEST_ALGOD_TOKEN: ('ALGODEX_ALGOD_TOKEN' in process.env) ? process.env.ALGODEX_ALGOD_TOKEN : '', + PUBLIC_TEST_BACKEND_API: 'https://api-testnet-public.algodex.com/algodex-backend', + PUBLIC_TEST_INDEXER_SERVER: 'https://algoindexer.testnet.algoexplorerapi.io', + PUBLIC_TEST_INDEXER_PORT: '', + PUBLIC_TEST_INDEXER_TOKEN: '', + PUBLIC_TEST_ALGO_ORDERBOOK_APPID: 22045503, + PUBLIC_TEST_ASA_ORDERBOOK_APPID: 22045522, - PROD_ALGOD_SERVER: ("ALGODEX_ALGOD_SERVER" in process.env) ? process.env.ALGODEX_ALGOD_SERVER : "https://node.algoexplorerapi.io", - PROD_ALGOD_PORT: ("ALGODEX_ALGOD_PORT" in process.env) ? process.env.ALGODEX_ALGOD_PORT : "", - PROD_ALGOD_TOKEN: ("ALGODEX_ALGOD_TOKEN" in process.env) ? process.env.ALGODEX_ALGOD_TOKEN : "", - PROD_BACKEND_API: "https://api.algodex.com/algodex-backend", - PROD_INDEXER_SERVER: "https://algoindexer.algoexplorerapi.io", - PROD_INDEXER_PORT: "", - PROD_INDEXER_TOKEN: "", - PROD_ALGO_ORDERBOOK_APPID: 354073718, - PROD_ASA_ORDERBOOK_APPID: 354073834, -}; \ No newline at end of file + PROD_ALGOD_SERVER: ('ALGODEX_ALGOD_SERVER' in process.env) ? process.env.ALGODEX_ALGOD_SERVER : 'https://node.algoexplorerapi.io', + PROD_ALGOD_PORT: ('ALGODEX_ALGOD_PORT' in process.env) ? process.env.ALGODEX_ALGOD_PORT : '', + PROD_ALGOD_TOKEN: ('ALGODEX_ALGOD_TOKEN' in process.env) ? process.env.ALGODEX_ALGOD_TOKEN : '', + PROD_BACKEND_API: 'https://api.algodex.com/algodex-backend', + PROD_INDEXER_SERVER: 'https://algoindexer.algoexplorerapi.io', + PROD_INDEXER_PORT: '', + PROD_INDEXER_TOKEN: '', + PROD_ALGO_ORDERBOOK_APPID: 354073718, + PROD_ASA_ORDERBOOK_APPID: 354073834, +}; diff --git a/lib/order/__tests__/dex_teal.js b/lib/order/__tests__/dex_teal.js index 65c90be5..bfd9374f 100644 --- a/lib/order/__tests__/dex_teal.js +++ b/lib/order/__tests__/dex_teal.js @@ -1,15 +1,15 @@ -///////////////////////////// +// /////////////////////////// // Alexander Trefonas // // 7/9/2021 // // Copyright Algodev Inc // // All Rights Reserved. // -///////////////////////////// +// /////////////////////////// const AlgoOrderbookTeal = { -getClearProgram : function getClearProgram() { - const clearProgram = + getClearProgram: function getClearProgram() { + const clearProgram = ` #pragma version 2 // This program clears program state. @@ -19,10 +19,10 @@ getClearProgram : function getClearProgram() { int 1 ` ; -return clearProgram; -}, + return clearProgram; + }, -getAlgoOrderBookApprovalProgram : function getAlgoOrderBookApprovalProgram() { + getAlgoOrderBookApprovalProgram: function getAlgoOrderBookApprovalProgram() { // stateful DEX contract // This is for the order book return ` @@ -259,9 +259,8 @@ getAlgoOrderBookApprovalProgram : function getAlgoOrderBookApprovalProgram() { int 1 return `; - - } -} + }, +}; module.exports = AlgoOrderbookTeal; diff --git a/lib/order/__tests__/generate_transaction_types.js b/lib/order/__tests__/generate_transaction_types.js index e0d42f05..a2fefbd7 100644 --- a/lib/order/__tests__/generate_transaction_types.js +++ b/lib/order/__tests__/generate_transaction_types.js @@ -1,10 +1,3 @@ -///////////////////////////// -// Alexander Trefonas // -// 7/12/2021 // -// Copyright Algodev Inc // -// All Rights Reserved. // -///////////////////////////// - const http = require('http'); const algosdk = require('algosdk'); @@ -14,611 +7,980 @@ const algosdk = require('algosdk'); const algoOrderBook = require('./dex_teal.js'); const asaOrderBook = require('./asa_dex_teal.js'); -//require('./dex_teal.js'); +// require('./dex_teal.js'); -const dexInternal = require('./algodex_internal_api.js'); +// const dexInternal = require('./algodex_internal_api.js'); const algodex = require('./algodex_api.js'); const constants = require('./constants.js'); const testHelper = require('./test_helper.js'); -let ALGO_ESCROW_ORDER_BOOK_ID = -1; -let ASA_ESCROW_ORDER_BOOK_ID = -1; +const ALGO_ESCROW_ORDER_BOOK_ID = -1; +const ASA_ESCROW_ORDER_BOOK_ID = -1; const GenerateTransactions = { - // helper function to compile program source - compileProgram: async function (client, programSource) { - let encoder = new TextEncoder(); - let programBytes = encoder.encode(programSource); - let compileResponse = await client.compile(programBytes).do(); - let compiledBytes = new Uint8Array(Buffer.from(compileResponse.result, "base64")); - return compiledBytes; - }, - - getAssetSendTxn : async function (client, fromAcct, toAcct, amount, assetId, shouldClose) { - if (typeof(fromAcct) !== "string") { - fromAcct = fromAcct.addr; - } - if (typeof(toAcct) !== "string") { - toAcct = toAcct.addr; - } - let params = await client.getTransactionParams().do(); - // comment out the next two lines to use suggested fee - params.fee = 1000; - params.flatFee = true; - let closeAddr = undefined; - if (shouldClose === true) { - closeAddr = toAcct; - } - - let txn = algosdk.makeAssetTransferTxnWithSuggestedParams(fromAcct, toAcct, closeAddr, undefined, - amount, undefined, assetId, params); - return txn; - }, - - getPayTxn : async function (client, fromAcct, toAcct, amount, shouldClose) { - if (typeof(fromAcct) !== "string") { - fromAcct = fromAcct.addr; - } - if (typeof(toAcct) !== "string") { - toAcct = toAcct.addr; - } - let params = await client.getTransactionParams().do(); - // comment out the next two lines to use suggested fee - params.fee = 1000; - params.flatFee = true; - const enc = new TextEncoder(); - let note = enc.encode("Hello World"); - let closeAddr = undefined; - if (shouldClose === true) { - closeAddr = toAcct; - } - let txn = algosdk.makePaymentTxnWithSuggestedParams(fromAcct, toAcct, amount, closeAddr, note, params); - return txn; - }, - - getCreateAppTxn : async function (client, creatorAccount, isAlgoEscrowApp = true) { - // define sender as creator - let approvalProgramSource = null; - if (isAlgoEscrowApp) { - approvalProgramSource = algoOrderBook.getAlgoOrderBookApprovalProgram(); - } else { - approvalProgramSource = asaOrderBook.getASAOrderBookApprovalProgram(); - } - const clearProgramSource = algoOrderBook.getClearProgram(); - - // declare application state storage (immutable) - const localInts = 2; - const localBytes = 1; - const globalInts = 0; - const globalBytes = 1; - - sender = creatorAccount.addr; - - // declare onComplete as NoOp - onComplete = algosdk.OnApplicationComplete.NoOpOC; - - // get node suggested parameters - let params = await client.getTransactionParams().do(); - // create unsigned transaction - - let approvalProgram = await this.compileProgram(client, approvalProgramSource); - let clearProgram = await this.compileProgram(client, clearProgramSource); - - let txn = algosdk.makeApplicationCreateTxn(sender, params, onComplete, - approvalProgram, clearProgram, - localInts, localBytes, globalInts, globalBytes,); - - return txn; - }, - - getCloseAlgoEscrowOrderTxns : async function (algodClient, creator, price, assetId, appId) { - let numAndDenom = algodex.getNumeratorAndDenominatorFromPrice(price); - let n = numAndDenom.n; - let d = numAndDenom.d; - let creatorAddr = creator.addr; - - let escrowSource = algodex.buildDelegateTemplateFromArgs(0, assetId, n, d, creatorAddr, false, constants.ESCROW_CONTRACT_VERSION); - let lsig = await algodex.getLsigFromProgramSource(algosdk, algodClient, escrowSource, constants.DEBUG_SMART_CONTRACT_SOURCE); - let escrowAccountAddr = lsig.address(); - - let outerTxns = []; - // "2500-625-0-15322902" - let orderBookEntry = n + "-" + d + "-0-" + assetId; - console.log("closing order from order book entry!"); - console.log("escrowAccountAddr, creatorAddr, orderBookEntry", - escrowAccountAddr, creatorAddr, orderBookEntry); - - - let appArgs = []; - let enc = new TextEncoder(); - appArgs.push(enc.encode("close")); - appArgs.push(enc.encode(orderBookEntry)); - //appArgs.push(enc.encode(creatorAddr)); - console.log("args length: " + appArgs.length); - - // get node suggested parameters - let params = await algodClient.getTransactionParams().do(); - - // create unsigned transaction - let txn = algosdk.makeApplicationClearStateTxn(lsig.address(), params, appId, appArgs); - outerTxns.push({ - unsignedTxn: txn, - lsig: lsig - }); - // Submit the transaction - - // Make payment tx signed with lsig - let txn2 = algosdk.makePaymentTxnWithSuggestedParams(lsig.address(), creatorAddr, 0, creatorAddr, undefined, params); - outerTxns.push({ - unsignedTxn: txn2, - lsig: lsig - }); - - let txn3 = algosdk.makePaymentTxnWithSuggestedParams(creatorAddr, creatorAddr, 0, undefined, undefined, params); - - outerTxns.push({ - unsignedTxn: txn3, - senderAcct: creator - }); - - return outerTxns; - }, - - getCloseASAEscrowOrderTxns : async function (algodClient, creator, price, assetId, appId) { - let numAndDenom = algodex.getNumeratorAndDenominatorFromPrice(price); - let n = numAndDenom.n; - let d = numAndDenom.d; - let creatorAddr = creator.addr; - - let escrowSource = algodex.buildDelegateTemplateFromArgs(0, assetId, n, d, creatorAddr, true, constants.ESCROW_CONTRACT_VERSION); - let lsig = await algodex.getLsigFromProgramSource(algosdk, algodClient, escrowSource, constants.DEBUG_SMART_CONTRACT_SOURCE); - let escrowAccountAddr = lsig.address(); - - let outerTxns = []; - // "2500-625-0-15322902" - let orderBookEntry = n + "-" + d + "-0-" + assetId; - console.log("closing order from order book entry!"); - console.log("escrowAccountAddr, creatorAddr, orderBookEntry", - escrowAccountAddr, creatorAddr, orderBookEntry); - - let appArgs = []; - let enc = new TextEncoder(); - appArgs.push(enc.encode("close")); - appArgs.push(enc.encode(orderBookEntry)); - //appArgs.push(enc.encode(creatorAddr)); - console.log("args length: " + appArgs.length); - - // get node suggested parameters - let params = await algodClient.getTransactionParams().do(); - - // create unsigned transaction - let txn = algosdk.makeApplicationClearStateTxn(lsig.address(), params, appId, appArgs) - let txId = txn.txID().toString(); - // Submit the transaction - - // create optin transaction - // sender and receiver are both the same - let sender = lsig.address(); - let recipient = creatorAddr; - // We set revocationTarget to undefined as - // This is not a clawback operation - let revocationTarget = undefined; - // CloseReaminerTo is set to undefined as - // we are not closing out an asset - let closeRemainderTo = creatorAddr; - // We are sending 0 assets - let amount = 0; - - // signing and sending "txn" allows sender to begin accepting asset specified by creator and index - let txn2 = algosdk.makeAssetTransferTxnWithSuggestedParams(sender, recipient, closeRemainderTo, revocationTarget, - amount, undefined, assetId, params); - - // Make payment tx signed with lsig - let txn3 = algosdk.makePaymentTxnWithSuggestedParams(lsig.address(), creatorAddr, 0, creatorAddr, - undefined, params); - - // proof of ownership transaction - let txn4 = algosdk.makePaymentTxnWithSuggestedParams(creatorAddr, creatorAddr, 0, undefined, undefined, params); - - outerTxns.push({ - unsignedTxn: txn, - lsig: lsig - }); - outerTxns.push({ - unsignedTxn: txn2, - lsig: lsig - }); - outerTxns.push({ - unsignedTxn: txn3, - lsig: lsig - }); - outerTxns.push({ - unsignedTxn: txn4, - senderAcct: creator - }); - - return outerTxns; - }, - - getExecuteAlgoEscrowOrderTxns : async function (algodClient, executorAccount, makerAccount, algoAmountReceiving, asaAmountSending, - price, assetId, appId, shouldClose = false) { - - const orderCreatorAddr = makerAccount.addr; - const min = 0; - const numAndDenom = algodex.getNumeratorAndDenominatorFromPrice(price); - const n = numAndDenom.n; - const d = numAndDenom.d; - const takerAddr = executorAccount.addr; - - let appCallType = null; - const orderBookEntry = algodex.generateOrder(orderCreatorAddr, n, d, min, assetId, false); - const refundFees = 0.002 * 1000000; // fees refunded to escrow in case of partial execution - - const escrowSource = algodex.buildDelegateTemplateFromArgs(0, assetId, n, d, orderCreatorAddr, false, constants.ESCROW_CONTRACT_VERSION); - const lsig = await algodex.getLsigFromProgramSource(algosdk, algodClient, escrowSource, constants.DEBUG_SMART_CONTRACT_SOURCE); - const params = await algodClient.getTransactionParams().do(); - - const appAccts = []; - appAccts.push(orderCreatorAddr); - appAccts.push(takerAddr); - - let closeRemainderTo = undefined; - - if (shouldClose) { - closeRemainderTo = makerAccount.addr; - } - - if (closeRemainderTo == undefined) { - appCallType = "execute"; - } else { - appCallType = "execute_with_closeout"; - } - console.log("arg1: " + appCallType); - console.log("arg2: " + orderBookEntry); - console.log("arg3: " + orderCreatorAddr); - - let appArgs = []; - let enc = new TextEncoder(); - appArgs.push(enc.encode(appCallType)); - appArgs.push(enc.encode(orderBookEntry)); - console.log(appArgs.length); - - let transaction1 = null; - - if (closeRemainderTo == undefined) { - transaction1 = algosdk.makeApplicationNoOpTxn(lsig.address(), params, appId, appArgs, appAccts); - } else { - transaction1 = algosdk.makeApplicationCloseOutTxn(lsig.address(), params, appId, appArgs, appAccts); - } - - - // Make payment tx signed with lsig - let transaction2 = algosdk.makePaymentTxnWithSuggestedParams(lsig.address(), takerAddr, algoAmountReceiving, closeRemainderTo, undefined, params); - // Make asset xfer - - let transaction3 = await this.getAssetSendTxn(algodClient, takerAddr, orderCreatorAddr, asaAmountSending, assetId, false); - - let transaction4 = null; - - if (closeRemainderTo == undefined) { - // create refund transaction for fees - transaction4 = await this.getPayTxn(algodClient, takerAddr, lsig.address(), refundFees, false); - } - - let retTxns = []; - - retTxns.push({ - 'unsignedTxn': transaction1, - 'lsig': lsig - }); - retTxns.push({ - 'unsignedTxn': transaction2, - 'lsig': lsig - }); - retTxns.push({ - 'unsignedTxn': transaction3, - 'senderAcct': executorAccount - }); - - if (transaction4 != null) { - retTxns.push({ - 'unsignedTxn': transaction4, - 'senderAcct': executorAccount - }); - } - - return retTxns; - - - }, - - getExecuteASAEscrowOrderTxns : async function (algodClient, executorAccount, makerAccount, algoAmountSending, asaAmountReceiving, price, assetId, appId, shouldClose = false) { - console.log("here664 ", executorAccount, makerAccount, algoAmountSending, asaAmountReceiving, price, assetId, appId, shouldClose); - const orderCreatorAddr = makerAccount.addr; - const min = 0; - const numAndDenom = algodex.getNumeratorAndDenominatorFromPrice(price); - const n = numAndDenom.n; - const d = numAndDenom.d; - const takerAddr = executorAccount.addr; - - const refundFees = 0.002 * 1000000; // fees refunded to escrow in case of partial execution - - let appCallType = null; - const orderBookEntry = algodex.generateOrder(orderCreatorAddr, n, d, min, assetId, false); - - const escrowSource = algodex.buildDelegateTemplateFromArgs(0, assetId, n, d, orderCreatorAddr, true, constants.ESCROW_CONTRACT_VERSION); - const lsig = await algodex.getLsigFromProgramSource(algosdk, algodClient, escrowSource, constants.DEBUG_SMART_CONTRACT_SOURCE); - const params = await algodClient.getTransactionParams().do(); - - const appAccts = []; - appAccts.push(orderCreatorAddr); - appAccts.push(takerAddr); - - - let transaction1 = null; - let closeRemainderTo = undefined; - - if (shouldClose) { - closeRemainderTo = makerAccount.addr; - appCallType = "execute_with_closeout"; - } else { - appCallType = "execute"; - } - - let appArgs = []; - let enc = new TextEncoder(); - appArgs.push(enc.encode(appCallType)); - appArgs.push(enc.encode(orderBookEntry)); - - if (closeRemainderTo == undefined) { - transaction1 = algosdk.makeApplicationNoOpTxn(lsig.address(), params, appId, appArgs, appAccts, [0], [assetId]); - } else { - transaction1 = algosdk.makeApplicationCloseOutTxn(lsig.address(), params, appId, appArgs, appAccts, [0], [assetId]); - } - - console.log("app call type is: " + appCallType); - - let transaction2 = await this.getPayTxn(algodClient, takerAddr, orderCreatorAddr, algoAmountSending, false); - - let accountInfo = await algodex.getAccountInfo(takerAddr); - let takerAlreadyOptedIntoASA = false; - if (accountInfo != null && accountInfo['assets'] != null - && accountInfo['assets'].length > 0) { - for (let i = 0; i < accountInfo['assets'].length; i++) { - if (accountInfo['assets'][i]['asset-id'] === assetId) { - takerAlreadyOptedIntoASA = true; - break; - } - } - } - - // asset opt-in transfer - let transaction2b = null; - - if (!takerAlreadyOptedIntoASA) { - transaction2b = await this.getAssetSendTxn(algodClient, takerAddr, takerAddr, 0, assetId, false); - } - - // Make asset xfer - - // Asset transfer from escrow account to order executor - - let transaction3 = algosdk.makeAssetTransferTxnWithSuggestedParams(lsig.address(), takerAddr, closeRemainderTo, undefined, - asaAmountReceiving, undefined, assetId, params); - - let transaction4 = null; - if (closeRemainderTo != undefined) { - // Make payment tx signed with lsig back to owner creator - console.log("making transaction4 due to closeRemainderTo"); - transaction4 = algosdk.makePaymentTxnWithSuggestedParams(lsig.address(), orderCreatorAddr, 0, orderCreatorAddr, - undefined, params); - } else { - // Make fee refund transaction - transaction4 = await this.getPayTxn(algodClient, takerAddr, lsig.address(), refundFees, false); - } - - if (transaction2b != null) { - // myAlgoWalletUtil.setTransactionFee(transaction2b); - } - - let retTxns = []; - - retTxns.push({ - 'unsignedTxn': transaction1, - 'lsig': lsig - }); - retTxns.push({ - 'unsignedTxn': transaction2, // FIXME - change to sdk - 'senderAcct': executorAccount - }); - - if (transaction2b != null) { - retTxns.push({ - 'unsignedTxn': transaction2b, // FIXME - change to sdk - 'senderAcct': executorAccount - }); - } - retTxns.push({ - 'unsignedTxn': transaction3, - 'lsig': lsig - }); - if (closeRemainderTo != undefined) { - // close out algo balance to owner - retTxns.push({ - 'unsignedTxn': transaction4, - 'lsig': lsig - }); - } else { - // fee refund - retTxns.push({ - 'unsignedTxn': transaction4, - 'senderAcct': executorAccount - }); - } - - return retTxns; - }, - - getPlaceAlgoEscrowOrderTxns : async function (algodClient, makerAccount, algoOrderSize, price, assetId, appId, isExistingEscrow = false, - skipASAOptIn = false) { - const makerAddr = makerAccount.addr; - const min = 0; - const numAndDenom = algodex.getNumeratorAndDenominatorFromPrice(price); - const n = numAndDenom.n; - const d = numAndDenom.d; - console.log("getPlaceAlgoEscrowOrderTxns makerWalletAddr, n, d, min, assetId", - makerAddr, n, d, min, assetId); - let program = algodex.buildDelegateTemplateFromArgs(min, assetId, n, d, makerAddr, false, constants.ESCROW_CONTRACT_VERSION); - let lsig = await algodex.getLsigFromProgramSource(algosdk, algodClient, program, constants.DEBUG_SMART_CONTRACT_SOURCE); - let generatedOrderEntry = algodex.generateOrder(makerAddr, n, d, min, assetId); - console.log("sending trans to: " + lsig.address()); - - let txn = await this.getPayTxn(algodClient, makerAddr, lsig.address(), algoOrderSize, false); - let outerTxns = []; - - outerTxns.push({ - unsignedTxn: txn, - senderAcct: makerAccount - }); - - console.log("here3 calling app from logic sig to open order"); - let appArgs = []; - var enc = new TextEncoder(); - appArgs.push(enc.encode("open")); - appArgs.push(enc.encode(generatedOrderEntry.slice(59))); - appArgs.push(new Uint8Array([constants.ESCROW_CONTRACT_VERSION])); - - //appArgs.push(algosdk.decodeAddress(makerAddr).publicKey); - - //console.log("owners bit addr: " + ownersBitAddr); - console.log("herezzz_888"); - console.log(appArgs.length); - let logSigTrans = null; - - if (!isExistingEscrow) { - // logSigTrans = await dexInternal.createTransactionFromLogicSig(algodClient, lsig, appId, appArgs, "appOptIn"); - // outerTxns.push({ - // unsignedTxn: logSigTrans, - // lsig: lsig - // }); - } - - console.log("skipASAOptIn: " + skipASAOptIn); - - if (!skipASAOptIn) { - // asset opt-in transfer - let assetOptInTxn = await this.getAssetSendTxn(algodClient, makerAddr, makerAddr, 0, assetId, false); - - outerTxns.push({ - unsignedTxn: assetOptInTxn, - senderAcct: makerAccount - }); - } - return outerTxns; - }, - - getPlaceASAEscrowOrderTxns : async function (algodClient, makerAccount, asaOrderSize, price, assetId, appId, isExistingEscrow = false) { - console.log("checking assetId type"); - assetId = parseInt(assetId+""); - - const makerAddr = makerAccount.addr; - const min = 0; - const numAndDenom = algodex.getNumeratorAndDenominatorFromPrice(price); - const n = numAndDenom.n; - const d = numAndDenom.d; - - let outerTxns = []; - - let program = algodex.buildDelegateTemplateFromArgs(min, assetId, n, d, makerAddr, true, constants.ESCROW_CONTRACT_VERSION); - - let lsig = await algodex.getLsigFromProgramSource(algosdk, algodClient, program); - let generatedOrderEntry = algodex.generateOrder(makerAddr, n, d, min, assetId); - console.log("address is: " + lsig.address()); - - // check if the lsig has already opted in - let accountInfo = await algodex.getAccountInfo(lsig.address()); - let alreadyOptedIn = false; - if (accountInfo != null && accountInfo['apps-local-state'] != null - && accountInfo['apps-local-state'].length > 0 - && accountInfo['apps-local-state'][0].id == appId) { - alreadyOptedIn = true; + // helper function to compile program source + compileProgram: async function (client, programSource) { + const encoder = new TextEncoder(); + const programBytes = encoder.encode(programSource); + const compileResponse = await client.compile(programBytes).do(); + const compiledBytes = new Uint8Array( + Buffer.from(compileResponse.result, 'base64') + ); + return compiledBytes; + }, + + getAssetSendTxn: async function ( + client, + fromAcct, + toAcct, + amount, + assetId, + shouldClose + ) { + if (typeof fromAcct !== 'string') { + fromAcct = fromAcct.addr; + } + if (typeof toAcct !== 'string') { + toAcct = toAcct.addr; + } + const params = await client.getTransactionParams().do(); + // comment out the next two lines to use suggested fee + params.fee = 1000; + params.flatFee = true; + let closeAddr = undefined; + if (shouldClose === true) { + closeAddr = toAcct; + } + + const txn = algosdk.makeAssetTransferTxnWithSuggestedParams( + fromAcct, + toAcct, + closeAddr, + undefined, + amount, + undefined, + assetId, + params + ); + return txn; + }, + + getPayTxn: async function (client, fromAcct, toAcct, amount, shouldClose) { + if (typeof fromAcct !== 'string') { + fromAcct = fromAcct.addr; + } + if (typeof toAcct !== 'string') { + toAcct = toAcct.addr; + } + const params = await client.getTransactionParams().do(); + // comment out the next two lines to use suggested fee + params.fee = 1000; + params.flatFee = true; + const enc = new TextEncoder(); + const note = enc.encode('Hello World'); + let closeAddr = undefined; + if (shouldClose === true) { + closeAddr = toAcct; + } + const txn = algosdk.makePaymentTxnWithSuggestedParams( + fromAcct, + toAcct, + amount, + closeAddr, + note, + params + ); + return txn; + }, + + getCreateAppTxn: async function ( + client, + creatorAccount, + isAlgoEscrowApp = true + ) { + // define sender as creator + let approvalProgramSource = null; + if (isAlgoEscrowApp) { + approvalProgramSource = algoOrderBook.getAlgoOrderBookApprovalProgram(); + } else { + approvalProgramSource = asaOrderBook.getASAOrderBookApprovalProgram(); + } + const clearProgramSource = algoOrderBook.getClearProgram(); + + // declare application state storage (immutable) + const localInts = 2; + const localBytes = 1; + const globalInts = 0; + const globalBytes = 1; + + sender = creatorAccount.addr; + + // declare onComplete as NoOp + onComplete = algosdk.OnApplicationComplete.NoOpOC; + + // get node suggested parameters + const params = await client.getTransactionParams().do(); + // create unsigned transaction + + const approvalProgram = await this.compileProgram( + client, + approvalProgramSource + ); + const clearProgram = await this.compileProgram(client, clearProgramSource); + + const txn = algosdk.makeApplicationCreateTxn( + sender, + params, + onComplete, + approvalProgram, + clearProgram, + localInts, + localBytes, + globalInts, + globalBytes + ); + + return txn; + }, + + getCloseAlgoEscrowOrderTxns: async function ( + algodClient, + creator, + price, + assetId, + appId + ) { + const numAndDenom = algodex.getNumeratorAndDenominatorFromPrice(price); + const n = numAndDenom.n; + const d = numAndDenom.d; + const creatorAddr = creator.addr; + + const escrowSource = algodex.buildDelegateTemplateFromArgs( + 0, + assetId, + n, + d, + creatorAddr, + false, + constants.ESCROW_CONTRACT_VERSION + ); + const lsig = await algodex.getLsigFromProgramSource( + algosdk, + algodClient, + escrowSource, + constants.DEBUG_SMART_CONTRACT_SOURCE + ); + const escrowAccountAddr = lsig.address(); + + const outerTxns = []; + // "2500-625-0-15322902" + const orderBookEntry = n + '-' + d + '-0-' + assetId; + console.log('closing order from order book entry!'); + console.log( + 'escrowAccountAddr, creatorAddr, orderBookEntry', + escrowAccountAddr, + creatorAddr, + orderBookEntry + ); + + const appArgs = []; + const enc = new TextEncoder(); + appArgs.push(enc.encode('close')); + appArgs.push(enc.encode(orderBookEntry)); + // appArgs.push(enc.encode(creatorAddr)); + console.log('args length: ' + appArgs.length); + + // get node suggested parameters + const params = await algodClient.getTransactionParams().do(); + + // create unsigned transaction + const txn = algosdk.makeApplicationClearStateTxn( + lsig.address(), + params, + appId, + appArgs + ); + outerTxns.push({ + unsignedTxn: txn, + lsig: lsig, + }); + // Submit the transaction + + // Make payment tx signed with lsig + const txn2 = algosdk.makePaymentTxnWithSuggestedParams( + lsig.address(), + creatorAddr, + 0, + creatorAddr, + undefined, + params + ); + outerTxns.push({ + unsignedTxn: txn2, + lsig: lsig, + }); + + const txn3 = algosdk.makePaymentTxnWithSuggestedParams( + creatorAddr, + creatorAddr, + 0, + undefined, + undefined, + params + ); + + outerTxns.push({ + unsignedTxn: txn3, + senderAcct: creator, + }); + + return outerTxns; + }, + + getCloseASAEscrowOrderTxns: async function ( + algodClient, + creator, + price, + assetId, + appId + ) { + const numAndDenom = algodex.getNumeratorAndDenominatorFromPrice(price); + const n = numAndDenom.n; + const d = numAndDenom.d; + const creatorAddr = creator.addr; + + const escrowSource = algodex.buildDelegateTemplateFromArgs( + 0, + assetId, + n, + d, + creatorAddr, + true, + constants.ESCROW_CONTRACT_VERSION + ); + const lsig = await algodex.getLsigFromProgramSource( + algosdk, + algodClient, + escrowSource, + constants.DEBUG_SMART_CONTRACT_SOURCE + ); + const escrowAccountAddr = lsig.address(); + + const outerTxns = []; + // "2500-625-0-15322902" + const orderBookEntry = n + '-' + d + '-0-' + assetId; + console.log('closing order from order book entry!'); + console.log( + 'escrowAccountAddr, creatorAddr, orderBookEntry', + escrowAccountAddr, + creatorAddr, + orderBookEntry + ); + + const appArgs = []; + const enc = new TextEncoder(); + appArgs.push(enc.encode('close')); + appArgs.push(enc.encode(orderBookEntry)); + // appArgs.push(enc.encode(creatorAddr)); + console.log('args length: ' + appArgs.length); + + // get node suggested parameters + const params = await algodClient.getTransactionParams().do(); + + // create unsigned transaction + const txn = algosdk.makeApplicationClearStateTxn( + lsig.address(), + params, + appId, + appArgs + ); + const txId = txn.txID().toString(); + // Submit the transaction + + // create optin transaction + // sender and receiver are both the same + const sender = lsig.address(); + const recipient = creatorAddr; + // We set revocationTarget to undefined as + // This is not a clawback operation + const revocationTarget = undefined; + // CloseReaminerTo is set to undefined as + // we are not closing out an asset + const closeRemainderTo = creatorAddr; + // We are sending 0 assets + const amount = 0; + + // signing and sending "txn" allows sender to begin accepting asset specified by creator and index + const txn2 = algosdk.makeAssetTransferTxnWithSuggestedParams( + sender, + recipient, + closeRemainderTo, + revocationTarget, + amount, + undefined, + assetId, + params + ); + + // Make payment tx signed with lsig + const txn3 = algosdk.makePaymentTxnWithSuggestedParams( + lsig.address(), + creatorAddr, + 0, + creatorAddr, + undefined, + params + ); + + // proof of ownership transaction + const txn4 = algosdk.makePaymentTxnWithSuggestedParams( + creatorAddr, + creatorAddr, + 0, + undefined, + undefined, + params + ); + + outerTxns.push({ + unsignedTxn: txn, + lsig: lsig, + }); + outerTxns.push({ + unsignedTxn: txn2, + lsig: lsig, + }); + outerTxns.push({ + unsignedTxn: txn3, + lsig: lsig, + }); + outerTxns.push({ + unsignedTxn: txn4, + senderAcct: creator, + }); + + return outerTxns; + }, + + getExecuteAlgoEscrowOrderTxns: async function ( + algodClient, + executorAccount, + makerAccount, + algoAmountReceiving, + asaAmountSending, + price, + assetId, + appId, + shouldClose = false + ) { + const orderCreatorAddr = makerAccount.addr; + const min = 0; + const numAndDenom = algodex.getNumeratorAndDenominatorFromPrice(price); + const n = numAndDenom.n; + const d = numAndDenom.d; + const takerAddr = executorAccount.addr; + + let appCallType = null; + const orderBookEntry = algodex.generateOrder( + orderCreatorAddr, + n, + d, + min, + assetId, + false + ); + const refundFees = 0.002 * 1000000; // fees refunded to escrow in case of partial execution + + const escrowSource = algodex.buildDelegateTemplateFromArgs( + 0, + assetId, + n, + d, + orderCreatorAddr, + false, + constants.ESCROW_CONTRACT_VERSION + ); + const lsig = await algodex.getLsigFromProgramSource( + algosdk, + algodClient, + escrowSource, + constants.DEBUG_SMART_CONTRACT_SOURCE + ); + const params = await algodClient.getTransactionParams().do(); + + const appAccts = []; + appAccts.push(orderCreatorAddr); + appAccts.push(takerAddr); + + let closeRemainderTo = undefined; + + if (shouldClose) { + closeRemainderTo = makerAccount.addr; + } + + if (closeRemainderTo == undefined) { + appCallType = 'execute'; + } else { + appCallType = 'execute_with_closeout'; + } + console.log('arg1: ' + appCallType); + console.log('arg2: ' + orderBookEntry); + console.log('arg3: ' + orderCreatorAddr); + + const appArgs = []; + const enc = new TextEncoder(); + appArgs.push(enc.encode(appCallType)); + appArgs.push(enc.encode(orderBookEntry)); + console.log(appArgs.length); + + let transaction1 = null; + + if (closeRemainderTo == undefined) { + transaction1 = algosdk.makeApplicationNoOpTxn( + lsig.address(), + params, + appId, + appArgs, + appAccts + ); + } else { + transaction1 = algosdk.makeApplicationCloseOutTxn( + lsig.address(), + params, + appId, + appArgs, + appAccts + ); + } + + // Make payment tx signed with lsig + const transaction2 = algosdk.makePaymentTxnWithSuggestedParams( + lsig.address(), + takerAddr, + algoAmountReceiving, + closeRemainderTo, + undefined, + params + ); + // Make asset xfer + + const transaction3 = await this.getAssetSendTxn( + algodClient, + takerAddr, + orderCreatorAddr, + asaAmountSending, + assetId, + false + ); + + let transaction4 = null; + + if (closeRemainderTo == undefined) { + // create refund transaction for fees + transaction4 = await this.getPayTxn( + algodClient, + takerAddr, + lsig.address(), + refundFees, + false + ); + } + + const retTxns = []; + + retTxns.push({ + unsignedTxn: transaction1, + lsig: lsig, + }); + retTxns.push({ + unsignedTxn: transaction2, + lsig: lsig, + }); + retTxns.push({ + unsignedTxn: transaction3, + senderAcct: executorAccount, + }); + + if (transaction4 != null) { + retTxns.push({ + unsignedTxn: transaction4, + senderAcct: executorAccount, + }); + } + + return retTxns; + }, + + getExecuteASAEscrowOrderTxns: async function ( + algodClient, + executorAccount, + makerAccount, + algoAmountSending, + asaAmountReceiving, + price, + assetId, + appId, + shouldClose = false + ) { + console.log( + 'here664 ', + executorAccount, + makerAccount, + algoAmountSending, + asaAmountReceiving, + price, + assetId, + appId, + shouldClose + ); + const orderCreatorAddr = makerAccount.addr; + const min = 0; + const numAndDenom = algodex.getNumeratorAndDenominatorFromPrice(price); + const n = numAndDenom.n; + const d = numAndDenom.d; + const takerAddr = executorAccount.addr; + + const refundFees = 0.002 * 1000000; // fees refunded to escrow in case of partial execution + + let appCallType = null; + const orderBookEntry = algodex.generateOrder( + orderCreatorAddr, + n, + d, + min, + assetId, + false + ); + + const escrowSource = algodex.buildDelegateTemplateFromArgs( + 0, + assetId, + n, + d, + orderCreatorAddr, + true, + constants.ESCROW_CONTRACT_VERSION + ); + const lsig = await algodex.getLsigFromProgramSource( + algosdk, + algodClient, + escrowSource, + constants.DEBUG_SMART_CONTRACT_SOURCE + ); + const params = await algodClient.getTransactionParams().do(); + + const appAccts = []; + appAccts.push(orderCreatorAddr); + appAccts.push(takerAddr); + + let transaction1 = null; + let closeRemainderTo = undefined; + + if (shouldClose) { + closeRemainderTo = makerAccount.addr; + appCallType = 'execute_with_closeout'; + } else { + appCallType = 'execute'; + } + + const appArgs = []; + const enc = new TextEncoder(); + appArgs.push(enc.encode(appCallType)); + appArgs.push(enc.encode(orderBookEntry)); + + if (closeRemainderTo == undefined) { + transaction1 = algosdk.makeApplicationNoOpTxn( + lsig.address(), + params, + appId, + appArgs, + appAccts, + [0], + [assetId] + ); + } else { + transaction1 = algosdk.makeApplicationCloseOutTxn( + lsig.address(), + params, + appId, + appArgs, + appAccts, + [0], + [assetId] + ); + } + + console.log('app call type is: ' + appCallType); + + const transaction2 = await this.getPayTxn( + algodClient, + takerAddr, + orderCreatorAddr, + algoAmountSending, + false + ); + + const accountInfo = await algodex.getAccountInfo(takerAddr); + let takerAlreadyOptedIntoASA = false; + if ( + accountInfo != null && + accountInfo['assets'] != null && + accountInfo['assets'].length > 0 + ) { + for (let i = 0; i < accountInfo['assets'].length; i++) { + if (accountInfo['assets'][i]['asset-id'] === assetId) { + takerAlreadyOptedIntoASA = true; + break; } - console.log("alreadyOptedIn: " + alreadyOptedIn); - console.log("acct info:" + JSON.stringify(accountInfo)); - - let params = await algodClient.getTransactionParams().do(); - console.log("sending trans to: " + lsig.address()); - - - let assetSendTrans = await this.getAssetSendTxn(algodClient, makerAddr, lsig.address(), asaOrderSize, assetId, - false); - - let payTxn = await this.getPayTxn(algodClient, makerAddr, lsig.address(), constants.MIN_ASA_ESCROW_BALANCE, - false); - - // myAlgoWalletUtil.setTransactionFee(payTxn); - - console.log("typeof: " + typeof payTxn.txId); - console.log("the val: " + payTxn.txId); - - //console.log("confirmed!!"); - // create unsigned transaction - - console.log("here3 calling app from logic sig to open order"); - let appArgs = []; - var enc = new TextEncoder(); - appArgs.push(enc.encode("open")); - - appArgs.push(enc.encode(generatedOrderEntry.slice(59))); - appArgs.push(new Uint8Array([constants.ESCROW_CONTRACT_VERSION])); - - // add owners address as arg - //ownersAddr = "WYWRYK42XADLY3O62N52BOLT27DMPRA3WNBT2OBRT65N6OEZQWD4OSH6PI"; - //ownersBitAddr = (algosdk.decodeAddress(ownersAddr)).publicKey; - console.log(appArgs.length); - - // let logSigTrans = await dexInternal.createTransactionFromLogicSig(algodClient, lsig, appId, - // appArgs, "appOptIn"); - - // create optin transaction - // sender and receiver are both the same - let sender = lsig.address(); - let recipient = sender; - // We set revocationTarget to undefined as - // This is not a clawback operation - let revocationTarget = undefined; - // CloseReaminerTo is set to undefined as - // we are not closing out an asset - let closeRemainderTo = undefined; - // We are sending 0 assets - let amount = 0; - - // signing and sending "txn" allows sender to begin accepting asset specified by creator and index - let logSigAssetOptInTrans = algosdk.makeAssetTransferTxnWithSuggestedParams(sender, recipient, closeRemainderTo, - revocationTarget, - amount, undefined, assetId, params); - - outerTxns.push({ - unsignedTxn: payTxn, - senderAcct: makerAccount - }); - outerTxns.push({ - unsignedTxn: logSigTrans, - lsig: lsig - }); - outerTxns.push({ - unsignedTxn: logSigAssetOptInTrans, - lsig: lsig - }); - outerTxns.push({ - unsignedTxn: assetSendTrans, - senderAcct: makerAccount - }); - - return outerTxns; - }, - -} - -module.exports = GenerateTransactions; \ No newline at end of file + } + } + + // asset opt-in transfer + let transaction2b = null; + + if (!takerAlreadyOptedIntoASA) { + transaction2b = await this.getAssetSendTxn( + algodClient, + takerAddr, + takerAddr, + 0, + assetId, + false + ); + } + + // Make asset xfer + + // Asset transfer from escrow account to order executor + + const transaction3 = algosdk.makeAssetTransferTxnWithSuggestedParams( + lsig.address(), + takerAddr, + closeRemainderTo, + undefined, + asaAmountReceiving, + undefined, + assetId, + params + ); + + let transaction4 = null; + if (closeRemainderTo != undefined) { + // Make payment tx signed with lsig back to owner creator + console.log('making transaction4 due to closeRemainderTo'); + transaction4 = algosdk.makePaymentTxnWithSuggestedParams( + lsig.address(), + orderCreatorAddr, + 0, + orderCreatorAddr, + undefined, + params + ); + } else { + // Make fee refund transaction + transaction4 = await this.getPayTxn( + algodClient, + takerAddr, + lsig.address(), + refundFees, + false + ); + } + + if (transaction2b != null) { + // myAlgoWalletUtil.setTransactionFee(transaction2b); + } + + const retTxns = []; + + retTxns.push({ + unsignedTxn: transaction1, + lsig: lsig, + }); + retTxns.push({ + unsignedTxn: transaction2, // FIXME - change to sdk + senderAcct: executorAccount, + }); + + if (transaction2b != null) { + retTxns.push({ + unsignedTxn: transaction2b, // FIXME - change to sdk + senderAcct: executorAccount, + }); + } + retTxns.push({ + unsignedTxn: transaction3, + lsig: lsig, + }); + if (closeRemainderTo != undefined) { + // close out algo balance to owner + retTxns.push({ + unsignedTxn: transaction4, + lsig: lsig, + }); + } else { + // fee refund + retTxns.push({ + unsignedTxn: transaction4, + senderAcct: executorAccount, + }); + } + + return retTxns; + }, + + getPlaceAlgoEscrowOrderTxns: async function ( + algodClient, + makerAccount, + algoOrderSize, + price, + assetId, + appId, + isExistingEscrow = false, + skipASAOptIn = false + ) { + const makerAddr = makerAccount.addr; + const min = 0; + const numAndDenom = algodex.getNumeratorAndDenominatorFromPrice(price); + const n = numAndDenom.n; + const d = numAndDenom.d; + console.log( + 'getPlaceAlgoEscrowOrderTxns makerWalletAddr, n, d, min, assetId', + makerAddr, + n, + d, + min, + assetId + ); + const program = algodex.buildDelegateTemplateFromArgs( + min, + assetId, + n, + d, + makerAddr, + false, + constants.ESCROW_CONTRACT_VERSION + ); + const lsig = await algodex.getLsigFromProgramSource( + algosdk, + algodClient, + program, + constants.DEBUG_SMART_CONTRACT_SOURCE + ); + const generatedOrderEntry = algodex.generateOrder( + makerAddr, + n, + d, + min, + assetId + ); + console.log('sending trans to: ' + lsig.address()); + + const txn = await this.getPayTxn( + algodClient, + makerAddr, + lsig.address(), + algoOrderSize, + false + ); + const outerTxns = []; + + outerTxns.push({ + unsignedTxn: txn, + senderAcct: makerAccount, + }); + + console.log('here3 calling app from logic sig to open order'); + const appArgs = []; + const enc = new TextEncoder(); + appArgs.push(enc.encode('open')); + appArgs.push(enc.encode(generatedOrderEntry.slice(59))); + appArgs.push(new Uint8Array([constants.ESCROW_CONTRACT_VERSION])); + + // appArgs.push(algosdk.decodeAddress(makerAddr).publicKey); + + // console.log("owners bit addr: " + ownersBitAddr); + console.log('herezzz_888'); + console.log(appArgs.length); + const logSigTrans = null; + + if (!isExistingEscrow) { + // logSigTrans = await dexInternal.createTransactionFromLogicSig(algodClient, lsig, appId, appArgs, "appOptIn"); + // outerTxns.push({ + // unsignedTxn: logSigTrans, + // lsig: lsig + // }); + } + + console.log('skipASAOptIn: ' + skipASAOptIn); + + if (!skipASAOptIn) { + // asset opt-in transfer + const assetOptInTxn = await this.getAssetSendTxn( + algodClient, + makerAddr, + makerAddr, + 0, + assetId, + false + ); + + outerTxns.push({ + unsignedTxn: assetOptInTxn, + senderAcct: makerAccount, + }); + } + return outerTxns; + }, + + getPlaceASAEscrowOrderTxns: async function ( + algodClient, + makerAccount, + asaOrderSize, + price, + assetId, + appId, + isExistingEscrow = false + ) { + console.log('checking assetId type'); + assetId = parseInt(assetId + ''); + + const makerAddr = makerAccount.addr; + const min = 0; + const numAndDenom = algodex.getNumeratorAndDenominatorFromPrice(price); + const n = numAndDenom.n; + const d = numAndDenom.d; + + const outerTxns = []; + + const program = algodex.buildDelegateTemplateFromArgs( + min, + assetId, + n, + d, + makerAddr, + true, + constants.ESCROW_CONTRACT_VERSION + ); + + const lsig = await algodex.getLsigFromProgramSource( + algosdk, + algodClient, + program + ); + const generatedOrderEntry = algodex.generateOrder( + makerAddr, + n, + d, + min, + assetId + ); + console.log('address is: ' + lsig.address()); + + // check if the lsig has already opted in + const accountInfo = await algodex.getAccountInfo(lsig.address()); + let alreadyOptedIn = false; + if ( + accountInfo != null && + accountInfo['apps-local-state'] != null && + accountInfo['apps-local-state'].length > 0 && + accountInfo['apps-local-state'][0].id == appId + ) { + alreadyOptedIn = true; + } + console.log('alreadyOptedIn: ' + alreadyOptedIn); + console.log('acct info:' + JSON.stringify(accountInfo)); + + const params = await algodClient.getTransactionParams().do(); + console.log('sending trans to: ' + lsig.address()); + + const assetSendTrans = await this.getAssetSendTxn( + algodClient, + makerAddr, + lsig.address(), + asaOrderSize, + assetId, + false + ); + + const payTxn = await this.getPayTxn( + algodClient, + makerAddr, + lsig.address(), + constants.MIN_ASA_ESCROW_BALANCE, + false + ); + + // myAlgoWalletUtil.setTransactionFee(payTxn); + + console.log('typeof: ' + typeof payTxn.txId); + console.log('the val: ' + payTxn.txId); + + // console.log("confirmed!!"); + // create unsigned transaction + + console.log('here3 calling app from logic sig to open order'); + const appArgs = []; + const enc = new TextEncoder(); + appArgs.push(enc.encode('open')); + + appArgs.push(enc.encode(generatedOrderEntry.slice(59))); + appArgs.push(new Uint8Array([constants.ESCROW_CONTRACT_VERSION])); + + // add owners address as arg + // ownersAddr = "WYWRYK42XADLY3O62N52BOLT27DMPRA3WNBT2OBRT65N6OEZQWD4OSH6PI"; + // ownersBitAddr = (algosdk.decodeAddress(ownersAddr)).publicKey; + console.log(appArgs.length); + + // let logSigTrans = await dexInternal.createTransactionFromLogicSig(algodClient, lsig, appId, + // appArgs, "appOptIn"); + + // create optin transaction + // sender and receiver are both the same + const sender = lsig.address(); + const recipient = sender; + // We set revocationTarget to undefined as + // This is not a clawback operation + const revocationTarget = undefined; + // CloseReaminerTo is set to undefined as + // we are not closing out an asset + const closeRemainderTo = undefined; + // We are sending 0 assets + const amount = 0; + + // signing and sending "txn" allows sender to begin accepting asset specified by creator and index + const logSigAssetOptInTrans = + algosdk.makeAssetTransferTxnWithSuggestedParams( + sender, + recipient, + closeRemainderTo, + revocationTarget, + amount, + undefined, + assetId, + params + ); + + outerTxns.push({ + unsignedTxn: payTxn, + senderAcct: makerAccount, + }); + outerTxns.push({ + unsignedTxn: logSigTrans, + lsig: lsig, + }); + outerTxns.push({ + unsignedTxn: logSigAssetOptInTrans, + lsig: lsig, + }); + outerTxns.push({ + unsignedTxn: assetSendTrans, + senderAcct: makerAccount, + }); + + return outerTxns; + }, +}; + +module.exports = GenerateTransactions; diff --git a/lib/order/__tests__/setup.js b/lib/order/__tests__/setup.js index 2fd02e7a..9ff3d498 100644 --- a/lib/order/__tests__/setup.js +++ b/lib/order/__tests__/setup.js @@ -1,13 +1,7 @@ -///////////////////////////// -// Alexander Trefonas // -// 7/9/2021 // -// Copyright Algodev Inc // -// All Rights Reserved. // -///////////////////////////// - const http = require('http'); const algosdk = require('algosdk'); const axios = require('axios').default; +const signer = require('../../wallet/signers/AlgoSDK'); // const algoDelegateTemplate = require('./algo_delegate_template_teal.js'); // const asaDelegateTemplate = require('./ASA_delegate_template_teal.js'); @@ -16,37 +10,40 @@ const axios = require('axios').default; // //require('./dex_teal.js'); // const dexInternal = require('./algodex_internal_api.js'); -const algodex = require('../../AlgodexApi.js'); +// const algodex = require('../../AlgodexApi.js'); // TODO: need to replace this with v2. -const constants = require('./constants.js'); -const transactionGenerator = require('./generate_transaction_types.js'); - -let ALGO_ESCROW_ORDER_BOOK_ID = -1; -let ASA_ESCROW_ORDER_BOOK_ID = -1; +// const constants = require('./constants.js'); +// const transactionGenerator = require('./generate_transaction_types.js'); -const ALGOD_SERVER='https://node.testnet.algoexplorerapi.io'; -const ALGOD_TOKEN = ''; //{ 'X-API-Key': 'VELyABA1dGqGbAVktbew4oACvp0c0298gMgYtYIb' } -const ALGOD_PORT=''; +// const ALGO_ESCROW_ORDER_BOOK_ID = -1; +// const ASA_ESCROW_ORDER_BOOK_ID = -1; +const ALGOD_SERVER = 'https://node.testnet.algoexplorerapi.io'; +const ALGOD_TOKEN = ''; // { 'X-API-Key': 'VELyABA1dGqGbAVktbew4oACvp0c0298gMgYtYIb' } +const ALGOD_PORT = ''; const TestHelper = { - getLocalClient : function getLocalClientAndEnv() { - //const algodClient = algodex.initAlgodClient("test"); - const algodClient = new algosdk.Algodv2(ALGOD_TOKEN, ALGOD_SERVER, ALGOD_PORT); - return algodClient; - }, - - getRandomAccount : function getRandomAccount() { - return algosdk.generateAccount(); - }, - - getAccountInfo : async function getAccountInfo(addr) { - return algodex.getAccountInfo(addr); - - // This is the old account info that uses algod, not the indexer - // This is necessary for the tests to go faster as the indexer takes time to update. - - /*try { + getLocalClient: function getLocalClientAndEnv() { + // const algodClient = algodex.initAlgodClient("test"); + const algodClient = new algosdk.Algodv2( + ALGOD_TOKEN, + ALGOD_SERVER, + ALGOD_PORT + ); + return algodClient; + }, + + getRandomAccount: function getRandomAccount() { + return algosdk.generateAccount(); + }, + + getAccountInfo: async function getAccountInfo(addr) { + return algodex.getAccountInfo(addr); + + // This is the old account info that uses algod, not the indexer + // This is necessary for the tests to go faster as the indexer takes time to update. + + /* try { let port = (!!ALGOD_PORT) ? ':' + ALGOD_PORT : ''; const response = await axios.get(ALGOD_SERVER + port + "/v2/accounts/"+addr, {headers: {'X-Algo-API-Token': ALGOD_TOKEN}}); //console.debug(response); @@ -55,249 +52,297 @@ const TestHelper = { console.error(error); throw new Error("getAccountInfo failed: ", error); }*/ - }, - - printOuterTransactions : function (outerTxns) { - for (let i = 0; i < outerTxns.length; i++ ) { - console.log(outerTxns[i]); - } - }, - - checkFailureType : function (error) { - let hasKnownError = false; - - if (error != null && error.response.body.message != null) { - const msg = error.response.body.message; - if (msg.includes("rejected by logic err=")) { - hasKnownError = true; - } else if (msg.includes("TEAL runtime encountered err opcode")) { - hasKnownError = true; - } else { - throw("Unknown error type: " + msg); - } - } - - return hasKnownError; - }, - - getOpenAccount : function getOpenAccount() { - //WYWRYK42XADLY3O62N52BOLT27DMPRA3WNBT2OBRT65N6OEZQWD4OSH6PI - let mn = "mass army warrior number blush distance enroll vivid horse become spend asthma hat desert amazing room asset ivory lucky ridge now deputy erase absorb above"; - let openAccount = algosdk.mnemonicToSecretKey(mn); - return openAccount; - }, - - transferASA : async function (client, fromAccount, toAccount, amount, assetId) { - const asaTransferTxn = await transactionGenerator.getAssetSendTxn(client, fromAccount, toAccount, amount, assetId, false); - const asaTxnId = asaTransferTxn.txID().toString(); - - let signedFundTxn = asaTransferTxn.signTxn(fromAccount.sk); - console.log("Signed transaction with txID: %s", asaTxnId); - - // Submit the transaction - try { - await client.sendRawTransaction(signedFundTxn).do(); - } catch (e) { - console.log(JSON.stringify(e)); - } - - // Wait for confirmation - await this.checkPending(client, asaTxnId); - }, - - transferFunds : async function (client, fromAccount, toAccount, amount) { - const fundTxn = await transactionGenerator.getPayTxn(client, fromAccount, toAccount, amount, false); - const fundTxnId = fundTxn.txID().toString(); - - let signedFundTxn = fundTxn.signTxn(fromAccount.sk); - console.log("Signed transaction with txID: %s", fundTxnId); - - // Submit the transaction - try { - await client.sendRawTransaction(signedFundTxn).do(); - } catch (e) { - console.log(JSON.stringify(e)); - } - - // Wait for confirmation - await this.checkPending(client, fundTxnId); - }, - - sendAndCheckConfirmed : async function(client, signedTxns) { - // Submit the transaction - let txId = null; - try { - let sentTxns = await client.sendRawTransaction(signedTxns).do(); - txId = sentTxns.txId; - } catch (e) { - throw e; - } - // Wait for confirmation - await this.waitForConfirmation(client, txId); - }, - sendAndCheckPending : async function(client, signedTxns) { - // Submit the transaction - let txId = null; - try { - let sentTxns = await client.sendRawTransaction(signedTxns).do(); - txId = sentTxns.txId; - } catch (e) { - throw e; - } - // Wait for confirmation - await this.checkPending(client, txId); - }, - - getOrderLsig : async function (algodClient, makerAccount, - price, assetId, isASAEscrow) { - - // Change this to {compile} and then return the lsig. - - const orderCreatorAddr = makerAccount.addr; - const numAndDenom = algodex.getNumeratorAndDenominatorFromPrice(price); - const n = numAndDenom.n; - const d = numAndDenom.d; - - const escrowSource = algodex.buildDelegateTemplateFromArgs(0, assetId, n, d, orderCreatorAddr, isASAEscrow, constants.ESCROW_CONTRACT_VERSION); - const lsig = await algodex.getLsigFromProgramSource(algosdk, algodClient, escrowSource, constants.DEBUG_SMART_CONTRACT_SOURCE); - return lsig; - }, - - getAssetBalance : async function (accountAddr, assetId) { - console.log("checking account info for: " + accountAddr) - const accountInfo = await this.getAccountInfo(accountAddr); - if (accountInfo != null && accountInfo['assets'] != null - && accountInfo['assets'].length > 0) { - for (let i = 0; i < accountInfo['assets'].length; i++) { - let asset = accountInfo['assets'][i]; - console.log({asset} ); - if (asset['asset-id'] == assetId) { - return asset['amount']; - } - } - } - return null; - }, - - closeAccount : async function closeAccount (client, fromAccount, toAccount) { - console.log("checking account info for: " + fromAccount.addr) - const fromAccountInfo = await this.getAccountInfo(fromAccount.addr); - if (fromAccountInfo != null && fromAccountInfo['assets'] != null - && fromAccountInfo['assets'].length > 0) { - for (let i = 0; i < fromAccountInfo['assets'].length; i++) { - let asset = fromAccountInfo['assets'][i]; - let assetId = asset['asset-id']; - console.log("closing asset: " + assetId + " for account: " + fromAccount.addr); - let txn = await transactionGenerator.getAssetSendTxn(client, fromAccount, toAccount, 0, assetId, true); - let signedTxn = algosdk.signTransaction(txn, fromAccount.sk); - await this.sendAndCheckPending(client, [signedTxn.blob]); - } - } - - const fundTxn = await transactionGenerator.getPayTxn(client, fromAccount, toAccount, 0, true); - const fundTxnId = fundTxn.txID().toString(); - let signedTxn = fundTxn.signTxn(fromAccount.sk); - console.log("Signed transaction with txID: %s", fundTxnId); - // Submit the transaction - try { - await client.sendRawTransaction(signedTxn).do(); - } catch (e) { - console.log(JSON.stringify(e)); - } - await this.checkPending(client, fundTxnId); - }, - - deleteApplication : async function deleteApplication (client, sender, appId) { - // create unsigned transaction - let params = await client.getTransactionParams().do(); - let txn = algosdk.makeApplicationDeleteTxn(sender.addr, params, appId); - - // sign, send, await - let signedTxn = txn.signTxn(sender.sk); - let txId = txn.txID().toString(); - - console.log("Signed transaction with txID: %s", txId); - // Submit the transaction - try { - await client.sendRawTransaction(signedTxn).do(); - } catch (e) { - console.log(JSON.stringify(e)); - } - // display results - let transactionResponse = await client.pendingTransactionInformation(txId).do(); - console.log("Deleted app-id: ",appId); - }, - - getExecuteAccount : function getExecuteAccount() { - //UUEUTRNQY7RUXESXRDO7HSYRSJJSSVKYVB4DI7X2HVVDWYOBWJOP5OSM3A - let mn = "three satisfy build purse lens another idle fashion base equal echo recall proof hill shadow coach early palm act wealth dawn menu portion above mystery"; - let executeAccount = algosdk.mnemonicToSecretKey(mn); - return executeAccount; - }, - - // helper function to await transaction confirmation - waitForConfirmation : async function waitForConfirmation (algodClient, txId) { - let status = (await algodClient.status().do()); - let lastRound = status["last-round"]; - while (true) { - const pendingInfo = await algodClient.pendingTransactionInformation(txId).do(); - if (pendingInfo["confirmed-round"] !== null && pendingInfo["confirmed-round"] > 0) { - //Got the completed Transaction - console.log("Transaction " + txId + " confirmed in round " + pendingInfo["confirmed-round"]); - break; - } - lastRound++; - await algodClient.statusAfterBlock(lastRound).do(); - } - }, - - // helper function to await transaction confirmation - checkPending : async function checkPending (algodClient, txId) { - while (true) { - const pendingInfo = await algodClient.pendingTransactionInformation(txId).do(); - if (pendingInfo != null && pendingInfo.txn != null && pendingInfo.txn.txn != null) { - break; - } - } - }, - - groupAndSignTransactions : - function (outerTxns) { - console.log("inside signAndSend transactions"); - let txns = []; - - for (let i = 0; i < outerTxns.length; i++) { - txns.push(outerTxns[i].unsignedTxn); - } - - const groupID = algosdk.computeGroupID(txns); - for (let i = 0; i < txns.length; i++) { - txns[i].group = groupID; - } - - for (let i = 0; i < outerTxns.length; i++) { - let txn = outerTxns[i]; - if (txn.lsig != null) { - let signedLsig = algosdk.signLogicSigTransactionObject(txn.unsignedTxn, txn.lsig); - txn.signedTxn = signedLsig.blob; - } else { - let signedTxn = algosdk.signTransaction(txn.unsignedTxn, txn.senderAcct.sk); - txn.signedTxn = signedTxn.blob; - } - } - - let signed = []; - - for (let i = 0; i < outerTxns.length; i++) { - signed.push(outerTxns[i].signedTxn); - } - console.log("printing transaction debug"); - algodex.printTransactionDebug(signed); - - return signed; - }, - - -} - -module.exports = TestHelper; \ No newline at end of file + }, + + printOuterTransactions: function (outerTxns) { + for (let i = 0; i < outerTxns.length; i++) { + console.log(outerTxns[i]); + } + }, + + checkFailureType: function (error) { + let hasKnownError = false; + + if (error != null && error.response.body.message != null) { + const msg = error.response.body.message; + if (msg.includes('rejected by logic err=')) { + hasKnownError = true; + } else if (msg.includes('TEAL runtime encountered err opcode')) { + hasKnownError = true; + } else { + throw 'Unknown error type: ' + msg; + } + } + + return hasKnownError; + }, + + getOpenAccount: function getOpenAccount() { + // WYWRYK42XADLY3O62N52BOLT27DMPRA3WNBT2OBRT65N6OEZQWD4OSH6PI + const mn = + 'mass army warrior number blush distance enroll vivid horse become spend asthma hat desert amazing room asset ivory lucky ridge now deputy erase absorb above'; + const openAccount = algosdk.mnemonicToSecretKey(mn); + return openAccount; + }, + + // transferASA: async function ( + // client, + // fromAccount, + // toAccount, + // amount, + // assetId + // ) { + // const asaTransferTxn = await transactionGenerator.getAssetSendTxn( + // client, + // fromAccount, + // toAccount, + // amount, + // assetId, + // false + // ); + // const asaTxnId = asaTransferTxn.txID().toString(); + + // const signedFundTxn = asaTransferTxn.signTxn(fromAccount.sk); + // console.log('Signed transaction with txID: %s', asaTxnId); + + // // Submit the transaction + // try { + // await client.sendRawTransaction(signedFundTxn).do(); + // } catch (e) { + // console.log(JSON.stringify(e)); + // } + + // // Wait for confirmation + // await this.checkPending(client, asaTxnId); + // }, + + // transferFunds: async function (client, fromAccount, toAccount, amount) { + // const fundTxn = await transactionGenerator.getPayTxn( + // client, + // fromAccount, + // toAccount, + // amount, + // false + // ); + // const fundTxnId = fundTxn.txID().toString(); + + // const signedFundTxn = fundTxn.signTxn(fromAccount.sk); + // console.log('Signed transaction with txID: %s', fundTxnId); + + // // Submit the transaction + // try { + // await client.sendRawTransaction(signedFundTxn).do(); + // } catch (e) { + // console.log(JSON.stringify(e)); + // } + + // // Wait for confirmation + // await this.checkPending(client, fundTxnId); + // }, + + // sendAndCheckConfirmed: async function (client, signedTxns) { + // // Submit the transaction + // let txId = null; + // try { + // const sentTxns = await client.sendRawTransaction(signedTxns).do(); + // txId = sentTxns.txId; + // } catch (e) { + // throw e; + // } + // // Wait for confirmation + // await this.waitForConfirmation(client, txId); + // }, + // sendAndCheckPending: async function (client, signedTxns) { + // // Submit the transaction + // let txId = null; + // try { + // const sentTxns = await client.sendRawTransaction(signedTxns).do(); + // txId = sentTxns.txId; + // } catch (e) { + // throw e; + // } + // // Wait for confirmation + // await this.checkPending(client, txId); + // }, + + // getAssetBalance: async function (accountAddr, assetId) { + // console.log('checking account info for: ' + accountAddr); + // const accountInfo = await this.getAccountInfo(accountAddr); + // if ( + // accountInfo != null && + // accountInfo['assets'] != null && + // accountInfo['assets'].length > 0 + // ) { + // for (let i = 0; i < accountInfo['assets'].length; i++) { + // const asset = accountInfo['assets'][i]; + // console.log({ asset }); + // if (asset['asset-id'] == assetId) { + // return asset['amount']; + // } + // } + // } + // return null; + // }, + + // closeAccount: async function closeAccount(client, fromAccount, toAccount) { + // console.log('checking account info for: ' + fromAccount.addr); + // const fromAccountInfo = await this.getAccountInfo(fromAccount.addr); + // if ( + // fromAccountInfo != null && + // fromAccountInfo['assets'] != null && + // fromAccountInfo['assets'].length > 0 + // ) { + // for (let i = 0; i < fromAccountInfo['assets'].length; i++) { + // const asset = fromAccountInfo['assets'][i]; + // const assetId = asset['asset-id']; + // console.log( + // 'closing asset: ' + assetId + ' for account: ' + fromAccount.addr + // ); + // const txn = await transactionGenerator.getAssetSendTxn( + // client, + // fromAccount, + // toAccount, + // 0, + // assetId, + // true + // ); + // const signedTxn = algosdk.signTransaction(txn, fromAccount.sk); + // await this.sendAndCheckPending(client, [signedTxn.blob]); + // } + // } + + // const fundTxn = await transactionGenerator.getPayTxn( + // client, + // fromAccount, + // toAccount, + // 0, + // true + // ); + // const fundTxnId = fundTxn.txID().toString(); + // const signedTxn = fundTxn.signTxn(fromAccount.sk); + // console.log('Signed transaction with txID: %s', fundTxnId); + // // Submit the transaction + // try { + // await client.sendRawTransaction(signedTxn).do(); + // } catch (e) { + // console.log(JSON.stringify(e)); + // } + // await this.checkPending(client, fundTxnId); + // }, + + // deleteApplication: async function deleteApplication(client, sender, appId) { + // // create unsigned transaction + // const params = await client.getTransactionParams().do(); + // const txn = algosdk.makeApplicationDeleteTxn(sender.addr, params, appId); + + // // sign, send, await + // const signedTxn = txn.signTxn(sender.sk); + // const txId = txn.txID().toString(); + + // console.log('Signed transaction with txID: %s', txId); + // // Submit the transaction + // try { + // await client.sendRawTransaction(signedTxn).do(); + // } catch (e) { + // console.log(JSON.stringify(e)); + // } + // // display results + // const transactionResponse = await client + // .pendingTransactionInformation(txId) + // .do(); + // console.log('Deleted app-id: ', appId); + // }, + + // getExecuteAccount: function getExecuteAccount() { + // // UUEUTRNQY7RUXESXRDO7HSYRSJJSSVKYVB4DI7X2HVVDWYOBWJOP5OSM3A + // const mn = + // 'three satisfy build purse lens another idle fashion base equal echo recall proof hill shadow coach early palm act wealth dawn menu portion above mystery'; + // const executeAccount = algosdk.mnemonicToSecretKey(mn); + // return executeAccount; + // }, + + // helper function to await transaction confirmation + // waitForConfirmation: async function waitForConfirmation(algodClient, txId) { + // const status = await algodClient.status().do(); + // let lastRound = status['last-round']; + // while (true) { + // const pendingInfo = await algodClient + // .pendingTransactionInformation(txId) + // .do(); + // if ( + // pendingInfo['confirmed-round'] !== null && + // pendingInfo['confirmed-round'] > 0 + // ) { + // // Got the completed Transaction + // console.log( + // 'Transaction ' + + // txId + + // ' confirmed in round ' + + // pendingInfo['confirmed-round'] + // ); + // break; + // } + // lastRound++; + // await algodClient.statusAfterBlock(lastRound).do(); + // } + // }, + + // helper function to await transaction confirmation + // checkPending: async function checkPending(algodClient, txId) { + // while (true) { + // const pendingInfo = await algodClient + // .pendingTransactionInformation(txId) + // .do(); + // if ( + // pendingInfo != null && + // pendingInfo.txn != null && + // pendingInfo.txn.txn != null + // ) { + // break; + // } + // } + // }, + + // groupAndSignTransactions: function (outerTxns) { + // console.log('inside signAndSend transactions'); + // const txns = []; + + // for (let i = 0; i < outerTxns.length; i++) { + // txns.push(outerTxns[i].unsignedTxn); + // } + + // const groupID = algosdk.computeGroupID(txns); + // for (let i = 0; i < txns.length; i++) { + // txns[i].group = groupID; + // } + + // for (let i = 0; i < outerTxns.length; i++) { + // const txn = outerTxns[i]; + // if (txn.lsig != null) { + // const signedLsig = algosdk.signLogicSigTransactionObject( + // txn.unsignedTxn, + // txn.lsig + // ); + // txn.signedTxn = signedLsig.blob; + // } else { + // const signedTxn = algosdk.signTransaction( + // txn.unsignedTxn, + // txn.senderAcct.sk + // ); + // txn.signedTxn = signedTxn.blob; + // } + // } + + // const signed = []; + + // for (let i = 0; i < outerTxns.length; i++) { + // signed.push(outerTxns[i].signedTxn); + // } + // console.log('printing transaction debug'); + // algodex.printTransactionDebug(signed); + + // return signed; + // }, +}; + +module.exports = TestHelper; diff --git a/lib/order/__tests__/teal_tests/createAppTest.js b/lib/order/__tests__/teal_tests/createAppTest.js index 27a2cb84..d8150005 100644 --- a/lib/order/__tests__/teal_tests/createAppTest.js +++ b/lib/order/__tests__/teal_tests/createAppTest.js @@ -3,58 +3,57 @@ const transactionGenerator = require('../generate_transaction_types.js'); const algosdk = require('algosdk'); const Test = { - runTest : createAppTest = async(config, isAlgoEscrowApp = true, optIntoASAForExecutor = true) => { - - console.log("STARTING createAppTest: ", {isAlgoEscrowApp} ); - const client = config.client; - const openAccount = config.openAccount; - const maliciousAccount = config.maliciousAccount; - const creatorAccount = config.creatorAccount; - const executorAccount = config.executorAccount; - - console.log("starting the test"); - - await testHelper.transferFunds(client, openAccount, creatorAccount, 5000000); //5 algos - await testHelper.transferFunds(client, openAccount, executorAccount, 5000000); //5 algos - await testHelper.transferASA(client, creatorAccount, creatorAccount, 0, config.assetId); //opt in transaction - await testHelper.transferASA(client, openAccount, creatorAccount, 2000000, config.assetId); //5 algos - if (optIntoASAForExecutor) { - await testHelper.transferASA(client, executorAccount, executorAccount, 0, config.assetId); //opt in transaction - await testHelper.transferASA(client, openAccount, executorAccount, 2000000, config.assetId); //5 algos - } - - await testHelper.transferFunds(client, openAccount, maliciousAccount, 5000000); //5 algos - await testHelper.transferASA(client, maliciousAccount, maliciousAccount, 0, config.assetId); //opt in transaction - await testHelper.transferASA(client, openAccount, maliciousAccount, 2000000, config.assetId); //5 algos - - const createTxn = await transactionGenerator.getCreateAppTxn(client, creatorAccount, isAlgoEscrowApp); - let txId = createTxn.txID().toString(); - console.log("txID: " + txId); - - // Sign the transaction - - let signedTxn = createTxn.signTxn(creatorAccount.sk); - console.log("Signed transaction with txID: %s", txId); - - // Submit the transaction - try { - await client.sendRawTransaction(signedTxn).do(); - } catch (e) { - console.log(JSON.stringify(e)); - } - - // Wait for confirmation - await testHelper.waitForConfirmation(client, txId); - - // display results - let transactionResponse = await client.pendingTransactionInformation(txId).do(); - appId = transactionResponse['application-index']; - console.log("Created new app-id: ", appId); - - let accountInfo = await testHelper.getAccountInfo(creatorAccount.addr); - console.log( "amount: " , accountInfo.amount ); - - return appId; + runTest: createAppTest = async (config, isAlgoEscrowApp = true, optIntoASAForExecutor = true) => { + console.log('STARTING createAppTest: ', {isAlgoEscrowApp} ); + const client = config.client; + const openAccount = config.openAccount; + const maliciousAccount = config.maliciousAccount; + const creatorAccount = config.creatorAccount; + const executorAccount = config.executorAccount; + + console.log('starting the test'); + + await testHelper.transferFunds(client, openAccount, creatorAccount, 5000000); // 5 algos + await testHelper.transferFunds(client, openAccount, executorAccount, 5000000); // 5 algos + await testHelper.transferASA(client, creatorAccount, creatorAccount, 0, config.assetId); // opt in transaction + await testHelper.transferASA(client, openAccount, creatorAccount, 2000000, config.assetId); // 5 algos + if (optIntoASAForExecutor) { + await testHelper.transferASA(client, executorAccount, executorAccount, 0, config.assetId); // opt in transaction + await testHelper.transferASA(client, openAccount, executorAccount, 2000000, config.assetId); // 5 algos } -} -module.exports = Test; \ No newline at end of file + + await testHelper.transferFunds(client, openAccount, maliciousAccount, 5000000); // 5 algos + await testHelper.transferASA(client, maliciousAccount, maliciousAccount, 0, config.assetId); // opt in transaction + await testHelper.transferASA(client, openAccount, maliciousAccount, 2000000, config.assetId); // 5 algos + + const createTxn = await transactionGenerator.getCreateAppTxn(client, creatorAccount, isAlgoEscrowApp); + const txId = createTxn.txID().toString(); + console.log('txID: ' + txId); + + // Sign the transaction + + const signedTxn = createTxn.signTxn(creatorAccount.sk); + console.log('Signed transaction with txID: %s', txId); + + // Submit the transaction + try { + await client.sendRawTransaction(signedTxn).do(); + } catch (e) { + console.log(JSON.stringify(e)); + } + + // Wait for confirmation + await testHelper.waitForConfirmation(client, txId); + + // display results + const transactionResponse = await client.pendingTransactionInformation(txId).do(); + appId = transactionResponse['application-index']; + console.log('Created new app-id: ', appId); + + const accountInfo = await testHelper.getAccountInfo(creatorAccount.addr); + console.log( 'amount: ', accountInfo.amount ); + + return appId; + }, +}; +module.exports = Test; diff --git a/lib/order/__tests__/teal_tests/placeASAEscrowOrder.js b/lib/order/__tests__/teal_tests/placeASAEscrowOrder.js index 33475aae..b0ec8fdf 100644 --- a/lib/order/__tests__/teal_tests/placeASAEscrowOrder.js +++ b/lib/order/__tests__/teal_tests/placeASAEscrowOrder.js @@ -1,34 +1,81 @@ /* eslint-disable */ const testHelper = require('../setup.js'); -const transactionGenerator = require('../../lib/teal/generate_transaction_types.js'); +const transactionGenerator = require('../GenerateTransactionTypes'); const algosdk = require('algosdk'); +const signer = require('../../../wallet/signers/AlgoSDK') + +const _sendTransactions = async (client, signedTransactions) => { + for (const group of signedTransactions) { + console.debug(`Sending ${group.length} Group Transactions`); + const rawTxns = group.map((txn) => txn.blob); + + const {txId} = await client.sendRawTransaction(rawTxns).do(); + console.debug(`Waiting for confirmation for ${txId}`); + await algosdk.waitForConfirmation(client, txId, 10); + console.debug(`Confirmed ${txId}`); + } +}; const PRINT_TXNS = 0; const Test = { - runTest: async function(config, asaAmount, price, returnOuterTransactions) { + runTest: async function ( + config, + asaAmount, + price, + optIn, + returnOuterTransactions + ) { console.log('STARTING placeASAEscrowOrder test'); const client = config.client; - const creatorAccount = config.creatorAccount; - const appId = config.appId; - const outerTxns = await transactionGenerator.getPlaceASAEscrowOrderTxns(client, creatorAccount, asaAmount, price, config.assetId, appId); + const creatorAccount = config.creatorAccount.addr; + const wallet = { + type: 'sdk', + address: config.creatorAccount.addr, + connector: { + ...config.connector, + sk: config.creatorAccount.sk, //Just in case we want to test signing and sending from the api and not from the tests. + connected: true, + }, + // mnemonic: config.creatorAccount.sk, + }; + + const order = { + asset: { + id: config.assetId, + decimals: 6, + }, + address: creatorAccount, + price: price, + amount: asaAmount, + total: price * asaAmount, + type: 'sell', + client: config.client, + execution: 'maker', + wallet: wallet, + }; + + const placeASAEscrowOrder = await transactionGenerator.getPlaceASAEscrowOrderTxns( + order, + optIn + ); if (returnOuterTransactions) { return outerTxns; } - const signedTxns = testHelper.groupAndSignTransactions(outerTxns); + const signedTxns = await signer([placeASAEscrowOrder], config.creatorAccount.sk) - await testHelper.sendAndCheckConfirmed(client, signedTxns); + const confirmation = await _sendTransactions(client, signedTxns); return true; }, - getOuterTransactions: async function(config) { + getOuterTransactions: async function (config) { const outerTxns = await this.runTest(config, 200000, 1.2, true); return outerTxns; }, - runGroupSizeWrongTest: async function(config) { + runGroupSizeWrongTest: async function (config) { const outerTxns = await this.getOuterTransactions(config); const client = config.client; const maliciousAccount = config.maliciousAccount; @@ -39,9 +86,14 @@ const Test = { const lsig = outerTxns[1].lsig; - outerTxns.push( { - unsignedTxn: await transactionGenerator.getPayTxn(client, lsig.address(), maliciousAccount.addr, - 1000, false), + outerTxns.push({ + unsignedTxn: await transactionGenerator.getPayTxn( + client, + lsig.address(), + maliciousAccount.addr, + 1000, + false + ), lsig: lsig, }); @@ -56,7 +108,7 @@ const Test = { return false; }, - runGroupSizeWrongTest2: async function(config) { + runGroupSizeWrongTest2: async function (config) { const outerTxns = await this.getOuterTransactions(config); const client = config.client; const maliciousAccount = config.maliciousAccount; @@ -67,9 +119,14 @@ const Test = { const lsig = outerTxns[1].lsig; - outerTxns.push( { - unsignedTxn: await transactionGenerator.getPayTxn(client, maliciousAccount.addr, maliciousAccount.addr, - 1000, false), + outerTxns.push({ + unsignedTxn: await transactionGenerator.getPayTxn( + client, + maliciousAccount.addr, + maliciousAccount.addr, + 1000, + false + ), senderAcct: maliciousAccount, }); @@ -84,7 +141,7 @@ const Test = { return false; }, - runPayAmountTooLowTest: async function(config, skipASAOptIn = false) { + runPayAmountTooLowTest: async function (config, skipASAOptIn = false) { const outerTxns = await this.getOuterTransactions(config); const client = config.client; const maliciousAccount = config.maliciousAccount; @@ -108,7 +165,7 @@ const Test = { return false; }, - runAppOptInMissingTest: async function(config, skipASAOptIn = false) { + runAppOptInMissingTest: async function (config, skipASAOptIn = false) { const outerTxns = await this.getOuterTransactions(config); const client = config.client; const maliciousAccount = config.maliciousAccount; @@ -120,8 +177,13 @@ const Test = { const lsig = outerTxns[1].lsig; outerTxns[1] = { - unsignedTxn: await transactionGenerator.getPayTxn(client, maliciousAccount.addr, maliciousAccount.addr, - 1000, false), + unsignedTxn: await transactionGenerator.getPayTxn( + client, + maliciousAccount.addr, + maliciousAccount.addr, + 1000, + false + ), senderAcct: maliciousAccount, }; @@ -136,7 +198,7 @@ const Test = { return false; }, - runAssetIdWrongTest: async function(config, skipASAOptIn = false) { + runAssetIdWrongTest: async function (config, skipASAOptIn = false) { const outerTxns = await this.getOuterTransactions(config); const client = config.client; const maliciousAccount = config.maliciousAccount; @@ -160,7 +222,7 @@ const Test = { return false; }, - runAssetAmountZeroTest: async function(config, skipASAOptIn = false) { + runAssetAmountZeroTest: async function (config, skipASAOptIn = false) { const outerTxns = await this.getOuterTransactions(config); const client = config.client; const maliciousAccount = config.maliciousAccount; @@ -183,7 +245,7 @@ const Test = { return false; }, - runAssetRecipientWrongTest: async function(config, skipASAOptIn = false) { + runAssetRecipientWrongTest: async function (config, skipASAOptIn = false) { const outerTxns = await this.getOuterTransactions(config); const client = config.client; const maliciousAccount = config.maliciousAccount; @@ -205,6 +267,5 @@ const Test = { return false; }, - }; module.exports = Test; diff --git a/lib/order/txns/buy/makeExecuteAlgoTxns.spec.js b/lib/order/txns/buy/makeExecuteAlgoTxns.spec.js index 2cbe1f86..682e14db 100644 --- a/lib/order/txns/buy/makeExecuteAlgoTxns.spec.js +++ b/lib/order/txns/buy/makeExecuteAlgoTxns.spec.js @@ -77,7 +77,7 @@ describe('makeExecuteAlgoTxns', () => { // }; // }).forEach(({order, exist, optIn})=>{ let signedTxns; - it('should create ExecuteAlgoTxns', async () => { + it.skip('should create ExecuteAlgoTxns', async () => { const openBuyOrder = (await config.api.http.dexd.fetchOrders('wallet', 'UUEUTRNQY7RUXESXRDO7HSYRSJJSSVKYVB4DI7X2HVVDWYOBWJOP5OSM3A')).filter((o) => o.type === 'buy')[0]; openBuyOrder.wallet = config.api.wallet; openBuyOrder.client = config.client; diff --git a/lib/teal/test/initAccounts.js b/lib/teal/test/initAccounts.js index 4d1545f7..6978281f 100644 --- a/lib/teal/test/initAccounts.js +++ b/lib/teal/test/initAccounts.js @@ -15,25 +15,26 @@ async function initAccounts(config, optIn = false, newCreator = false) { // and overrides the current creator account config.setCreatorAccount(algosdk.generateAccount()); } + const {client, openAccount, maliciousAccount, creatorAccount, executorAccount, assetId} = config; - await transferFunds(config.client, config.openAccount, config.creatorAccount, 2000000); - const {client, openAccount, maliciousAccount, creatorAccount, executorAccount} = config; + await transferFunds(client, openAccount, creatorAccount, 2000000); - await transferFunds(client, openAccount, creatorAccount, 5000000); // 5 algos - await transferFunds(client, openAccount, executorAccount, 5000000); // 5 algos - await transferASA(client, creatorAccount, creatorAccount, 0, config.assetIndex); // opt in transaction - await transferASA(client, openAccount, creatorAccount, 2000000, config.assetIndex); // 5 algos - if (optIn) { - await transferASA(client, executorAccount, executorAccount, 0, config.assetIndex); // opt in transaction - await transferASA(client, openAccount, executorAccount, 2000000, config.assetIndex); // 5 algos - } + // await transferFunds(client, openAccount, creatorAccount, 5000000); // 5 algos + // await transferFunds(client, openAccount, executorAccount, 5000000); // 5 algos + await transferASA(client, creatorAccount, creatorAccount, 0, assetId); // opt in transaction + await transferASA(client, openAccount, creatorAccount, 2000000, assetId); // 5 algos + + // if (optIn) { + // await transferASA(client, executorAccount, executorAccount, 0, config.assetIndex); // opt in transaction + // await transferASA(client, openAccount, executorAccount, 2000000, config.assetIndex); // 5 algos + // } - await transferFunds(client, openAccount, maliciousAccount, 5000000); // 5 algos - await transferASA(client, maliciousAccount, maliciousAccount, 0, config.assetIndex); // opt in transaction - await transferASA(client, openAccount, maliciousAccount, 2000000, config.assetIndex); // 5 algos + // await transferFunds(client, openAccount, maliciousAccount, 5000000); // 5 algos + // await transferASA(client, maliciousAccount, maliciousAccount, 0, config.assetIndex); // opt in transaction + // await transferASA(client, openAccount, maliciousAccount, 2000000, config.assetIndex); // 5 algos } module.exports = initAccounts; diff --git a/lib/teal/utils.js b/lib/teal/utils.js index 899891fd..b1770faf 100644 --- a/lib/teal/utils.js +++ b/lib/teal/utils.js @@ -185,9 +185,16 @@ async function closeAccount(client, fromAccount, toAccount) { * @return {Promise} */ async function transferFunds(client, fromAccount, toAccount, amount) { - const fundTxn = await txns.makePaymentTxn( - client, fromAccount, toAccount, amount, false, - ); + const _suggestedParams = await client.getTransactionParams().do() + const fundTxn = algosdk.makePaymentTxnWithSuggestedParams( + fromAccount.addr, + toAccount.addr, + amount, + undefined, + undefined, + _suggestedParams, + undefined, +) const fundTxnId = fundTxn.txID().toString(); const signedFundTxn = fundTxn.signTxn(fromAccount.sk); @@ -279,7 +286,19 @@ async function transferASA( amount, assetId, ) { - const asaTransferTxn = await txns.makeAssetTransferTxn(client, fromAccount, toAccount, amount, assetId, false); + const _suggestedParams = await client.getTransactionParams().do() + + const asaTransferTxn = algosdk.makeAssetTransferTxnWithSuggestedParams( + fromAccount.addr, + toAccount.addr, + undefined, + undefined, + amount, + undefined, + assetId, + _suggestedParams, + undefined, +) const asaTxnId = asaTransferTxn.txID().toString(); const signedFundTxn = asaTransferTxn.signTxn(fromAccount.sk);