diff --git a/examples/accounts.ts b/examples/accounts.ts index 30f959c88..4f144ca7c 100644 --- a/examples/accounts.ts +++ b/examples/accounts.ts @@ -101,7 +101,7 @@ async function main() { const acctInfo = await client.accountInformation(acct1.addr).do(); console.log( - `Account Info: ${JSON.stringify(acctInfo)} Auth Addr: ${ + `Account Info: ${algosdk.stringifyJSON(acctInfo)} Auth Addr: ${ acctInfo['auth-addr'] }` ); diff --git a/examples/app.ts b/examples/app.ts index 14999f0ef..775eed265 100644 --- a/examples/app.ts +++ b/examples/app.ts @@ -133,7 +133,7 @@ async function main() { // example: APP_READ_STATE const appInfo = await algodClient.getApplicationByID(appId).do(); const globalState = appInfo.params.globalState[0]; - console.log(`Raw global state - ${JSON.stringify(globalState)}`); + console.log(`Raw global state - ${algosdk.stringifyJSON(globalState)}`); // decode b64 string key with Buffer const globalKey = algosdk.base64ToString(globalState.key); @@ -147,7 +147,7 @@ async function main() { .do(); const localState = accountAppInfo.appLocalState.keyValue[0]; - console.log(`Raw local state - ${JSON.stringify(localState)}`); + console.log(`Raw local state - ${algosdk.stringifyJSON(localState)}`); // decode b64 string key with Buffer const localKey = algosdk.base64ToString(localState.key); diff --git a/examples/asa.ts b/examples/asa.ts index 64b4ffffb..134f18667 100644 --- a/examples/asa.ts +++ b/examples/asa.ts @@ -42,7 +42,7 @@ async function main() { // example: ASSET_INFO const assetInfo = await algodClient.getAssetByID(assetIndex).do(); console.log(`Asset Name: ${assetInfo.params.name}`); - console.log(`Asset Params: ${JSON.stringify(assetInfo.params)}`); + console.log(`Asset Params: ${algosdk.stringifyJSON(assetInfo.params)}`); // example: ASSET_INFO await new Promise((f) => setTimeout(f, 45000)); // sleep to ensure indexer is caught up diff --git a/examples/indexer.ts b/examples/indexer.ts index e2fba35c9..4f4c2116c 100644 --- a/examples/indexer.ts +++ b/examples/indexer.ts @@ -82,7 +82,7 @@ async function main() { .notePrefix(new TextEncoder().encode('Hello')) .do(); console.log( - `Transactions with note prefix "Hello" ${JSON.stringify( + `Transactions with note prefix "Hello" ${algosdk.stringifyJSON( txnsWithNotePrefix, undefined, 2 diff --git a/examples/overview.ts b/examples/overview.ts index a94d863ca..a8803c7c5 100644 --- a/examples/overview.ts +++ b/examples/overview.ts @@ -38,7 +38,7 @@ async function main() { const { txid } = await algodClient.sendRawTransaction(signedTxn).do(); const result = await algosdk.waitForConfirmation(algodClient, txid, 4); console.log(result); - console.log(`Transaction Information: ${JSON.stringify(result.txn)}`); + console.log(`Transaction Information: ${algosdk.stringifyJSON(result.txn)}`); console.log( `Decoded Note: ${new TextDecoder('utf-8').decode(result.txn.txn.note)}` ); diff --git a/src/client/client.ts b/src/client/client.ts index 08dff35ed..7a7dff65b 100644 --- a/src/client/client.ts +++ b/src/client/client.ts @@ -112,8 +112,7 @@ export class HTTPClient { } /** - * Parse JSON using either the built-in JSON.parse or utils.parseJSON - * depending on whether jsonOptions are provided or not + * Parse JSON using utils.parseJSON * * @param text - JSON data * @param status - Status of the response (used in case parseJSON fails) @@ -123,13 +122,13 @@ export class HTTPClient { public static parseJSON( text: string, status: number, - jsonOptions: utils.JSONOptions = {} + jsonOptions: utils.ParseJSONOptions ) { try { - if (Object.keys(jsonOptions).length === 0) { - return text && JSON.parse(text); + if (!text) { + return null; } - return text && utils.parseJSON(text, jsonOptions); + return utils.parseJSON(text, jsonOptions); } catch (err_) { const err = err_ as ErrorWithAdditionalInfo; // return the raw response if the response parsing fails @@ -156,7 +155,7 @@ export class HTTPClient { return new Uint8Array(0); // empty Uint8Array } if (requestHeaders['content-type'] === 'application/json') { - return new TextEncoder().encode(JSON.stringify(data)); + return new TextEncoder().encode(utils.stringifyJSON(data)); } if (typeof data === 'string') { return new TextEncoder().encode(data); @@ -178,7 +177,7 @@ export class HTTPClient { res: BaseHTTPClientResponse, format: 'application/msgpack' | 'application/json', parseBody: boolean, - jsonOptions: utils.JSONOptions = {} + jsonOptions: utils.ParseJSONOptions ): HTTPClientResponse { let { body } = res; let text: string | undefined; @@ -205,13 +204,17 @@ export class HTTPClient { * by adding the status and preparing the internal response * @private */ - private static prepareResponseError(err: any) { + private static prepareResponseError( + err: any, + jsonOptions: utils.ParseJSONOptions + ) { if (err.response) { // eslint-disable-next-line no-param-reassign err.response = HTTPClient.prepareResponse( err.response, 'application/json', - true + true, + jsonOptions ); // eslint-disable-next-line no-param-reassign err.status = err.response.status; @@ -221,24 +224,32 @@ export class HTTPClient { /** * Send a GET request. - * @param relativePath - The path of the request. - * @param query - An object containing the query parameters of the request. - * @param requestHeaders - An object containing additional request headers to use. - * @param jsonOptions - Options object to use to decode JSON responses. See + * + * @param options - The options to use for the request. + * @param options.relativePath - The path of the request. + * @param options.jsonOptions - Options object to use to decode JSON responses. See * utils.parseJSON for the options available. - * @param parseBody - An optional boolean indicating whether the response body should be parsed + * @param options.query - An object containing the query parameters of the request. + * @param options.requestHeaders - An object containing additional request headers to use. + * @param options.parseBody - An optional boolean indicating whether the response body should be parsed * or not. * @returns Response object. */ - async get( - relativePath: string, - query?: Query, - requestHeaders: Record = {}, - jsonOptions: utils.JSONOptions = {}, - parseBody: boolean = true - ): Promise { + async get({ + relativePath, + jsonOptions, + query, + requestHeaders, + parseBody, + }: { + relativePath: string; + jsonOptions: utils.ParseJSONOptions; + query?: Query; + requestHeaders?: Record; + parseBody: boolean; + }): Promise { const format = getAcceptFormat(query); - const fullHeaders = { ...requestHeaders, accept: format }; + const fullHeaders = { ...(requestHeaders ?? {}), accept: format }; try { const res = await this.bc.get( @@ -249,7 +260,7 @@ export class HTTPClient { return HTTPClient.prepareResponse(res, format, parseBody, jsonOptions); } catch (err) { - throw HTTPClient.prepareResponseError(err); + throw HTTPClient.prepareResponseError(err, jsonOptions); } } @@ -257,17 +268,26 @@ export class HTTPClient { * Send a POST request. * If no content-type present, adds the header "content-type: application/json" * and data is serialized in JSON (if not empty) + * @param options - The options to use for the request. */ - async post( - relativePath: string, - data: any, - query?: Query, - requestHeaders: Record = {}, - parseBody: boolean = true - ): Promise { + async post({ + relativePath, + data, + jsonOptions, + query, + requestHeaders, + parseBody, + }: { + relativePath: string; + data: any; + jsonOptions: utils.ParseJSONOptions; + query?: Query; + requestHeaders?: Record; + parseBody: boolean; + }): Promise { const fullHeaders = { 'content-type': 'application/json', - ...tolowerCaseKeys(requestHeaders), + ...tolowerCaseKeys(requestHeaders ?? {}), }; try { @@ -278,9 +298,14 @@ export class HTTPClient { fullHeaders ); - return HTTPClient.prepareResponse(res, 'application/json', parseBody); + return HTTPClient.prepareResponse( + res, + 'application/json', + parseBody, + jsonOptions + ); } catch (err) { - throw HTTPClient.prepareResponseError(err); + throw HTTPClient.prepareResponseError(err, jsonOptions); } } @@ -288,25 +313,44 @@ export class HTTPClient { * Send a DELETE request. * If no content-type present, adds the header "content-type: application/json" * and data is serialized in JSON (if not empty) + * @param options - The options to use for the request. */ - async delete( - relativePath: string, - data: any, - requestHeaders: Record = {}, - parseBody: boolean = true - ) { + async delete({ + relativePath, + data, + jsonOptions, + requestHeaders, + parseBody, + }: { + relativePath: string; + data: any; + jsonOptions: utils.ParseJSONOptions; + requestHeaders?: Record; + parseBody: boolean; + }) { const fullHeaders = { 'content-type': 'application/json', - ...tolowerCaseKeys(requestHeaders), + ...tolowerCaseKeys(requestHeaders ?? {}), }; - const res = await this.bc.delete( - relativePath, - HTTPClient.serializeData(data, fullHeaders), - undefined, - fullHeaders - ); + try { + const res = await this.bc.delete( + relativePath, + typeof data !== 'undefined' + ? HTTPClient.serializeData(data, fullHeaders) + : undefined, + undefined, + fullHeaders + ); - return HTTPClient.prepareResponse(res, 'application/json', parseBody); + return HTTPClient.prepareResponse( + res, + 'application/json', + parseBody, + jsonOptions + ); + } catch (err) { + throw HTTPClient.prepareResponseError(err, jsonOptions); + } } } diff --git a/src/client/kmd.ts b/src/client/kmd.ts index 472f6a696..1e9a09e21 100644 --- a/src/client/kmd.ts +++ b/src/client/kmd.ts @@ -3,6 +3,7 @@ import { bytesToBase64, coerceToBytes, } from '../encoding/binarydata.js'; +import IntDecoding from '../types/intDecoding.js'; import { Transaction } from '../transaction.js'; import { CustomTokenHeader, KMDTokenHeader } from './urlTokenBaseHTTPClient.js'; import ServiceClient from './v2/serviceClient.js'; @@ -17,12 +18,49 @@ export class KmdClient extends ServiceClient { super('X-KMD-API-Token', token, baseServer, port, headers); } + private async get(relativePath: string): Promise { + const res = await this.c.get({ + relativePath, + jsonOptions: { + // Using SAFE for all KMD endpoints because no integers in responses should ever be too big + intDecoding: IntDecoding.SAFE, + }, + parseBody: true, + }); + return res.body; + } + + private async delete(relativePath: string, data: any): Promise { + const res = await this.c.delete({ + relativePath, + data, + jsonOptions: { + // Using SAFE for all KMD endpoints because no integers in responses should ever be too big + intDecoding: IntDecoding.SAFE, + }, + parseBody: true, + }); + return res.body; + } + + private async post(relativePath: string, data: any): Promise { + const res = await this.c.post({ + relativePath, + data, + parseBody: true, + jsonOptions: { + // Using SAFE for all KMD endpoints because no integers in responses should ever be too big + intDecoding: IntDecoding.SAFE, + }, + }); + return res.body; + } + /** * version returns a VersionResponse containing a list of kmd API versions supported by this running kmd instance. */ async versions() { - const res = await this.c.get('/versions'); - return res.body; + return this.get('/versions'); } /** @@ -30,8 +68,7 @@ export class KmdClient extends ServiceClient { * returned from this endpoint, you can initialize a wallet handle with client.InitWalletHandle */ async listWallets() { - const res = await this.c.get('/v1/wallets'); - return res.body; + return this.get('/v1/wallets'); } /** @@ -56,8 +93,7 @@ export class KmdClient extends ServiceClient { wallet_password: walletPassword, master_derivation_key: bytesToBase64(walletMDK), }; - const res = await this.c.post('/v1/wallet', req); - return res.body; + return this.post('/v1/wallet', req); } /** @@ -76,8 +112,7 @@ export class KmdClient extends ServiceClient { wallet_id: walletID, wallet_password: walletPassword, }; - const res = await this.c.post('/v1/wallet/init', req); - return res.body; + return this.post('/v1/wallet/init', req); } /** @@ -89,8 +124,7 @@ export class KmdClient extends ServiceClient { const req = { wallet_handle_token: walletHandle, }; - const res = await this.c.post('/v1/wallet/release', req); - return res.body; + return this.post('/v1/wallet/release', req); } /** @@ -104,8 +138,7 @@ export class KmdClient extends ServiceClient { const req = { wallet_handle_token: walletHandle, }; - const res = await this.c.post('/v1/wallet/renew', req); - return res.body; + return this.post('/v1/wallet/renew', req); } /** @@ -125,8 +158,7 @@ export class KmdClient extends ServiceClient { wallet_password: walletPassword, wallet_name: newWalletName, }; - const res = await this.c.post('/v1/wallet/rename', req); - return res.body; + return this.post('/v1/wallet/rename', req); } /** @@ -138,8 +170,7 @@ export class KmdClient extends ServiceClient { const req = { wallet_handle_token: walletHandle, }; - const res = await this.c.post('/v1/wallet/info', req); - return res.body; + return this.post('/v1/wallet/info', req); } /** @@ -159,9 +190,9 @@ export class KmdClient extends ServiceClient { wallet_handle_token: walletHandle, wallet_password: walletPassword, }; - const res = await this.c.post('/v1/master-key/export', req); + const res = await this.post('/v1/master-key/export', req); return { - master_derivation_key: base64ToBytes(res.body.master_derivation_key), + master_derivation_key: base64ToBytes(res.master_derivation_key), }; } @@ -177,8 +208,7 @@ export class KmdClient extends ServiceClient { wallet_handle_token: walletHandle, private_key: bytesToBase64(secretKey), }; - const res = await this.c.post('/v1/key/import', req); - return res.body; + return this.post('/v1/key/import', req); } /** @@ -195,8 +225,8 @@ export class KmdClient extends ServiceClient { address: addr, wallet_password: walletPassword, }; - const res = await this.c.post('/v1/key/export', req); - return { private_key: base64ToBytes(res.body.private_key) }; + const res = await this.post('/v1/key/export', req); + return { private_key: base64ToBytes(res.private_key) }; } /** @@ -210,8 +240,7 @@ export class KmdClient extends ServiceClient { wallet_handle_token: walletHandle, display_mnemonic: false, }; - const res = await this.c.post('/v1/key', req); - return res.body; + return this.post('/v1/key', req); } /** @@ -231,8 +260,7 @@ export class KmdClient extends ServiceClient { address: addr, wallet_password: walletPassword, }; - const res = await this.c.delete('/v1/key', req); - return res.body; + return this.delete('/v1/key', req); } /** @@ -244,8 +272,7 @@ export class KmdClient extends ServiceClient { const req = { wallet_handle_token: walletHandle, }; - const res = await this.c.post('/v1/key/list', req); - return res.body; + return this.post('/v1/key/list', req); } /** @@ -267,12 +294,8 @@ export class KmdClient extends ServiceClient { wallet_password: walletPassword, transaction: bytesToBase64(transaction.toByte()), }; - const res = await this.c.post('/v1/transaction/sign', req); - - if (res.status === 200) { - return base64ToBytes(res.body.signed_transaction); - } - return res.body; + const res = await this.post('/v1/transaction/sign', req); + return base64ToBytes(res.signed_transaction); } /** @@ -299,12 +322,8 @@ export class KmdClient extends ServiceClient { transaction: bytesToBase64(transaction.toByte()), public_key: bytesToBase64(pk), }; - const res = await this.c.post('/v1/transaction/sign', req); - - if (res.status === 200) { - return base64ToBytes(res.body.signed_transaction); - } - return res.body; + const res = await this.post('/v1/transaction/sign', req); + return base64ToBytes(res.signed_transaction); } /** @@ -319,8 +338,7 @@ export class KmdClient extends ServiceClient { const req = { wallet_handle_token: walletHandle, }; - const res = await this.c.post('/v1/multisig/list', req); - return res.body; + return this.post('/v1/multisig/list', req); } /** @@ -345,8 +363,7 @@ export class KmdClient extends ServiceClient { threshold, pks, }; - const res = await this.c.post('/v1/multisig/import', req); - return res.body; + return this.post('/v1/multisig/import', req); } /** @@ -364,8 +381,7 @@ export class KmdClient extends ServiceClient { wallet_handle_token: walletHandle, address: addr, }; - const res = await this.c.post('/v1/multisig/export', req); - return res.body; + return this.post('/v1/multisig/export', req); } /** @@ -395,8 +411,7 @@ export class KmdClient extends ServiceClient { partial_multisig: partial, wallet_password: pw, }; - const res = await this.c.post('/v1/multisig/sign', req); - return res.body; + return this.post('/v1/multisig/sign', req); } /** @@ -417,7 +432,6 @@ export class KmdClient extends ServiceClient { address: addr, wallet_password: walletPassword, }; - const res = await this.c.delete('/v1/multisig', req); - return res.body; + return this.delete('/v1/multisig', req); } } diff --git a/src/client/v2/algod/accountApplicationInformation.ts b/src/client/v2/algod/accountApplicationInformation.ts index 676c19177..4460f14e5 100644 --- a/src/client/v2/algod/accountApplicationInformation.ts +++ b/src/client/v2/algod/accountApplicationInformation.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { AccountApplicationResponse } from './models/types.js'; import { Address } from '../../../encoding/address.js'; @@ -12,11 +11,10 @@ export default class AccountApplicationInformation extends JSONRequest< constructor( c: HTTPClient, - intDecoding: IntDecoding, account: string | Address, private applicationID: number ) { - super(c, intDecoding); + super(c); this.account = account.toString(); } diff --git a/src/client/v2/algod/accountAssetInformation.ts b/src/client/v2/algod/accountAssetInformation.ts index 2d6cad527..2494c43bf 100644 --- a/src/client/v2/algod/accountAssetInformation.ts +++ b/src/client/v2/algod/accountAssetInformation.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { AccountAssetResponse } from './models/types.js'; import { Address } from '../../../encoding/address.js'; @@ -12,11 +11,10 @@ export default class AccountAssetInformation extends JSONRequest< constructor( c: HTTPClient, - intDecoding: IntDecoding, account: string | Address, private assetID: number ) { - super(c, intDecoding); + super(c); this.account = account.toString(); } diff --git a/src/client/v2/algod/accountInformation.ts b/src/client/v2/algod/accountInformation.ts index 937186e37..838dc2245 100644 --- a/src/client/v2/algod/accountInformation.ts +++ b/src/client/v2/algod/accountInformation.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { Account } from './models/types.js'; import { Address } from '../../../encoding/address.js'; @@ -10,12 +9,8 @@ export default class AccountInformation extends JSONRequest< > { private account: string; - constructor( - c: HTTPClient, - intDecoding: IntDecoding, - account: string | Address - ) { - super(c, intDecoding); + constructor(c: HTTPClient, account: string | Address) { + super(c); this.account = account.toString(); } diff --git a/src/client/v2/algod/algod.ts b/src/client/v2/algod/algod.ts index 0370572b6..8f4e7cf06 100644 --- a/src/client/v2/algod/algod.ts +++ b/src/client/v2/algod/algod.ts @@ -155,7 +155,7 @@ export class AlgodClient extends ServiceClient { * @category GET */ accountInformation(account: string | Address) { - return new AccountInformation(this.c, this.intDecoding, account); + return new AccountInformation(this.c, account); } /** @@ -174,12 +174,7 @@ export class AlgodClient extends ServiceClient { * @category GET */ accountAssetInformation(account: string | Address, index: number) { - return new AccountAssetInformation( - this.c, - this.intDecoding, - account, - index - ); + return new AccountAssetInformation(this.c, account, index); } /** @@ -198,12 +193,7 @@ export class AlgodClient extends ServiceClient { * @category GET */ accountApplicationInformation(account: string | Address, index: number) { - return new AccountApplicationInformation( - this.c, - this.intDecoding, - account, - index - ); + return new AccountApplicationInformation(this.c, account, index); } /** @@ -237,7 +227,7 @@ export class AlgodClient extends ServiceClient { * @category GET */ getBlockHash(roundNumber: number) { - return new GetBlockHash(this.c, this.intDecoding, roundNumber); + return new GetBlockHash(this.c, roundNumber); } /** @@ -254,7 +244,7 @@ export class AlgodClient extends ServiceClient { * @category GET */ getBlockTxids(roundNumber: number) { - return new GetBlockTxids(this.c, this.intDecoding, roundNumber); + return new GetBlockTxids(this.c, roundNumber); } /** @@ -349,7 +339,7 @@ export class AlgodClient extends ServiceClient { * @category GET */ status() { - return new Status(this.c, this.intDecoding); + return new Status(this.c); } /** @@ -366,7 +356,7 @@ export class AlgodClient extends ServiceClient { * @category GET */ statusAfterBlock(round: number) { - return new StatusAfterBlock(this.c, this.intDecoding, round); + return new StatusAfterBlock(this.c, round); } /** @@ -407,7 +397,7 @@ export class AlgodClient extends ServiceClient { * @category GET */ supply() { - return new Supply(this.c, this.intDecoding); + return new Supply(this.c); } /** @@ -478,7 +468,7 @@ export class AlgodClient extends ServiceClient { * @category GET */ getAssetByID(index: number | bigint) { - return new GetAssetByID(this.c, this.intDecoding, index); + return new GetAssetByID(this.c, index); } /** @@ -496,7 +486,7 @@ export class AlgodClient extends ServiceClient { * @category GET */ getApplicationByID(index: number | bigint) { - return new GetApplicationByID(this.c, this.intDecoding, index); + return new GetApplicationByID(this.c, index); } /** @@ -515,12 +505,7 @@ export class AlgodClient extends ServiceClient { * @category GET */ getApplicationBoxByName(index: number, boxName: Uint8Array) { - return new GetApplicationBoxByName( - this.c, - this.intDecoding, - index, - boxName - ); + return new GetApplicationBoxByName(this.c, index, boxName); } /** @@ -538,7 +523,7 @@ export class AlgodClient extends ServiceClient { * @category GET */ getApplicationBoxes(index: number) { - return new GetApplicationBoxes(this.c, this.intDecoding, index); + return new GetApplicationBoxes(this.c, index); } /** @@ -553,7 +538,7 @@ export class AlgodClient extends ServiceClient { * @category GET */ genesis() { - return new Genesis(this.c, this.intDecoding); + return new Genesis(this.c); } /** @@ -572,7 +557,7 @@ export class AlgodClient extends ServiceClient { * @category GET */ getTransactionProof(round: number, txID: string) { - return new GetTransactionProof(this.c, this.intDecoding, round, txID); + return new GetTransactionProof(this.c, round, txID); } /** @@ -588,7 +573,7 @@ export class AlgodClient extends ServiceClient { * @param round */ getLightBlockHeaderProof(round: number) { - return new LightBlockHeaderProof(this.c, this.intDecoding, round); + return new LightBlockHeaderProof(this.c, round); } /** @@ -604,7 +589,7 @@ export class AlgodClient extends ServiceClient { * @param round */ getStateProof(round: number) { - return new StateProof(this.c, this.intDecoding, round); + return new StateProof(this.c, round); } /** @@ -694,7 +679,7 @@ export class AlgodClient extends ServiceClient { * @category POST */ setBlockOffsetTimestamp(offset: number) { - return new SetBlockOffsetTimestamp(this.c, this.intDecoding, offset); + return new SetBlockOffsetTimestamp(this.c, offset); } /** @@ -709,7 +694,7 @@ export class AlgodClient extends ServiceClient { * @category GET */ getBlockOffsetTimestamp() { - return new GetBlockOffsetTimestamp(this.c, this.intDecoding); + return new GetBlockOffsetTimestamp(this.c); } /** @@ -726,7 +711,7 @@ export class AlgodClient extends ServiceClient { * @category POST */ setSyncRound(round: number) { - return new SetSyncRound(this.c, this.intDecoding, round); + return new SetSyncRound(this.c, round); } /** @@ -741,7 +726,7 @@ export class AlgodClient extends ServiceClient { * @category DELETE */ unsetSyncRound() { - return new UnsetSyncRound(this.c, this.intDecoding); + return new UnsetSyncRound(this.c); } /** @@ -756,7 +741,7 @@ export class AlgodClient extends ServiceClient { * @category GET */ getSyncRound() { - return new GetSyncRound(this.c, this.intDecoding); + return new GetSyncRound(this.c); } /** @@ -771,7 +756,7 @@ export class AlgodClient extends ServiceClient { * @category GET */ ready() { - return new Ready(this.c, this.intDecoding); + return new Ready(this.c); } /** @@ -788,11 +773,7 @@ export class AlgodClient extends ServiceClient { * @category GET */ getLedgerStateDeltaForTransactionGroup(id: string) { - return new GetLedgerStateDeltaForTransactionGroup( - this.c, - this.intDecoding, - id - ); + return new GetLedgerStateDeltaForTransactionGroup(this.c, id); } /** @@ -809,7 +790,7 @@ export class AlgodClient extends ServiceClient { * @category GET */ getLedgerStateDelta(round: number) { - return new GetLedgerStateDelta(this.c, this.intDecoding, round); + return new GetLedgerStateDelta(this.c, round); } /** @@ -826,10 +807,6 @@ export class AlgodClient extends ServiceClient { * @category GET */ getTransactionGroupLedgerStateDeltasForRound(round: number) { - return new GetTransactionGroupLedgerStateDeltasForRound( - this.c, - this.intDecoding, - round - ); + return new GetTransactionGroupLedgerStateDeltasForRound(this.c, round); } } diff --git a/src/client/v2/algod/compile.ts b/src/client/v2/algod/compile.ts index dc004d8a4..c692baf67 100644 --- a/src/client/v2/algod/compile.ts +++ b/src/client/v2/algod/compile.ts @@ -1,4 +1,5 @@ import { coerceToBytes } from '../../../encoding/binarydata.js'; +import IntDecoding from '../../../types/intDecoding.js'; import { HTTPClient } from '../../client.js'; import { CompileResponse } from './models/types.js'; import JSONRequest from '../jsonrequest.js'; @@ -46,12 +47,14 @@ export default class Compile extends JSONRequest< */ async do(headers = {}) { const txHeaders = setHeaders(headers); - const res = await this.c.post( - this.path(), - coerceToBytes(this.source), - this.query, - txHeaders - ); + const res = await this.c.post({ + relativePath: this.path(), + data: coerceToBytes(this.source), + parseBody: true, + jsonOptions: { intDecoding: IntDecoding.BIGINT }, + query: this.query, + requestHeaders: txHeaders, + }); return res.body; } diff --git a/src/client/v2/algod/disassemble.ts b/src/client/v2/algod/disassemble.ts index c9eb53f5f..143870d23 100644 --- a/src/client/v2/algod/disassemble.ts +++ b/src/client/v2/algod/disassemble.ts @@ -1,4 +1,5 @@ import { coerceToBytes } from '../../../encoding/binarydata.js'; +import IntDecoding from '../../../types/intDecoding.js'; import { HTTPClient } from '../../client.js'; import { DisassembleResponse } from './models/types.js'; import JSONRequest from '../jsonrequest.js'; @@ -41,12 +42,14 @@ export default class Disassemble extends JSONRequest< */ async do(headers = {}) { const txHeaders = setHeaders(headers); - const res = await this.c.post( - this.path(), - coerceToBytes(this.source), - this.query, - txHeaders - ); + const res = await this.c.post({ + relativePath: this.path(), + data: coerceToBytes(this.source), + parseBody: true, + jsonOptions: { intDecoding: IntDecoding.BIGINT }, + query: this.query, + requestHeaders: txHeaders, + }); return res.body; } diff --git a/src/client/v2/algod/dryrun.ts b/src/client/v2/algod/dryrun.ts index a3dbf3ceb..c57de2f71 100644 --- a/src/client/v2/algod/dryrun.ts +++ b/src/client/v2/algod/dryrun.ts @@ -1,4 +1,5 @@ import * as encoding from '../../../encoding/encoding.js'; +import IntDecoding from '../../../types/intDecoding.js'; import { HTTPClient } from '../../client.js'; import JSONRequest from '../jsonrequest.js'; import { setHeaders } from './compile.js'; @@ -27,7 +28,13 @@ export default class Dryrun extends JSONRequest< */ async do(headers = {}) { const txHeaders = setHeaders(headers); - const res = await this.c.post(this.path(), this.blob, undefined, txHeaders); + const res = await this.c.post({ + relativePath: this.path(), + data: this.blob, + parseBody: true, + jsonOptions: { intDecoding: IntDecoding.BIGINT }, + requestHeaders: txHeaders, + }); return this.prepare(res.body); } diff --git a/src/client/v2/algod/getApplicationBoxByName.ts b/src/client/v2/algod/getApplicationBoxByName.ts index 7e139f8d4..56e802412 100644 --- a/src/client/v2/algod/getApplicationBoxByName.ts +++ b/src/client/v2/algod/getApplicationBoxByName.ts @@ -1,5 +1,4 @@ import { bytesToBase64 } from '../../../encoding/binarydata.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { HTTPClient } from '../../client.js'; import JSONRequest from '../jsonrequest.js'; import { Box } from './models/types.js'; @@ -25,11 +24,10 @@ export default class GetApplicationBoxByName extends JSONRequest< > { constructor( c: HTTPClient, - intDecoding: IntDecoding, private index: number, name: Uint8Array ) { - super(c, intDecoding); + super(c); // Encode name in base64 format and append the encoding prefix. const encodedName = bytesToBase64(name); this.query.name = encodeURI(`b64:${encodedName}`); diff --git a/src/client/v2/algod/getApplicationBoxes.ts b/src/client/v2/algod/getApplicationBoxes.ts index 14bdcea3b..04bed7b29 100644 --- a/src/client/v2/algod/getApplicationBoxes.ts +++ b/src/client/v2/algod/getApplicationBoxes.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { BoxesResponse } from './models/types.js'; /** @@ -23,10 +22,9 @@ export default class GetApplicationBoxes extends JSONRequest< > { constructor( c: HTTPClient, - intDecoding: IntDecoding, private index: number ) { - super(c, intDecoding); + super(c); this.query.max = 0; } diff --git a/src/client/v2/algod/getApplicationByID.ts b/src/client/v2/algod/getApplicationByID.ts index c9bbc1f9d..53cd8f465 100644 --- a/src/client/v2/algod/getApplicationByID.ts +++ b/src/client/v2/algod/getApplicationByID.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { Application } from './models/types.js'; export default class GetApplicationByID extends JSONRequest< @@ -9,10 +8,9 @@ export default class GetApplicationByID extends JSONRequest< > { constructor( c: HTTPClient, - intDecoding: IntDecoding, private index: number | bigint ) { - super(c, intDecoding); + super(c); } path() { diff --git a/src/client/v2/algod/getAssetByID.ts b/src/client/v2/algod/getAssetByID.ts index ffb89f6c7..6073332a4 100644 --- a/src/client/v2/algod/getAssetByID.ts +++ b/src/client/v2/algod/getAssetByID.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { Asset } from './models/types.js'; export default class GetAssetByID extends JSONRequest< @@ -9,10 +8,9 @@ export default class GetAssetByID extends JSONRequest< > { constructor( c: HTTPClient, - intDecoding: IntDecoding, private index: number | bigint ) { - super(c, intDecoding); + super(c); } path() { diff --git a/src/client/v2/algod/getBlockHash.ts b/src/client/v2/algod/getBlockHash.ts index b6d2c85eb..ee50650da 100644 --- a/src/client/v2/algod/getBlockHash.ts +++ b/src/client/v2/algod/getBlockHash.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { BlockHashResponse } from './models/types.js'; export default class GetBlockHash extends JSONRequest< @@ -9,8 +8,8 @@ export default class GetBlockHash extends JSONRequest< > { round: number | bigint; - constructor(c: HTTPClient, intDecoding: IntDecoding, roundNumber: number) { - super(c, intDecoding); + constructor(c: HTTPClient, roundNumber: number) { + super(c); this.round = roundNumber; } diff --git a/src/client/v2/algod/getBlockTxids.ts b/src/client/v2/algod/getBlockTxids.ts index fdeca9df2..bba9df96c 100644 --- a/src/client/v2/algod/getBlockTxids.ts +++ b/src/client/v2/algod/getBlockTxids.ts @@ -1,12 +1,11 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; export default class GetBlockTxids extends JSONRequest { round: number; - constructor(c: HTTPClient, intDecoding: IntDecoding, roundNumber: number) { - super(c, intDecoding); + constructor(c: HTTPClient, roundNumber: number) { + super(c); if (!Number.isInteger(roundNumber)) throw Error('roundNumber should be an integer'); this.round = roundNumber; diff --git a/src/client/v2/algod/getLedgerStateDelta.ts b/src/client/v2/algod/getLedgerStateDelta.ts index 168eb69f1..0e722ed95 100644 --- a/src/client/v2/algod/getLedgerStateDelta.ts +++ b/src/client/v2/algod/getLedgerStateDelta.ts @@ -1,14 +1,12 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; export default class GetLedgerStateDelta extends JSONRequest { constructor( c: HTTPClient, - intDecoding: IntDecoding, private round: number ) { - super(c, intDecoding); + super(c); this.query = { format: 'json' }; } diff --git a/src/client/v2/algod/getLedgerStateDeltaForTransactionGroup.ts b/src/client/v2/algod/getLedgerStateDeltaForTransactionGroup.ts index 3a4e404cd..bd3738e43 100644 --- a/src/client/v2/algod/getLedgerStateDeltaForTransactionGroup.ts +++ b/src/client/v2/algod/getLedgerStateDeltaForTransactionGroup.ts @@ -1,14 +1,12 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; export default class GetLedgerStateDeltaForTransactionGroup extends JSONRequest { constructor( c: HTTPClient, - intDecoding: IntDecoding, private id: string ) { - super(c, intDecoding); + super(c); this.query = { format: 'json' }; } diff --git a/src/client/v2/algod/getTransactionGroupLedgerStateDeltasForRound.ts b/src/client/v2/algod/getTransactionGroupLedgerStateDeltasForRound.ts index 2563b77a7..2d8e93cd4 100644 --- a/src/client/v2/algod/getTransactionGroupLedgerStateDeltasForRound.ts +++ b/src/client/v2/algod/getTransactionGroupLedgerStateDeltasForRound.ts @@ -1,7 +1,6 @@ import JSONRequest from '../jsonrequest.js'; import { TransactionGroupLedgerStateDeltasForRoundResponse } from './models/types.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; export default class GetTransactionGroupLedgerStateDeltasForRound extends JSONRequest< TransactionGroupLedgerStateDeltasForRoundResponse, @@ -9,10 +8,9 @@ export default class GetTransactionGroupLedgerStateDeltasForRound extends JSONRe > { constructor( c: HTTPClient, - intDecoding: IntDecoding, private round: number ) { - super(c, intDecoding); + super(c); this.query = { format: 'json' }; } diff --git a/src/client/v2/algod/getTransactionProof.ts b/src/client/v2/algod/getTransactionProof.ts index 49122390a..726be17c6 100644 --- a/src/client/v2/algod/getTransactionProof.ts +++ b/src/client/v2/algod/getTransactionProof.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { TransactionProofResponse } from './models/types.js'; export default class GetTransactionProof extends JSONRequest< @@ -9,11 +8,10 @@ export default class GetTransactionProof extends JSONRequest< > { constructor( c: HTTPClient, - intDecoding: IntDecoding, private round: number, private txID: string ) { - super(c, intDecoding); + super(c); } path() { diff --git a/src/client/v2/algod/healthCheck.ts b/src/client/v2/algod/healthCheck.ts index 6c55f1693..7db804e84 100644 --- a/src/client/v2/algod/healthCheck.ts +++ b/src/client/v2/algod/healthCheck.ts @@ -1,4 +1,5 @@ import JSONRequest from '../jsonrequest.js'; +import IntDecoding from '../../../types/intDecoding.js'; /** * healthCheck returns an empty object iff the node is running @@ -10,7 +11,12 @@ export default class HealthCheck extends JSONRequest { } async do(headers = {}) { - const res = await this.c.get(this.path(), {}, headers); + const res = await this.c.get({ + relativePath: this.path(), + parseBody: true, + jsonOptions: { intDecoding: IntDecoding.BIGINT }, + requestHeaders: headers, + }); if (!res.ok) { throw new Error(`Health response: ${res.status}`); } diff --git a/src/client/v2/algod/lightBlockHeaderProof.ts b/src/client/v2/algod/lightBlockHeaderProof.ts index 723f6ee67..7748e0a4e 100644 --- a/src/client/v2/algod/lightBlockHeaderProof.ts +++ b/src/client/v2/algod/lightBlockHeaderProof.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { LightBlockHeaderProof as LBHP } from './models/types.js'; export default class LightBlockHeaderProof extends JSONRequest< @@ -9,10 +8,9 @@ export default class LightBlockHeaderProof extends JSONRequest< > { constructor( c: HTTPClient, - intDecoding: IntDecoding, private round: number ) { - super(c, intDecoding); + super(c); } path() { diff --git a/src/client/v2/algod/models/types.ts b/src/client/v2/algod/models/types.ts index 67f0fb97a..3b21b91c6 100644 --- a/src/client/v2/algod/models/types.ts +++ b/src/client/v2/algod/models/types.ts @@ -3,6 +3,7 @@ */ /* eslint-disable no-use-before-define */ +import { ensureBigInt, ensureSafeInteger } from '../../../../utils/utils.js'; import { base64ToBytes } from '../../../../encoding/binarydata.js'; import BlockHeader from '../../../../types/blockHeader.js'; import { EncodedSignedTransaction } from '../../../../types/transactions/encoded.js'; @@ -22,34 +23,34 @@ export class Account extends BaseModel { /** * (algo) total number of MicroAlgos in the account */ - public amount: number | bigint; + public amount: bigint; /** * specifies the amount of MicroAlgos in the account, without the pending rewards. */ - public amountWithoutPendingRewards: number | bigint; + public amountWithoutPendingRewards: bigint; /** * MicroAlgo balance required by the account. * The requirement grows based on asset and application usage. */ - public minBalance: number | bigint; + public minBalance: bigint; /** * amount of MicroAlgos of pending rewards in this account. */ - public pendingRewards: number | bigint; + public pendingRewards: bigint; /** * (ern) total rewards of MicroAlgos the account has received, including pending * rewards. */ - public rewards: number | bigint; + public rewards: bigint; /** * The round for which this information is relevant. */ - public round: number | bigint; + public round: bigint; /** * (onl) delegation status of the account's MicroAlgos @@ -65,23 +66,23 @@ export class Account extends BaseModel { * The count of all applications that have been opted in, equivalent to the count * of application local data (AppLocalState objects) stored in this account. */ - public totalAppsOptedIn: number | bigint; + public totalAppsOptedIn: number; /** * The count of all assets that have been opted in, equivalent to the count of * AssetHolding objects held by this account. */ - public totalAssetsOptedIn: number | bigint; + public totalAssetsOptedIn: number; /** * The count of all apps (AppParams objects) created by this account. */ - public totalCreatedApps: number | bigint; + public totalCreatedApps: number; /** * The count of all assets (AssetParams objects) created by this account. */ - public totalCreatedAssets: number | bigint; + public totalCreatedAssets: number; /** * (appl) applications local data stored in this account. @@ -92,7 +93,7 @@ export class Account extends BaseModel { /** * (teap) the sum of all extra application program pages for this account. */ - public appsTotalExtraPages?: number | bigint; + public appsTotalExtraPages?: number; /** * (tsch) stores the sum of all of the local schemas and global schemas in this @@ -137,7 +138,7 @@ export class Account extends BaseModel { * (ebase) used as part of the rewards computation. Only applicable to accounts * which are participating. */ - public rewardBase?: number | bigint; + public rewardBase?: bigint; /** * Indicates what type of signature is used by this account, must be one of: @@ -151,12 +152,12 @@ export class Account extends BaseModel { * (tbxb) The total number of bytes used by this account's app's box keys and * values. */ - public totalBoxBytes?: number | bigint; + public totalBoxBytes?: number; /** * (tbx) The number of existing boxes created by this account's app. */ - public totalBoxes?: number | bigint; + public totalBoxes?: number; /** * Creates a new `Account` object. @@ -262,29 +263,41 @@ export class Account extends BaseModel { }) { super(); this.address = address; - this.amount = amount; - this.amountWithoutPendingRewards = amountWithoutPendingRewards; - this.minBalance = minBalance; - this.pendingRewards = pendingRewards; - this.rewards = rewards; - this.round = round; + this.amount = ensureBigInt(amount); + this.amountWithoutPendingRewards = ensureBigInt( + amountWithoutPendingRewards + ); + this.minBalance = ensureBigInt(minBalance); + this.pendingRewards = ensureBigInt(pendingRewards); + this.rewards = ensureBigInt(rewards); + this.round = ensureBigInt(round); this.status = status; - this.totalAppsOptedIn = totalAppsOptedIn; - this.totalAssetsOptedIn = totalAssetsOptedIn; - this.totalCreatedApps = totalCreatedApps; - this.totalCreatedAssets = totalCreatedAssets; + this.totalAppsOptedIn = ensureSafeInteger(totalAppsOptedIn); + this.totalAssetsOptedIn = ensureSafeInteger(totalAssetsOptedIn); + this.totalCreatedApps = ensureSafeInteger(totalCreatedApps); + this.totalCreatedAssets = ensureSafeInteger(totalCreatedAssets); this.appsLocalState = appsLocalState; - this.appsTotalExtraPages = appsTotalExtraPages; + this.appsTotalExtraPages = + typeof appsTotalExtraPages === 'undefined' + ? undefined + : ensureSafeInteger(appsTotalExtraPages); this.appsTotalSchema = appsTotalSchema; this.assets = assets; this.authAddr = authAddr; this.createdApps = createdApps; this.createdAssets = createdAssets; this.participation = participation; - this.rewardBase = rewardBase; + this.rewardBase = + typeof rewardBase === 'undefined' ? undefined : ensureBigInt(rewardBase); this.sigType = sigType; - this.totalBoxBytes = totalBoxBytes; - this.totalBoxes = totalBoxes; + this.totalBoxBytes = + typeof totalBoxBytes === 'undefined' + ? undefined + : ensureSafeInteger(totalBoxBytes); + this.totalBoxes = + typeof totalBoxes === 'undefined' + ? undefined + : ensureSafeInteger(totalBoxes); this.attribute_map = { address: 'address', @@ -417,7 +430,7 @@ export class AccountApplicationResponse extends BaseModel { /** * The round for which this information is relevant. */ - public round: number | bigint; + public round: bigint; /** * (appl) the application local data stored in this account. @@ -451,7 +464,7 @@ export class AccountApplicationResponse extends BaseModel { createdApp?: ApplicationParams; }) { super(); - this.round = round; + this.round = ensureBigInt(round); this.appLocalState = appLocalState; this.createdApp = createdApp; @@ -493,7 +506,7 @@ export class AccountAssetResponse extends BaseModel { /** * The round for which this information is relevant. */ - public round: number | bigint; + public round: bigint; /** * (asset) Details about the asset held by this account. @@ -525,7 +538,7 @@ export class AccountAssetResponse extends BaseModel { createdAsset?: AssetParams; }) { super(); - this.round = round; + this.round = ensureBigInt(round); this.assetHolding = assetHolding; this.createdAsset = createdAsset; @@ -571,17 +584,17 @@ export class AccountParticipation extends BaseModel { /** * (voteFst) First round for which this participation is valid. */ - public voteFirstValid: number | bigint; + public voteFirstValid: bigint; /** * (voteKD) Number of subkeys in each batch of participation keys. */ - public voteKeyDilution: number | bigint; + public voteKeyDilution: bigint; /** * (voteLst) Last round for which this participation is valid. */ - public voteLastValid: number | bigint; + public voteLastValid: bigint; /** * (vote) root participation public key (if any) currently registered for this @@ -624,9 +637,9 @@ export class AccountParticipation extends BaseModel { typeof selectionParticipationKey === 'string' ? base64ToBytes(selectionParticipationKey) : selectionParticipationKey; - this.voteFirstValid = voteFirstValid; - this.voteKeyDilution = voteKeyDilution; - this.voteLastValid = voteLastValid; + this.voteFirstValid = ensureBigInt(voteFirstValid); + this.voteKeyDilution = ensureBigInt(voteKeyDilution); + this.voteLastValid = ensureBigInt(voteLastValid); this.voteParticipationKey = typeof voteParticipationKey === 'string' ? base64ToBytes(voteParticipationKey) @@ -740,7 +753,7 @@ export class Application extends BaseModel { /** * (appidx) application index. */ - public id: number | bigint; + public id: bigint; /** * (appparams) application parameters. @@ -760,7 +773,7 @@ export class Application extends BaseModel { params: ApplicationParams; }) { super(); - this.id = id; + this.id = ensureBigInt(id); this.params = params; this.attribute_map = { @@ -792,7 +805,7 @@ export class ApplicationInitialStates extends BaseModel { /** * Application index. */ - public id: number | bigint; + public id: bigint; /** * An application's global/local/box state. @@ -828,7 +841,7 @@ export class ApplicationInitialStates extends BaseModel { appLocals?: ApplicationKVStorage[]; }) { super(); - this.id = id; + this.id = ensureBigInt(id); this.appBoxes = appBoxes; this.appGlobals = appGlobals; this.appLocals = appLocals; @@ -926,7 +939,7 @@ export class ApplicationLocalReference extends BaseModel { /** * Application ID of the local state application. */ - public app: number | bigint; + public app: bigint; /** * Creates a new `ApplicationLocalReference` object. @@ -936,7 +949,7 @@ export class ApplicationLocalReference extends BaseModel { constructor({ account, app }: { account: string; app: number | bigint }) { super(); this.account = account; - this.app = app; + this.app = ensureBigInt(app); this.attribute_map = { account: 'account', @@ -968,7 +981,7 @@ export class ApplicationLocalState extends BaseModel { /** * The application which this local state is for. */ - public id: number | bigint; + public id: bigint; /** * (hsch) schema. @@ -996,7 +1009,7 @@ export class ApplicationLocalState extends BaseModel { keyValue?: TealKeyValue[]; }) { super(); - this.id = id; + this.id = ensureBigInt(id); this.schema = schema; this.keyValue = keyValue; @@ -1051,7 +1064,7 @@ export class ApplicationParams extends BaseModel { /** * (epp) the amount of extra program pages available to this app. */ - public extraProgramPages?: number | bigint; + public extraProgramPages?: number; /** * (gs) global state @@ -1106,7 +1119,10 @@ export class ApplicationParams extends BaseModel { ? base64ToBytes(clearStateProgram) : clearStateProgram; this.creator = creator; - this.extraProgramPages = extraProgramPages; + this.extraProgramPages = + typeof extraProgramPages === 'undefined' + ? undefined + : ensureSafeInteger(extraProgramPages); this.globalState = globalState; this.globalStateSchema = globalStateSchema; this.localStateSchema = localStateSchema; @@ -1265,34 +1281,34 @@ export class ApplicationStateOperation extends BaseModel { */ export class ApplicationStateSchema extends BaseModel { /** - * (nui) num of uints. + * (nbs) num of byte slices. */ - public numUint: number | bigint; + public numByteSlice: number; /** - * (nbs) num of byte slices. + * (nui) num of uints. */ - public numByteSlice: number | bigint; + public numUint: number; /** * Creates a new `ApplicationStateSchema` object. - * @param numUint - (nui) num of uints. * @param numByteSlice - (nbs) num of byte slices. + * @param numUint - (nui) num of uints. */ constructor({ - numUint, numByteSlice, + numUint, }: { - numUint: number | bigint; numByteSlice: number | bigint; + numUint: number | bigint; }) { super(); - this.numUint = numUint; - this.numByteSlice = numByteSlice; + this.numByteSlice = ensureSafeInteger(numByteSlice); + this.numUint = ensureSafeInteger(numUint); this.attribute_map = { - numUint: 'num-uint', numByteSlice: 'num-byte-slice', + numUint: 'num-uint', }; } @@ -1301,15 +1317,15 @@ export class ApplicationStateSchema extends BaseModel { data: Record ): ApplicationStateSchema { /* eslint-disable dot-notation */ - if (typeof data['num-uint'] === 'undefined') - throw new Error(`Response is missing required field 'num-uint': ${data}`); if (typeof data['num-byte-slice'] === 'undefined') throw new Error( `Response is missing required field 'num-byte-slice': ${data}` ); + if (typeof data['num-uint'] === 'undefined') + throw new Error(`Response is missing required field 'num-uint': ${data}`); return new ApplicationStateSchema({ - numUint: data['num-uint'], numByteSlice: data['num-byte-slice'], + numUint: data['num-uint'], }); /* eslint-enable dot-notation */ } @@ -1322,7 +1338,7 @@ export class Asset extends BaseModel { /** * unique asset identifier */ - public index: number | bigint; + public index: bigint; /** * AssetParams specifies the parameters for an asset. @@ -1348,7 +1364,7 @@ export class Asset extends BaseModel { params: AssetParams; }) { super(); - this.index = index; + this.index = ensureBigInt(index); this.params = params; this.attribute_map = { @@ -1381,12 +1397,12 @@ export class AssetHolding extends BaseModel { /** * (a) number of units held. */ - public amount: number | bigint; + public amount: bigint; /** * Asset ID of the holding. */ - public assetId: number | bigint; + public assetId: bigint; /** * (f) whether or not the holding is frozen. @@ -1409,8 +1425,8 @@ export class AssetHolding extends BaseModel { isFrozen: boolean; }) { super(); - this.amount = amount; - this.assetId = assetId; + this.amount = ensureBigInt(amount); + this.assetId = ensureBigInt(assetId); this.isFrozen = isFrozen; this.attribute_map = { @@ -1452,7 +1468,7 @@ export class AssetHoldingReference extends BaseModel { /** * Asset ID of the holding. */ - public asset: number | bigint; + public asset: bigint; /** * Creates a new `AssetHoldingReference` object. @@ -1462,7 +1478,7 @@ export class AssetHoldingReference extends BaseModel { constructor({ account, asset }: { account: string; asset: number | bigint }) { super(); this.account = account; - this.asset = asset; + this.asset = ensureBigInt(asset); this.attribute_map = { account: 'account', @@ -1507,12 +1523,12 @@ export class AssetParams extends BaseModel { * tenths. If 2, the base unit of the asset is in hundredths, and so on. This value * must be between 0 and 19 (inclusive). */ - public decimals: number | bigint; + public decimals: number; /** * (t) The total number of units of this asset. */ - public total: number | bigint; + public total: bigint; /** * (c) Address of account used to clawback holdings of this asset. If empty, @@ -1644,8 +1660,8 @@ export class AssetParams extends BaseModel { }) { super(); this.creator = creator; - this.decimals = decimals; - this.total = total; + this.decimals = ensureSafeInteger(decimals); + this.total = ensureBigInt(total); this.clawback = clawback; this.defaultFrozen = defaultFrozen; this.freeze = freeze; @@ -1764,7 +1780,7 @@ export class AvmValue extends BaseModel { /** * value type. Value `1` refers to **bytes**, value `2` refers to **uint64** */ - public type: number | bigint; + public type: number; /** * bytes value. @@ -1774,7 +1790,7 @@ export class AvmValue extends BaseModel { /** * uint value. */ - public uint?: number | bigint; + public uint?: bigint; /** * Creates a new `AvmValue` object. @@ -1792,9 +1808,9 @@ export class AvmValue extends BaseModel { uint?: number | bigint; }) { super(); - this.type = type; + this.type = ensureSafeInteger(type); this.bytes = typeof bytes === 'string' ? base64ToBytes(bytes) : bytes; - this.uint = uint; + this.uint = typeof uint === 'undefined' ? undefined : ensureBigInt(uint); this.attribute_map = { type: 'type', @@ -1952,7 +1968,7 @@ export class Box extends BaseModel { /** * The round for which this information is relevant */ - public round: number | bigint; + public round: bigint; /** * (value) box value, base64 encoded. @@ -1976,7 +1992,7 @@ export class Box extends BaseModel { }) { super(); this.name = typeof name === 'string' ? base64ToBytes(name) : name; - this.round = round; + this.round = ensureBigInt(round); this.value = typeof value === 'string' ? base64ToBytes(value) : value; this.attribute_map = { @@ -2045,7 +2061,7 @@ export class BoxReference extends BaseModel { /** * Application ID which this box belongs to */ - public app: number | bigint; + public app: bigint; /** * Base64 encoded box name @@ -2065,7 +2081,7 @@ export class BoxReference extends BaseModel { name: string | Uint8Array; }) { super(); - this.app = app; + this.app = ensureBigInt(app); this.name = typeof name === 'string' ? base64ToBytes(name) : name; this.attribute_map = { @@ -2125,15 +2141,15 @@ export class BoxesResponse extends BaseModel { export class BuildVersion extends BaseModel { public branch: string; - public buildNumber: number | bigint; + public buildNumber: number; public channel: string; public commitHash: string; - public major: number | bigint; + public major: number; - public minor: number | bigint; + public minor: number; /** * Creates a new `BuildVersion` object. @@ -2161,11 +2177,11 @@ export class BuildVersion extends BaseModel { }) { super(); this.branch = branch; - this.buildNumber = buildNumber; + this.buildNumber = ensureSafeInteger(buildNumber); this.channel = channel; this.commitHash = commitHash; - this.major = major; - this.minor = minor; + this.major = ensureSafeInteger(major); + this.minor = ensureSafeInteger(minor); this.attribute_map = { branch: 'branch', @@ -2317,7 +2333,7 @@ export class DryrunRequest extends BaseModel { * LatestTimestamp is available to some TEAL scripts. Defaults to the latest * confirmed timestamp this algod is attached to. */ - public latestTimestamp: number | bigint; + public latestTimestamp: number; /** * ProtocolVersion specifies a specific version string to operate under, otherwise @@ -2329,7 +2345,7 @@ export class DryrunRequest extends BaseModel { * Round is available to some TEAL scripts. Defaults to the current round on the * network this algod is attached to. */ - public round: number | bigint; + public round: bigint; public sources: DryrunSource[]; @@ -2368,9 +2384,9 @@ export class DryrunRequest extends BaseModel { super(); this.accounts = accounts; this.apps = apps; - this.latestTimestamp = latestTimestamp; + this.latestTimestamp = ensureSafeInteger(latestTimestamp); this.protocolVersion = protocolVersion; - this.round = round; + this.round = ensureBigInt(round); this.sources = sources; this.txns = txns; @@ -2494,6 +2510,8 @@ export class DryrunResponse extends BaseModel { * transactions or application state. */ export class DryrunSource extends BaseModel { + public appIndex: bigint; + /** * FieldName is what kind of sources this is. If lsig then it goes into the * transactions[this.TxnIndex].LogicSig. If approv or clearp it goes into the @@ -2503,47 +2521,49 @@ export class DryrunSource extends BaseModel { public source: string; - public txnIndex: number | bigint; - - public appIndex: number | bigint; + public txnIndex: number; /** * Creates a new `DryrunSource` object. + * @param appIndex - * @param fieldName - FieldName is what kind of sources this is. If lsig then it goes into the * transactions[this.TxnIndex].LogicSig. If approv or clearp it goes into the * Approval Program or Clear State Program of application[this.AppIndex]. * @param source - * @param txnIndex - - * @param appIndex - */ constructor({ + appIndex, fieldName, source, txnIndex, - appIndex, }: { + appIndex: number | bigint; fieldName: string; source: string; txnIndex: number | bigint; - appIndex: number | bigint; }) { super(); + this.appIndex = ensureBigInt(appIndex); this.fieldName = fieldName; this.source = source; - this.txnIndex = txnIndex; - this.appIndex = appIndex; + this.txnIndex = ensureSafeInteger(txnIndex); this.attribute_map = { + appIndex: 'app-index', fieldName: 'field-name', source: 'source', txnIndex: 'txn-index', - appIndex: 'app-index', }; } // eslint-disable-next-line camelcase static from_obj_for_encoding(data: Record): DryrunSource { /* eslint-disable dot-notation */ + if (typeof data['app-index'] === 'undefined') + throw new Error( + `Response is missing required field 'app-index': ${data}` + ); if (typeof data['field-name'] === 'undefined') throw new Error( `Response is missing required field 'field-name': ${data}` @@ -2554,15 +2574,11 @@ export class DryrunSource extends BaseModel { throw new Error( `Response is missing required field 'txn-index': ${data}` ); - if (typeof data['app-index'] === 'undefined') - throw new Error( - `Response is missing required field 'app-index': ${data}` - ); return new DryrunSource({ + appIndex: data['app-index'], fieldName: data['field-name'], source: data['source'], txnIndex: data['txn-index'], - appIndex: data['app-index'], }); /* eslint-enable dot-notation */ } @@ -2575,12 +2591,12 @@ export class DryrunState extends BaseModel { /** * Line number */ - public line: number | bigint; + public line: number; /** * Program counter */ - public pc: number | bigint; + public pc: number; public stack: TealValue[]; @@ -2613,8 +2629,8 @@ export class DryrunState extends BaseModel { scratch?: TealValue[]; }) { super(); - this.line = line; - this.pc = pc; + this.line = ensureSafeInteger(line); + this.pc = ensureSafeInteger(pc); this.stack = stack; this.error = error; this.scratch = scratch; @@ -2670,12 +2686,12 @@ export class DryrunTxnResult extends BaseModel { /** * Budget added during execution of app call transaction. */ - public budgetAdded?: number | bigint; + public budgetAdded?: number; /** * Budget consumed during execution of app call transaction. */ - public budgetConsumed?: number | bigint; + public budgetConsumed?: number; /** * Application state delta. @@ -2738,8 +2754,14 @@ export class DryrunTxnResult extends BaseModel { this.disassembly = disassembly; this.appCallMessages = appCallMessages; this.appCallTrace = appCallTrace; - this.budgetAdded = budgetAdded; - this.budgetConsumed = budgetConsumed; + this.budgetAdded = + typeof budgetAdded === 'undefined' + ? undefined + : ensureSafeInteger(budgetAdded); + this.budgetConsumed = + typeof budgetConsumed === 'undefined' + ? undefined + : ensureSafeInteger(budgetConsumed); this.globalDelta = globalDelta; this.localDeltas = localDeltas; this.logicSigDisassembly = logicSigDisassembly; @@ -2848,7 +2870,7 @@ export class EvalDelta extends BaseModel { /** * (at) delta action. */ - public action: number | bigint; + public action: number; /** * (bs) bytes value. @@ -2858,7 +2880,7 @@ export class EvalDelta extends BaseModel { /** * (ui) uint value. */ - public uint?: number | bigint; + public uint?: bigint; /** * Creates a new `EvalDelta` object. @@ -2876,9 +2898,9 @@ export class EvalDelta extends BaseModel { uint?: number | bigint; }) { super(); - this.action = action; + this.action = ensureSafeInteger(action); this.bytes = bytes; - this.uint = uint; + this.uint = typeof uint === 'undefined' ? undefined : ensureBigInt(uint); this.attribute_map = { action: 'action', @@ -2950,7 +2972,7 @@ export class GetBlockTimeStampOffsetResponse extends BaseModel { /** * Timestamp offset in seconds. */ - public offset: number | bigint; + public offset: number; /** * Creates a new `GetBlockTimeStampOffsetResponse` object. @@ -2958,7 +2980,7 @@ export class GetBlockTimeStampOffsetResponse extends BaseModel { */ constructor({ offset }: { offset: number | bigint }) { super(); - this.offset = offset; + this.offset = ensureSafeInteger(offset); this.attribute_map = { offset: 'offset', @@ -2986,7 +3008,7 @@ export class GetSyncRoundResponse extends BaseModel { /** * The minimum sync round for the ledger. */ - public round: number | bigint; + public round: bigint; /** * Creates a new `GetSyncRoundResponse` object. @@ -2994,7 +3016,7 @@ export class GetSyncRoundResponse extends BaseModel { */ constructor({ round }: { round: number | bigint }) { super(); - this.round = round; + this.round = ensureBigInt(round); this.attribute_map = { round: 'round', @@ -3116,7 +3138,7 @@ export class LightBlockHeaderProof extends BaseModel { /** * The index of the light block header in the vector commitment tree */ - public index: number | bigint; + public index: number; /** * The encoded proof. @@ -3127,7 +3149,7 @@ export class LightBlockHeaderProof extends BaseModel { * Represents the depth of the tree that is being proven, i.e. the number of edges * from a leaf to the root. */ - public treedepth: number | bigint; + public treedepth: number; /** * Creates a new `LightBlockHeaderProof` object. @@ -3146,9 +3168,9 @@ export class LightBlockHeaderProof extends BaseModel { treedepth: number | bigint; }) { super(); - this.index = index; + this.index = ensureSafeInteger(index); this.proof = typeof proof === 'string' ? base64ToBytes(proof) : proof; - this.treedepth = treedepth; + this.treedepth = ensureSafeInteger(treedepth); this.attribute_map = { index: 'index', @@ -3186,12 +3208,12 @@ export class NodeStatusResponse extends BaseModel { /** * CatchupTime in nanoseconds */ - public catchupTime: number | bigint; + public catchupTime: bigint; /** * LastRound indicates the last round seen */ - public lastRound: number | bigint; + public lastRound: bigint; /** * LastVersion indicates the last consensus version supported @@ -3206,7 +3228,7 @@ export class NodeStatusResponse extends BaseModel { /** * NextVersionRound is the round at which the next consensus version will apply */ - public nextVersionRound: number | bigint; + public nextVersionRound: bigint; /** * NextVersionSupported indicates whether the next consensus version is supported @@ -3223,7 +3245,7 @@ export class NodeStatusResponse extends BaseModel { /** * TimeSinceLastRound in nanoseconds */ - public timeSinceLastRound: number | bigint; + public timeSinceLastRound: bigint; /** * The current catchpoint that is being caught up to @@ -3234,47 +3256,47 @@ export class NodeStatusResponse extends BaseModel { * The number of blocks that have already been obtained by the node as part of the * catchup */ - public catchpointAcquiredBlocks?: number | bigint; + public catchpointAcquiredBlocks?: number; /** * The number of accounts from the current catchpoint that have been processed so * far as part of the catchup */ - public catchpointProcessedAccounts?: number | bigint; + public catchpointProcessedAccounts?: number; /** * The number of key-values (KVs) from the current catchpoint that have been * processed so far as part of the catchup */ - public catchpointProcessedKvs?: number | bigint; + public catchpointProcessedKvs?: number; /** * The total number of accounts included in the current catchpoint */ - public catchpointTotalAccounts?: number | bigint; + public catchpointTotalAccounts?: number; /** * The total number of blocks that are required to complete the current catchpoint * catchup */ - public catchpointTotalBlocks?: number | bigint; + public catchpointTotalBlocks?: number; /** * The total number of key-values (KVs) included in the current catchpoint */ - public catchpointTotalKvs?: number | bigint; + public catchpointTotalKvs?: number; /** * The number of accounts from the current catchpoint that have been verified so * far as part of the catchup */ - public catchpointVerifiedAccounts?: number | bigint; + public catchpointVerifiedAccounts?: number; /** * The number of key-values (KVs) from the current catchpoint that have been * verified so far as part of the catchup */ - public catchpointVerifiedKvs?: number | bigint; + public catchpointVerifiedKvs?: number; /** * The last catchpoint seen by the node @@ -3284,17 +3306,17 @@ export class NodeStatusResponse extends BaseModel { /** * Upgrade delay */ - public upgradeDelay?: number | bigint; + public upgradeDelay?: bigint; /** * Next protocol round */ - public upgradeNextProtocolVoteBefore?: number | bigint; + public upgradeNextProtocolVoteBefore?: bigint; /** * No votes cast for consensus upgrade */ - public upgradeNoVotes?: number | bigint; + public upgradeNoVotes?: number; /** * This node's upgrade vote @@ -3304,22 +3326,22 @@ export class NodeStatusResponse extends BaseModel { /** * Total voting rounds for current upgrade */ - public upgradeVoteRounds?: number | bigint; + public upgradeVoteRounds?: number; /** * Total votes cast for consensus upgrade */ - public upgradeVotes?: number | bigint; + public upgradeVotes?: number; /** * Yes votes required for consensus upgrade */ - public upgradeVotesRequired?: number | bigint; + public upgradeVotesRequired?: number; /** * Yes votes cast for consensus upgrade */ - public upgradeYesVotes?: number | bigint; + public upgradeYesVotes?: number; /** * Creates a new `NodeStatusResponse` object. @@ -3414,32 +3436,77 @@ export class NodeStatusResponse extends BaseModel { upgradeYesVotes?: number | bigint; }) { super(); - this.catchupTime = catchupTime; - this.lastRound = lastRound; + this.catchupTime = ensureBigInt(catchupTime); + this.lastRound = ensureBigInt(lastRound); this.lastVersion = lastVersion; this.nextVersion = nextVersion; - this.nextVersionRound = nextVersionRound; + this.nextVersionRound = ensureBigInt(nextVersionRound); this.nextVersionSupported = nextVersionSupported; this.stoppedAtUnsupportedRound = stoppedAtUnsupportedRound; - this.timeSinceLastRound = timeSinceLastRound; + this.timeSinceLastRound = ensureBigInt(timeSinceLastRound); this.catchpoint = catchpoint; - this.catchpointAcquiredBlocks = catchpointAcquiredBlocks; - this.catchpointProcessedAccounts = catchpointProcessedAccounts; - this.catchpointProcessedKvs = catchpointProcessedKvs; - this.catchpointTotalAccounts = catchpointTotalAccounts; - this.catchpointTotalBlocks = catchpointTotalBlocks; - this.catchpointTotalKvs = catchpointTotalKvs; - this.catchpointVerifiedAccounts = catchpointVerifiedAccounts; - this.catchpointVerifiedKvs = catchpointVerifiedKvs; + this.catchpointAcquiredBlocks = + typeof catchpointAcquiredBlocks === 'undefined' + ? undefined + : ensureSafeInteger(catchpointAcquiredBlocks); + this.catchpointProcessedAccounts = + typeof catchpointProcessedAccounts === 'undefined' + ? undefined + : ensureSafeInteger(catchpointProcessedAccounts); + this.catchpointProcessedKvs = + typeof catchpointProcessedKvs === 'undefined' + ? undefined + : ensureSafeInteger(catchpointProcessedKvs); + this.catchpointTotalAccounts = + typeof catchpointTotalAccounts === 'undefined' + ? undefined + : ensureSafeInteger(catchpointTotalAccounts); + this.catchpointTotalBlocks = + typeof catchpointTotalBlocks === 'undefined' + ? undefined + : ensureSafeInteger(catchpointTotalBlocks); + this.catchpointTotalKvs = + typeof catchpointTotalKvs === 'undefined' + ? undefined + : ensureSafeInteger(catchpointTotalKvs); + this.catchpointVerifiedAccounts = + typeof catchpointVerifiedAccounts === 'undefined' + ? undefined + : ensureSafeInteger(catchpointVerifiedAccounts); + this.catchpointVerifiedKvs = + typeof catchpointVerifiedKvs === 'undefined' + ? undefined + : ensureSafeInteger(catchpointVerifiedKvs); this.lastCatchpoint = lastCatchpoint; - this.upgradeDelay = upgradeDelay; - this.upgradeNextProtocolVoteBefore = upgradeNextProtocolVoteBefore; - this.upgradeNoVotes = upgradeNoVotes; + this.upgradeDelay = + typeof upgradeDelay === 'undefined' + ? undefined + : ensureBigInt(upgradeDelay); + this.upgradeNextProtocolVoteBefore = + typeof upgradeNextProtocolVoteBefore === 'undefined' + ? undefined + : ensureBigInt(upgradeNextProtocolVoteBefore); + this.upgradeNoVotes = + typeof upgradeNoVotes === 'undefined' + ? undefined + : ensureSafeInteger(upgradeNoVotes); this.upgradeNodeVote = upgradeNodeVote; - this.upgradeVoteRounds = upgradeVoteRounds; - this.upgradeVotes = upgradeVotes; - this.upgradeVotesRequired = upgradeVotesRequired; - this.upgradeYesVotes = upgradeYesVotes; + this.upgradeVoteRounds = + typeof upgradeVoteRounds === 'undefined' + ? undefined + : ensureSafeInteger(upgradeVoteRounds); + this.upgradeVotes = + typeof upgradeVotes === 'undefined' + ? undefined + : ensureSafeInteger(upgradeVotes); + this.upgradeVotesRequired = + typeof upgradeVotesRequired === 'undefined' + ? undefined + : ensureSafeInteger(upgradeVotesRequired); + this.upgradeYesVotes = + typeof upgradeYesVotes === 'undefined' + ? undefined + : ensureSafeInteger(upgradeYesVotes); this.attribute_map = { catchupTime: 'catchup-time', @@ -3559,32 +3626,32 @@ export class PendingTransactionResponse extends BaseModel { * The application index if the transaction was found and it created an * application. */ - public applicationIndex?: number | bigint; + public applicationIndex?: bigint; /** * The number of the asset's unit that were transferred to the close-to address. */ - public assetClosingAmount?: number | bigint; + public assetClosingAmount?: bigint; /** * The asset index if the transaction was found and it created an asset. */ - public assetIndex?: number | bigint; + public assetIndex?: bigint; /** * Rewards in microalgos applied to the close remainder to account. */ - public closeRewards?: number | bigint; + public closeRewards?: bigint; /** * Closing amount for the transaction. */ - public closingAmount?: number | bigint; + public closingAmount?: bigint; /** * The round where this transaction was confirmed, if present. */ - public confirmedRound?: number | bigint; + public confirmedRound?: bigint; /** * Global state key/value changes for the application being executed by this @@ -3611,12 +3678,12 @@ export class PendingTransactionResponse extends BaseModel { /** * Rewards in microalgos applied to the receiver account. */ - public receiverRewards?: number | bigint; + public receiverRewards?: bigint; /** * Rewards in microalgos applied to the sender account. */ - public senderRewards?: number | bigint; + public senderRewards?: bigint; /** * Creates a new `PendingTransactionResponse` object. @@ -3674,18 +3741,40 @@ export class PendingTransactionResponse extends BaseModel { super(); this.poolError = poolError; this.txn = txn; - this.applicationIndex = applicationIndex; - this.assetClosingAmount = assetClosingAmount; - this.assetIndex = assetIndex; - this.closeRewards = closeRewards; - this.closingAmount = closingAmount; - this.confirmedRound = confirmedRound; + this.applicationIndex = + typeof applicationIndex === 'undefined' + ? undefined + : ensureBigInt(applicationIndex); + this.assetClosingAmount = + typeof assetClosingAmount === 'undefined' + ? undefined + : ensureBigInt(assetClosingAmount); + this.assetIndex = + typeof assetIndex === 'undefined' ? undefined : ensureBigInt(assetIndex); + this.closeRewards = + typeof closeRewards === 'undefined' + ? undefined + : ensureBigInt(closeRewards); + this.closingAmount = + typeof closingAmount === 'undefined' + ? undefined + : ensureBigInt(closingAmount); + this.confirmedRound = + typeof confirmedRound === 'undefined' + ? undefined + : ensureBigInt(confirmedRound); this.globalStateDelta = globalStateDelta; this.innerTxns = innerTxns; this.localStateDelta = localStateDelta; this.logs = logs; - this.receiverRewards = receiverRewards; - this.senderRewards = senderRewards; + this.receiverRewards = + typeof receiverRewards === 'undefined' + ? undefined + : ensureBigInt(receiverRewards); + this.senderRewards = + typeof senderRewards === 'undefined' + ? undefined + : ensureBigInt(senderRewards); this.attribute_map = { poolError: 'pool-error', @@ -3765,7 +3854,7 @@ export class PendingTransactionsResponse extends BaseModel { /** * Total number of transactions in the pool. */ - public totalTransactions: number | bigint; + public totalTransactions: number; /** * Creates a new `PendingTransactionsResponse` object. @@ -3781,7 +3870,7 @@ export class PendingTransactionsResponse extends BaseModel { }) { super(); this.topTransactions = topTransactions; - this.totalTransactions = totalTransactions; + this.totalTransactions = ensureSafeInteger(totalTransactions); this.attribute_map = { topTransactions: 'top-transactions', @@ -3858,7 +3947,7 @@ export class ScratchChange extends BaseModel { /** * The scratch slot written. */ - public slot: number | bigint; + public slot: number; /** * Creates a new `ScratchChange` object. @@ -3874,7 +3963,7 @@ export class ScratchChange extends BaseModel { }) { super(); this.newValue = newValue; - this.slot = slot; + this.slot = ensureSafeInteger(slot); this.attribute_map = { newValue: 'new-value', @@ -3977,7 +4066,7 @@ export class SimulateRequest extends BaseModel { /** * Applies extra opcode budget during simulation for each transaction group. */ - public extraOpcodeBudget?: number | bigint; + public extraOpcodeBudget?: number; /** * If provided, specifies the round preceding the simulation. State changes through @@ -3985,7 +4074,7 @@ export class SimulateRequest extends BaseModel { * rounds will be available (controlled by the node config value MaxAcctLookback). * If not specified, defaults to the latest available round. */ - public round?: number | bigint; + public round?: bigint; /** * Creates a new `SimulateRequest` object. @@ -4024,8 +4113,11 @@ export class SimulateRequest extends BaseModel { this.allowMoreLogging = allowMoreLogging; this.allowUnnamedResources = allowUnnamedResources; this.execTraceConfig = execTraceConfig; - this.extraOpcodeBudget = extraOpcodeBudget; - this.round = round; + this.extraOpcodeBudget = + typeof extraOpcodeBudget === 'undefined' + ? undefined + : ensureSafeInteger(extraOpcodeBudget); + this.round = typeof round === 'undefined' ? undefined : ensureBigInt(round); this.attribute_map = { txnGroups: 'txn-groups', @@ -4109,7 +4201,7 @@ export class SimulateResponse extends BaseModel { * The round immediately preceding this simulation. State changes through this * round were used to run this simulation. */ - public lastRound: number | bigint; + public lastRound: bigint; /** * A result object for each transaction group that was simulated. @@ -4119,7 +4211,7 @@ export class SimulateResponse extends BaseModel { /** * The version of this response object. */ - public version: number | bigint; + public version: number; /** * The set of parameters and limits override during simulation. If this set of @@ -4166,9 +4258,9 @@ export class SimulateResponse extends BaseModel { initialStates?: SimulateInitialStates; }) { super(); - this.lastRound = lastRound; + this.lastRound = ensureBigInt(lastRound); this.txnGroups = txnGroups; - this.version = version; + this.version = ensureSafeInteger(version); this.evalOverrides = evalOverrides; this.execTraceConfig = execTraceConfig; this.initialStates = initialStates; @@ -4308,12 +4400,12 @@ export class SimulateTransactionGroupResult extends BaseModel { /** * Total budget added during execution of app calls in the transaction group. */ - public appBudgetAdded?: number | bigint; + public appBudgetAdded?: number; /** * Total budget consumed during execution of app calls in the transaction group. */ - public appBudgetConsumed?: number | bigint; + public appBudgetConsumed?: number; /** * If present, indicates which transaction in this group caused the failure. This @@ -4321,7 +4413,7 @@ export class SimulateTransactionGroupResult extends BaseModel { * the first element indicates the top-level transaction, and successive elements * indicate deeper inner transactions. */ - public failedAt?: (number | bigint)[]; + public failedAt?: number[]; /** * If present, indicates that the transaction group failed and specifies why that @@ -4380,9 +4472,18 @@ export class SimulateTransactionGroupResult extends BaseModel { }) { super(); this.txnResults = txnResults; - this.appBudgetAdded = appBudgetAdded; - this.appBudgetConsumed = appBudgetConsumed; - this.failedAt = failedAt; + this.appBudgetAdded = + typeof appBudgetAdded === 'undefined' + ? undefined + : ensureSafeInteger(appBudgetAdded); + this.appBudgetConsumed = + typeof appBudgetConsumed === 'undefined' + ? undefined + : ensureSafeInteger(appBudgetConsumed); + this.failedAt = + typeof failedAt === 'undefined' + ? undefined + : failedAt.map(ensureSafeInteger); this.failureMessage = failureMessage; this.unnamedResourcesAccessed = unnamedResourcesAccessed; @@ -4438,7 +4539,7 @@ export class SimulateTransactionResult extends BaseModel { * Budget used during execution of an app call transaction. This value includes * budged used by inner app calls spawned by this transaction. */ - public appBudgetConsumed?: number | bigint; + public appBudgetConsumed?: number; /** * The execution trace of calling an app or a logic sig, containing the inner app @@ -4449,7 +4550,7 @@ export class SimulateTransactionResult extends BaseModel { /** * Budget used during execution of a logic sig transaction. */ - public logicSigBudgetConsumed?: number | bigint; + public logicSigBudgetConsumed?: number; /** * These are resources that were accessed by this group that would normally have @@ -4498,9 +4599,15 @@ export class SimulateTransactionResult extends BaseModel { }) { super(); this.txnResult = txnResult; - this.appBudgetConsumed = appBudgetConsumed; + this.appBudgetConsumed = + typeof appBudgetConsumed === 'undefined' + ? undefined + : ensureSafeInteger(appBudgetConsumed); this.execTrace = execTrace; - this.logicSigBudgetConsumed = logicSigBudgetConsumed; + this.logicSigBudgetConsumed = + typeof logicSigBudgetConsumed === 'undefined' + ? undefined + : ensureSafeInteger(logicSigBudgetConsumed); this.unnamedResourcesAccessed = unnamedResourcesAccessed; this.attribute_map = { @@ -4571,7 +4678,7 @@ export class SimulateUnnamedResourcesAccessed extends BaseModel { * The unnamed applications that were referenced. The order of this array is * arbitrary. */ - public apps?: (number | bigint)[]; + public apps?: bigint[]; /** * The unnamed asset holdings that were referenced. The order of this array is @@ -4582,7 +4689,7 @@ export class SimulateUnnamedResourcesAccessed extends BaseModel { /** * The unnamed assets that were referenced. The order of this array is arbitrary. */ - public assets?: (number | bigint)[]; + public assets?: bigint[]; /** * The unnamed boxes that were referenced. The order of this array is arbitrary. @@ -4594,7 +4701,7 @@ export class SimulateUnnamedResourcesAccessed extends BaseModel { * addition to the references defined in the input transaction group and any * referenced to unnamed boxes. */ - public extraBoxRefs?: number | bigint; + public extraBoxRefs?: number; /** * Creates a new `SimulateUnnamedResourcesAccessed` object. @@ -4631,11 +4738,16 @@ export class SimulateUnnamedResourcesAccessed extends BaseModel { super(); this.accounts = accounts; this.appLocals = appLocals; - this.apps = apps; + this.apps = + typeof apps === 'undefined' ? undefined : apps.map(ensureBigInt); this.assetHoldings = assetHoldings; - this.assets = assets; + this.assets = + typeof assets === 'undefined' ? undefined : assets.map(ensureBigInt); this.boxes = boxes; - this.extraBoxRefs = extraBoxRefs; + this.extraBoxRefs = + typeof extraBoxRefs === 'undefined' + ? undefined + : ensureSafeInteger(extraBoxRefs); this.attribute_map = { accounts: 'accounts', @@ -4699,17 +4811,17 @@ export class SimulationEvalOverrides extends BaseModel { /** * The extra opcode budget added to each transaction group during simulation */ - public extraOpcodeBudget?: number | bigint; + public extraOpcodeBudget?: number; /** * The maximum log calls one can make during simulation */ - public maxLogCalls?: number | bigint; + public maxLogCalls?: number; /** * The maximum byte number to log during simulation */ - public maxLogSize?: number | bigint; + public maxLogSize?: number; /** * Creates a new `SimulationEvalOverrides` object. @@ -4736,9 +4848,18 @@ export class SimulationEvalOverrides extends BaseModel { super(); this.allowEmptySignatures = allowEmptySignatures; this.allowUnnamedResources = allowUnnamedResources; - this.extraOpcodeBudget = extraOpcodeBudget; - this.maxLogCalls = maxLogCalls; - this.maxLogSize = maxLogSize; + this.extraOpcodeBudget = + typeof extraOpcodeBudget === 'undefined' + ? undefined + : ensureSafeInteger(extraOpcodeBudget); + this.maxLogCalls = + typeof maxLogCalls === 'undefined' + ? undefined + : ensureSafeInteger(maxLogCalls); + this.maxLogSize = + typeof maxLogSize === 'undefined' + ? undefined + : ensureSafeInteger(maxLogSize); this.attribute_map = { allowEmptySignatures: 'allow-empty-signatures', @@ -4772,7 +4893,7 @@ export class SimulationOpcodeTraceUnit extends BaseModel { /** * The program counter of the current opcode being evaluated. */ - public pc: number | bigint; + public pc: number; /** * The writes into scratch slots. @@ -4782,7 +4903,7 @@ export class SimulationOpcodeTraceUnit extends BaseModel { /** * The indexes of the traces for inner transactions spawned by this opcode, if any. */ - public spawnedInners?: (number | bigint)[]; + public spawnedInners?: number[]; /** * The values added by this opcode to the stack. @@ -4792,7 +4913,7 @@ export class SimulationOpcodeTraceUnit extends BaseModel { /** * The number of deleted stack values by this opcode. */ - public stackPopCount?: number | bigint; + public stackPopCount?: number; /** * The operations against the current application's states. @@ -4824,11 +4945,17 @@ export class SimulationOpcodeTraceUnit extends BaseModel { stateChanges?: ApplicationStateOperation[]; }) { super(); - this.pc = pc; + this.pc = ensureSafeInteger(pc); this.scratchChanges = scratchChanges; - this.spawnedInners = spawnedInners; + this.spawnedInners = + typeof spawnedInners === 'undefined' + ? undefined + : spawnedInners.map(ensureSafeInteger); this.stackAdditions = stackAdditions; - this.stackPopCount = stackPopCount; + this.stackPopCount = + typeof stackPopCount === 'undefined' + ? undefined + : ensureSafeInteger(stackPopCount); this.stateChanges = stateChanges; this.attribute_map = { @@ -5102,18 +5229,18 @@ export class StateProofMessage extends BaseModel { /** * The first round the message attests to. */ - public firstattestedround: number | bigint; + public firstattestedround: bigint; /** * The last round the message attests to. */ - public lastattestedround: number | bigint; + public lastattestedround: bigint; /** * An integer value representing the natural log of the proven weight with 16 bits * of precision. This value would be used to verify the next state proof. */ - public lnprovenweight: number | bigint; + public lnprovenweight: bigint; /** * The vector commitment root of the top N accounts to sign the next StateProof. @@ -5148,9 +5275,9 @@ export class StateProofMessage extends BaseModel { typeof blockheaderscommitment === 'string' ? base64ToBytes(blockheaderscommitment) : blockheaderscommitment; - this.firstattestedround = firstattestedround; - this.lastattestedround = lastattestedround; - this.lnprovenweight = lnprovenweight; + this.firstattestedround = ensureBigInt(firstattestedround); + this.lastattestedround = ensureBigInt(lastattestedround); + this.lnprovenweight = ensureBigInt(lnprovenweight); this.voterscommitment = typeof voterscommitment === 'string' ? base64ToBytes(voterscommitment) @@ -5206,17 +5333,17 @@ export class SupplyResponse extends BaseModel { /** * Round */ - public currentRound: number | bigint; + public currentRound: bigint; /** * OnlineMoney */ - public onlineMoney: number | bigint; + public onlineMoney: bigint; /** * TotalMoney */ - public totalMoney: number | bigint; + public totalMoney: bigint; /** * Creates a new `SupplyResponse` object. @@ -5234,9 +5361,9 @@ export class SupplyResponse extends BaseModel { totalMoney: number | bigint; }) { super(); - this.currentRound = currentRound; - this.onlineMoney = onlineMoney; - this.totalMoney = totalMoney; + this.currentRound = ensureBigInt(currentRound); + this.onlineMoney = ensureBigInt(onlineMoney); + this.totalMoney = ensureBigInt(totalMoney); this.attribute_map = { currentRound: 'current_round', @@ -5316,43 +5443,43 @@ export class TealKeyValue extends BaseModel { */ export class TealValue extends BaseModel { /** - * (tt) value type. Value `1` refers to **bytes**, value `2` refers to **uint** + * (tb) bytes value. */ - public type: number | bigint; + public bytes: string; /** - * (tb) bytes value. + * (tt) value type. Value `1` refers to **bytes**, value `2` refers to **uint** */ - public bytes: string; + public type: number; /** * (ui) uint value. */ - public uint: number | bigint; + public uint: bigint; /** * Creates a new `TealValue` object. - * @param type - (tt) value type. Value `1` refers to **bytes**, value `2` refers to **uint** * @param bytes - (tb) bytes value. + * @param type - (tt) value type. Value `1` refers to **bytes**, value `2` refers to **uint** * @param uint - (ui) uint value. */ constructor({ - type, bytes, + type, uint, }: { - type: number | bigint; bytes: string; + type: number | bigint; uint: number | bigint; }) { super(); - this.type = type; this.bytes = bytes; - this.uint = uint; + this.type = ensureSafeInteger(type); + this.uint = ensureBigInt(uint); this.attribute_map = { - type: 'type', bytes: 'bytes', + type: 'type', uint: 'uint', }; } @@ -5360,15 +5487,15 @@ export class TealValue extends BaseModel { // eslint-disable-next-line camelcase static from_obj_for_encoding(data: Record): TealValue { /* eslint-disable dot-notation */ - if (typeof data['type'] === 'undefined') - throw new Error(`Response is missing required field 'type': ${data}`); if (typeof data['bytes'] === 'undefined') throw new Error(`Response is missing required field 'bytes': ${data}`); + if (typeof data['type'] === 'undefined') + throw new Error(`Response is missing required field 'type': ${data}`); if (typeof data['uint'] === 'undefined') throw new Error(`Response is missing required field 'uint': ${data}`); return new TealValue({ - type: data['type'], bytes: data['bytes'], + type: data['type'], uint: data['uint'], }); /* eslint-enable dot-notation */ @@ -5430,7 +5557,7 @@ export class TransactionParametersResponse extends BaseModel { * Fee may fall to zero but transactions must still have a fee of * at least MinTxnFee for the current network protocol. */ - public fee: number | bigint; + public fee: bigint; /** * GenesisHash is the hash of the genesis block. @@ -5445,13 +5572,13 @@ export class TransactionParametersResponse extends BaseModel { /** * LastRound indicates the last round seen */ - public lastRound: number | bigint; + public lastRound: bigint; /** * The minimum transaction fee (not per byte) required for the * txn to validate for the current network protocol. */ - public minFee: number | bigint; + public minFee: bigint; /** * Creates a new `TransactionParametersResponse` object. @@ -5484,14 +5611,14 @@ export class TransactionParametersResponse extends BaseModel { }) { super(); this.consensusVersion = consensusVersion; - this.fee = fee; + this.fee = ensureBigInt(fee); this.genesisHash = typeof genesisHash === 'string' ? base64ToBytes(genesisHash) : genesisHash; this.genesisId = genesisId; - this.lastRound = lastRound; - this.minFee = minFee; + this.lastRound = ensureBigInt(lastRound); + this.minFee = ensureBigInt(minFee); this.attribute_map = { consensusVersion: 'consensus-version', @@ -5547,7 +5674,7 @@ export class TransactionProofResponse extends BaseModel { /** * Index of the transaction in the block's payset. */ - public idx: number | bigint; + public idx: number; /** * Proof of transaction membership. @@ -5563,7 +5690,7 @@ export class TransactionProofResponse extends BaseModel { * Represents the depth of the tree that is being proven, i.e. the number of edges * from a leaf to the root. */ - public treedepth: number | bigint; + public treedepth: number; /** * The type of hash function used to create the proof, must be one of: @@ -5597,11 +5724,11 @@ export class TransactionProofResponse extends BaseModel { hashtype?: string; }) { super(); - this.idx = idx; + this.idx = ensureSafeInteger(idx); this.proof = typeof proof === 'string' ? base64ToBytes(proof) : proof; this.stibhash = typeof stibhash === 'string' ? base64ToBytes(stibhash) : stibhash; - this.treedepth = treedepth; + this.treedepth = ensureSafeInteger(treedepth); this.hashtype = hashtype; this.attribute_map = { diff --git a/src/client/v2/algod/sendRawTransaction.ts b/src/client/v2/algod/sendRawTransaction.ts index b758dd417..ec7939bd5 100644 --- a/src/client/v2/algod/sendRawTransaction.ts +++ b/src/client/v2/algod/sendRawTransaction.ts @@ -1,4 +1,5 @@ import { concatArrays } from '../../../utils/utils.js'; +import IntDecoding from '../../../types/intDecoding.js'; import { PostTransactionsResponse } from './models/types.js'; import { HTTPClient } from '../../client.js'; import JSONRequest from '../jsonrequest.js'; @@ -55,12 +56,13 @@ export default class SendRawTransaction extends JSONRequest< async do(headers = {}) { const txHeaders = setSendTransactionHeaders(headers); - const res = await this.c.post( - this.path(), - this.txnBytesToPost, - undefined, - txHeaders - ); + const res = await this.c.post({ + relativePath: this.path(), + data: this.txnBytesToPost, + parseBody: true, + jsonOptions: { intDecoding: IntDecoding.BIGINT }, + requestHeaders: txHeaders, + }); return this.prepare(res.body); } diff --git a/src/client/v2/algod/setBlockOffsetTimestamp.ts b/src/client/v2/algod/setBlockOffsetTimestamp.ts index 50b99f9cf..61db717e5 100644 --- a/src/client/v2/algod/setBlockOffsetTimestamp.ts +++ b/src/client/v2/algod/setBlockOffsetTimestamp.ts @@ -1,14 +1,13 @@ import JSONRequest from '../jsonrequest.js'; -import { HTTPClient } from '../../client.js'; import IntDecoding from '../../../types/intDecoding.js'; +import { HTTPClient } from '../../client.js'; export default class SetBlockOffsetTimestamp extends JSONRequest { constructor( c: HTTPClient, - intDecoding: IntDecoding, private offset: number ) { - super(c, intDecoding); + super(c); } path() { @@ -16,7 +15,13 @@ export default class SetBlockOffsetTimestamp extends JSONRequest { } async do(headers = {}) { - const res = await this.c.post(this.path(), null, undefined, headers); + const res = await this.c.post({ + relativePath: this.path(), + data: null, + parseBody: true, + jsonOptions: { intDecoding: IntDecoding.BIGINT }, + requestHeaders: headers, + }); return res.body; } } diff --git a/src/client/v2/algod/setSyncRound.ts b/src/client/v2/algod/setSyncRound.ts index 419987fad..40d55f37e 100644 --- a/src/client/v2/algod/setSyncRound.ts +++ b/src/client/v2/algod/setSyncRound.ts @@ -1,14 +1,13 @@ import JSONRequest from '../jsonrequest.js'; -import { HTTPClient } from '../../client.js'; import IntDecoding from '../../../types/intDecoding.js'; +import { HTTPClient } from '../../client.js'; export default class SetSyncRound extends JSONRequest { constructor( c: HTTPClient, - intDecoding: IntDecoding, private round: number ) { - super(c, intDecoding); + super(c); } path() { @@ -16,7 +15,13 @@ export default class SetSyncRound extends JSONRequest { } async do(headers = {}) { - const res = await this.c.post(this.path(), null, undefined, headers); + const res = await this.c.post({ + relativePath: this.path(), + data: null, + parseBody: true, + jsonOptions: { intDecoding: IntDecoding.BIGINT }, + requestHeaders: headers, + }); return res.body; } } diff --git a/src/client/v2/algod/simulateTransaction.ts b/src/client/v2/algod/simulateTransaction.ts index 986e67641..158000fd5 100644 --- a/src/client/v2/algod/simulateTransaction.ts +++ b/src/client/v2/algod/simulateTransaction.ts @@ -1,4 +1,5 @@ import * as encoding from '../../../encoding/encoding.js'; +import IntDecoding from '../../../types/intDecoding.js'; import { HTTPClient } from '../../client.js'; import JSONRequest from '../jsonrequest.js'; import { SimulateRequest, SimulateResponse } from './models/types.js'; @@ -43,13 +44,14 @@ export default class SimulateRawTransactions extends JSONRequest< async do(headers = {}) { const txHeaders = setSimulateTransactionsHeaders(headers); - const res = await this.c.post( - this.path(), - this.requestBytes, - this.query, - txHeaders, - false - ); + const res = await this.c.post({ + relativePath: this.path(), + data: this.requestBytes, + parseBody: false, + jsonOptions: { intDecoding: IntDecoding.BIGINT }, + query: this.query, + requestHeaders: txHeaders, + }); return this.prepare(res.body); } diff --git a/src/client/v2/algod/stateproof.ts b/src/client/v2/algod/stateproof.ts index 9ea048d4d..03cc12800 100644 --- a/src/client/v2/algod/stateproof.ts +++ b/src/client/v2/algod/stateproof.ts @@ -1,15 +1,13 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { StateProof as SP } from './models/types.js'; export default class StateProof extends JSONRequest> { constructor( c: HTTPClient, - intDecoding: IntDecoding, private round: number ) { - super(c, intDecoding); + super(c); } path() { diff --git a/src/client/v2/algod/statusAfterBlock.ts b/src/client/v2/algod/statusAfterBlock.ts index ed74730d5..2964ae027 100644 --- a/src/client/v2/algod/statusAfterBlock.ts +++ b/src/client/v2/algod/statusAfterBlock.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { NodeStatusResponse } from './models/types.js'; export default class StatusAfterBlock extends JSONRequest< @@ -9,10 +8,9 @@ export default class StatusAfterBlock extends JSONRequest< > { constructor( c: HTTPClient, - intDecoding: IntDecoding, private round: number ) { - super(c, intDecoding); + super(c); if (!Number.isInteger(round)) throw Error('round should be an integer'); } diff --git a/src/client/v2/algod/unsetSyncRound.ts b/src/client/v2/algod/unsetSyncRound.ts index 9aa1026b6..cb2a88057 100644 --- a/src/client/v2/algod/unsetSyncRound.ts +++ b/src/client/v2/algod/unsetSyncRound.ts @@ -1,4 +1,5 @@ import JSONRequest from '../jsonrequest.js'; +import IntDecoding from '../../../types/intDecoding.js'; export default class UnsetSyncRound extends JSONRequest { // eslint-disable-next-line class-methods-use-this @@ -7,7 +8,13 @@ export default class UnsetSyncRound extends JSONRequest { } async do(headers = {}) { - const res = await this.c.delete(this.path(), headers); + const res = await this.c.delete({ + relativePath: this.path(), + data: undefined, + parseBody: false, + jsonOptions: { intDecoding: IntDecoding.BIGINT }, + requestHeaders: headers, + }); return res.body; } } diff --git a/src/client/v2/indexer/indexer.ts b/src/client/v2/indexer/indexer.ts index e99522d36..f88235fd1 100644 --- a/src/client/v2/indexer/indexer.ts +++ b/src/client/v2/indexer/indexer.ts @@ -88,7 +88,7 @@ export class IndexerClient extends ServiceClient { * @category GET */ makeHealthCheck() { - return new MakeHealthCheck(this.c, this.intDecoding); + return new MakeHealthCheck(this.c); } /** @@ -105,7 +105,7 @@ export class IndexerClient extends ServiceClient { * @category GET */ lookupAssetBalances(index: number) { - return new LookupAssetBalances(this.c, this.intDecoding, index); + return new LookupAssetBalances(this.c, index); } /** @@ -122,7 +122,7 @@ export class IndexerClient extends ServiceClient { * @category GET */ lookupAssetTransactions(index: number) { - return new LookupAssetTransactions(this.c, this.intDecoding, index); + return new LookupAssetTransactions(this.c, index); } /** @@ -139,7 +139,7 @@ export class IndexerClient extends ServiceClient { * @category GET */ lookupAccountTransactions(account: string | Address) { - return new LookupAccountTransactions(this.c, this.intDecoding, account); + return new LookupAccountTransactions(this.c, account); } /** @@ -156,7 +156,7 @@ export class IndexerClient extends ServiceClient { * @category GET */ lookupBlock(round: number) { - return new LookupBlock(this.c, this.intDecoding, round); + return new LookupBlock(this.c, round); } /** @@ -173,7 +173,7 @@ export class IndexerClient extends ServiceClient { * @category GET */ lookupTransactionByID(txID: string) { - return new LookupTransactionByID(this.c, this.intDecoding, txID); + return new LookupTransactionByID(this.c, txID); } /** @@ -190,7 +190,7 @@ export class IndexerClient extends ServiceClient { * @category GET */ lookupAccountByID(account: string | Address) { - return new LookupAccountByID(this.c, this.intDecoding, account); + return new LookupAccountByID(this.c, account); } /** @@ -207,7 +207,7 @@ export class IndexerClient extends ServiceClient { * @category GET */ lookupAccountAssets(account: string | Address) { - return new LookupAccountAssets(this.c, this.intDecoding, account); + return new LookupAccountAssets(this.c, account); } /** @@ -224,7 +224,7 @@ export class IndexerClient extends ServiceClient { * @category GET */ lookupAccountCreatedAssets(account: string | Address) { - return new LookupAccountCreatedAssets(this.c, this.intDecoding, account); + return new LookupAccountCreatedAssets(this.c, account); } /** @@ -241,7 +241,7 @@ export class IndexerClient extends ServiceClient { * @category GET */ lookupAccountAppLocalStates(account: string | Address) { - return new LookupAccountAppLocalStates(this.c, this.intDecoding, account); + return new LookupAccountAppLocalStates(this.c, account); } /** @@ -258,11 +258,7 @@ export class IndexerClient extends ServiceClient { * @category GET */ lookupAccountCreatedApplications(account: string | Address) { - return new LookupAccountCreatedApplications( - this.c, - this.intDecoding, - account - ); + return new LookupAccountCreatedApplications(this.c, account); } /** @@ -279,7 +275,7 @@ export class IndexerClient extends ServiceClient { * @category GET */ lookupAssetByID(index: number) { - return new LookupAssetByID(this.c, this.intDecoding, index); + return new LookupAssetByID(this.c, index); } /** @@ -296,7 +292,7 @@ export class IndexerClient extends ServiceClient { * @category GET */ lookupApplications(index: number) { - return new LookupApplications(this.c, this.intDecoding, index); + return new LookupApplications(this.c, index); } /** @@ -313,7 +309,7 @@ export class IndexerClient extends ServiceClient { * @category GET */ lookupApplicationLogs(appID: number) { - return new LookupApplicationLogs(this.c, this.intDecoding, appID); + return new LookupApplicationLogs(this.c, appID); } /** @@ -328,7 +324,7 @@ export class IndexerClient extends ServiceClient { * @category GET */ searchAccounts() { - return new SearchAccounts(this.c, this.intDecoding); + return new SearchAccounts(this.c); } /** @@ -343,7 +339,7 @@ export class IndexerClient extends ServiceClient { * @category GET */ searchForTransactions() { - return new SearchForTransactions(this.c, this.intDecoding); + return new SearchForTransactions(this.c); } /** @@ -358,7 +354,7 @@ export class IndexerClient extends ServiceClient { * @category GET */ searchForAssets() { - return new SearchForAssets(this.c, this.intDecoding); + return new SearchForAssets(this.c); } /** @@ -373,7 +369,7 @@ export class IndexerClient extends ServiceClient { * @category GET */ searchForApplications() { - return new SearchForApplications(this.c, this.intDecoding); + return new SearchForApplications(this.c); } /** @@ -403,7 +399,7 @@ export class IndexerClient extends ServiceClient { * @category GET */ searchForApplicationBoxes(appID: number) { - return new SearchForApplicationBoxes(this.c, this.intDecoding, appID); + return new SearchForApplicationBoxes(this.c, appID); } /** @@ -423,11 +419,6 @@ export class IndexerClient extends ServiceClient { * @category GET */ lookupApplicationBoxByIDandName(appID: number, boxName: Uint8Array) { - return new LookupApplicationBoxByIDandName( - this.c, - this.intDecoding, - appID, - boxName - ); + return new LookupApplicationBoxByIDandName(this.c, appID, boxName); } } diff --git a/src/client/v2/indexer/lookupAccountAppLocalStates.ts b/src/client/v2/indexer/lookupAccountAppLocalStates.ts index 7c916edbc..71980ad4d 100644 --- a/src/client/v2/indexer/lookupAccountAppLocalStates.ts +++ b/src/client/v2/indexer/lookupAccountAppLocalStates.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { Address } from '../../../encoding/address.js'; export default class LookupAccountAppLocalStates extends JSONRequest { @@ -19,12 +18,8 @@ export default class LookupAccountAppLocalStates extends JSONRequest { * @param account - The address of the account to look up. * @category GET */ - constructor( - c: HTTPClient, - intDecoding: IntDecoding, - account: string | Address - ) { - super(c, intDecoding); + constructor(c: HTTPClient, account: string | Address) { + super(c); this.account = account.toString(); } diff --git a/src/client/v2/indexer/lookupAccountAssets.ts b/src/client/v2/indexer/lookupAccountAssets.ts index 3ef3a28c0..9062a94ca 100644 --- a/src/client/v2/indexer/lookupAccountAssets.ts +++ b/src/client/v2/indexer/lookupAccountAssets.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { Address } from '../../../encoding/address.js'; export default class LookupAccountAssets extends JSONRequest { @@ -19,12 +18,8 @@ export default class LookupAccountAssets extends JSONRequest { * @param account - The address of the account to look up. * @category GET */ - constructor( - c: HTTPClient, - intDecoding: IntDecoding, - account: string | Address - ) { - super(c, intDecoding); + constructor(c: HTTPClient, account: string | Address) { + super(c); this.account = account.toString(); } diff --git a/src/client/v2/indexer/lookupAccountByID.ts b/src/client/v2/indexer/lookupAccountByID.ts index e821c028c..0eb2e8b89 100644 --- a/src/client/v2/indexer/lookupAccountByID.ts +++ b/src/client/v2/indexer/lookupAccountByID.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { Address } from '../../../encoding/address.js'; export default class LookupAccountByID extends JSONRequest { @@ -19,12 +18,8 @@ export default class LookupAccountByID extends JSONRequest { * @param account - The address of the account to look up. * @category GET */ - constructor( - c: HTTPClient, - intDecoding: IntDecoding, - account: string | Address - ) { - super(c, intDecoding); + constructor(c: HTTPClient, account: string | Address) { + super(c); this.account = account.toString(); } diff --git a/src/client/v2/indexer/lookupAccountCreatedApplications.ts b/src/client/v2/indexer/lookupAccountCreatedApplications.ts index 2929ab8be..635f45c35 100644 --- a/src/client/v2/indexer/lookupAccountCreatedApplications.ts +++ b/src/client/v2/indexer/lookupAccountCreatedApplications.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { Address } from '../../../encoding/address.js'; export default class LookupAccountCreatedApplications extends JSONRequest { @@ -19,12 +18,8 @@ export default class LookupAccountCreatedApplications extends JSONRequest { * @param account - The address of the account to look up. * @category GET */ - constructor( - c: HTTPClient, - intDecoding: IntDecoding, - account: string | Address - ) { - super(c, intDecoding); + constructor(c: HTTPClient, account: string | Address) { + super(c); this.account = account.toString(); } diff --git a/src/client/v2/indexer/lookupAccountCreatedAssets.ts b/src/client/v2/indexer/lookupAccountCreatedAssets.ts index 952f5c186..5d668a5d2 100644 --- a/src/client/v2/indexer/lookupAccountCreatedAssets.ts +++ b/src/client/v2/indexer/lookupAccountCreatedAssets.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { Address } from '../../../encoding/address.js'; export default class LookupAccountCreatedAssets extends JSONRequest { @@ -19,12 +18,8 @@ export default class LookupAccountCreatedAssets extends JSONRequest { * @param account - The address of the account to look up. * @category GET */ - constructor( - c: HTTPClient, - intDecoding: IntDecoding, - account: string | Address - ) { - super(c, intDecoding); + constructor(c: HTTPClient, account: string | Address) { + super(c); this.account = account.toString(); } diff --git a/src/client/v2/indexer/lookupAccountTransactions.ts b/src/client/v2/indexer/lookupAccountTransactions.ts index 5c8ddf1c9..1f3c150ac 100644 --- a/src/client/v2/indexer/lookupAccountTransactions.ts +++ b/src/client/v2/indexer/lookupAccountTransactions.ts @@ -1,5 +1,4 @@ import { bytesToBase64 } from '../../../encoding/binarydata.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { HTTPClient } from '../../client.js'; import JSONRequest from '../jsonrequest.js'; import { Address } from '../../../encoding/address.js'; @@ -31,12 +30,8 @@ export default class LookupAccountTransactions extends JSONRequest { * [Response data schema details](https://developer.algorand.org/docs/rest-apis/indexer/#get-v2accountsaccount-idtransactions) * @param account - The address of the account. */ - constructor( - c: HTTPClient, - intDecoding: IntDecoding, - account: string | Address - ) { - super(c, intDecoding); + constructor(c: HTTPClient, account: string | Address) { + super(c); this.account = account.toString(); } diff --git a/src/client/v2/indexer/lookupApplicationBoxByIDandName.ts b/src/client/v2/indexer/lookupApplicationBoxByIDandName.ts index e9f68e4d6..07c21addd 100644 --- a/src/client/v2/indexer/lookupApplicationBoxByIDandName.ts +++ b/src/client/v2/indexer/lookupApplicationBoxByIDandName.ts @@ -1,5 +1,4 @@ import { bytesToBase64 } from '../../../encoding/binarydata.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { HTTPClient } from '../../client.js'; import JSONRequest from '../jsonrequest.js'; import { Box } from './models/types.js'; @@ -26,11 +25,10 @@ export default class LookupApplicationBoxByIDandName extends JSONRequest< */ constructor( c: HTTPClient, - intDecoding: IntDecoding, private index: number, boxName: Uint8Array ) { - super(c, intDecoding); + super(c); // Encode query in base64 format and append the encoding prefix. const encodedName = bytesToBase64(boxName); this.query.name = encodeURI(`b64:${encodedName}`); diff --git a/src/client/v2/indexer/lookupApplicationLogs.ts b/src/client/v2/indexer/lookupApplicationLogs.ts index 8c2c5cea2..e2133edfc 100644 --- a/src/client/v2/indexer/lookupApplicationLogs.ts +++ b/src/client/v2/indexer/lookupApplicationLogs.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; export default class LookupApplicationLogs extends JSONRequest { /** @@ -18,10 +17,9 @@ export default class LookupApplicationLogs extends JSONRequest { */ constructor( c: HTTPClient, - intDecoding: IntDecoding, private appID: number ) { - super(c, intDecoding); + super(c); } /** diff --git a/src/client/v2/indexer/lookupApplications.ts b/src/client/v2/indexer/lookupApplications.ts index 0827bcb66..c717e83d1 100644 --- a/src/client/v2/indexer/lookupApplications.ts +++ b/src/client/v2/indexer/lookupApplications.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; export default class LookupApplications extends JSONRequest { /** @@ -18,10 +17,9 @@ export default class LookupApplications extends JSONRequest { */ constructor( c: HTTPClient, - intDecoding: IntDecoding, private index: number ) { - super(c, intDecoding); + super(c); } /** diff --git a/src/client/v2/indexer/lookupAssetBalances.ts b/src/client/v2/indexer/lookupAssetBalances.ts index 5c77508cf..31b73b026 100644 --- a/src/client/v2/indexer/lookupAssetBalances.ts +++ b/src/client/v2/indexer/lookupAssetBalances.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; export default class LookupAssetBalances extends JSONRequest { /** @@ -17,10 +16,9 @@ export default class LookupAssetBalances extends JSONRequest { */ constructor( c: HTTPClient, - intDecoding: IntDecoding, private index: number ) { - super(c, intDecoding); + super(c); } /** diff --git a/src/client/v2/indexer/lookupAssetByID.ts b/src/client/v2/indexer/lookupAssetByID.ts index c171cfd8f..f04c6aef9 100644 --- a/src/client/v2/indexer/lookupAssetByID.ts +++ b/src/client/v2/indexer/lookupAssetByID.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; export default class LookupAssetByID extends JSONRequest { /** @@ -17,10 +16,9 @@ export default class LookupAssetByID extends JSONRequest { */ constructor( c: HTTPClient, - intDecoding: IntDecoding, private index: number ) { - super(c, intDecoding); + super(c); } /** diff --git a/src/client/v2/indexer/lookupAssetTransactions.ts b/src/client/v2/indexer/lookupAssetTransactions.ts index daa883c27..1dc3ebb2e 100644 --- a/src/client/v2/indexer/lookupAssetTransactions.ts +++ b/src/client/v2/indexer/lookupAssetTransactions.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { base64StringFunnel } from './lookupAccountTransactions.js'; import { Address } from '../../../encoding/address.js'; @@ -19,10 +18,9 @@ export default class LookupAssetTransactions extends JSONRequest { */ constructor( c: HTTPClient, - intDecoding: IntDecoding, private index: number ) { - super(c, intDecoding); + super(c); } /** diff --git a/src/client/v2/indexer/lookupBlock.ts b/src/client/v2/indexer/lookupBlock.ts index 21c967e50..b0e014512 100644 --- a/src/client/v2/indexer/lookupBlock.ts +++ b/src/client/v2/indexer/lookupBlock.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; export default class LookupBlock extends JSONRequest { /** @@ -18,10 +17,9 @@ export default class LookupBlock extends JSONRequest { */ constructor( c: HTTPClient, - intDecoding: IntDecoding, private round: number ) { - super(c, intDecoding); + super(c); } /** diff --git a/src/client/v2/indexer/lookupTransactionByID.ts b/src/client/v2/indexer/lookupTransactionByID.ts index 642f5b710..f03a95863 100644 --- a/src/client/v2/indexer/lookupTransactionByID.ts +++ b/src/client/v2/indexer/lookupTransactionByID.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; export default class LookupTransactionByID extends JSONRequest { /** @@ -18,10 +17,9 @@ export default class LookupTransactionByID extends JSONRequest { */ constructor( c: HTTPClient, - intDecoding: IntDecoding, private txID: string ) { - super(c, intDecoding); + super(c); } /** diff --git a/src/client/v2/indexer/models/types.ts b/src/client/v2/indexer/models/types.ts index 9883fb856..390edf56c 100644 --- a/src/client/v2/indexer/models/types.ts +++ b/src/client/v2/indexer/models/types.ts @@ -3,6 +3,7 @@ */ /* eslint-disable no-use-before-define */ +import { ensureBigInt, ensureSafeInteger } from '../../../../utils/utils.js'; import { base64ToBytes } from '../../../../encoding/binarydata.js'; import BaseModel from '../../basemodel.js'; @@ -20,28 +21,28 @@ export class Account extends BaseModel { /** * (algo) total number of MicroAlgos in the account */ - public amount: number | bigint; + public amount: bigint; /** * specifies the amount of MicroAlgos in the account, without the pending rewards. */ - public amountWithoutPendingRewards: number | bigint; + public amountWithoutPendingRewards: bigint; /** * amount of MicroAlgos of pending rewards in this account. */ - public pendingRewards: number | bigint; + public pendingRewards: bigint; /** * (ern) total rewards of MicroAlgos the account has received, including pending * rewards. */ - public rewards: number | bigint; + public rewards: bigint; /** * The round for which this information is relevant. */ - public round: number | bigint; + public round: bigint; /** * (onl) delegation status of the account's MicroAlgos @@ -57,35 +58,35 @@ export class Account extends BaseModel { * The count of all applications that have been opted in, equivalent to the count * of application local data (AppLocalState objects) stored in this account. */ - public totalAppsOptedIn: number | bigint; + public totalAppsOptedIn: number; /** * The count of all assets that have been opted in, equivalent to the count of * AssetHolding objects held by this account. */ - public totalAssetsOptedIn: number | bigint; + public totalAssetsOptedIn: number; /** * For app-accounts only. The total number of bytes allocated for the keys and * values of boxes which belong to the associated application. */ - public totalBoxBytes: number | bigint; + public totalBoxBytes: number; /** * For app-accounts only. The total number of boxes which belong to the associated * application. */ - public totalBoxes: number | bigint; + public totalBoxes: number; /** * The count of all apps (AppParams objects) created by this account. */ - public totalCreatedApps: number | bigint; + public totalCreatedApps: number; /** * The count of all assets (AssetParams objects) created by this account. */ - public totalCreatedAssets: number | bigint; + public totalCreatedAssets: number; /** * (appl) applications local data stored in this account. @@ -96,7 +97,7 @@ export class Account extends BaseModel { /** * (teap) the sum of all extra application program pages for this account. */ - public appsTotalExtraPages?: number | bigint; + public appsTotalExtraPages?: number; /** * (tsch) stores the sum of all of the local schemas and global schemas in this @@ -121,7 +122,7 @@ export class Account extends BaseModel { /** * Round during which this account was most recently closed. */ - public closedAtRound?: number | bigint; + public closedAtRound?: bigint; /** * (appp) parameters of applications created by this account including app global @@ -139,7 +140,7 @@ export class Account extends BaseModel { /** * Round during which this account first appeared in a transaction. */ - public createdAtRound?: number | bigint; + public createdAtRound?: bigint; /** * Whether or not this account is currently closed. @@ -156,7 +157,7 @@ export class Account extends BaseModel { * (ebase) used as part of the rewards computation. Only applicable to accounts * which are participating. */ - public rewardBase?: number | bigint; + public rewardBase?: bigint; /** * Indicates what type of signature is used by this account, must be one of: @@ -278,30 +279,42 @@ export class Account extends BaseModel { }) { super(); this.address = address; - this.amount = amount; - this.amountWithoutPendingRewards = amountWithoutPendingRewards; - this.pendingRewards = pendingRewards; - this.rewards = rewards; - this.round = round; + this.amount = ensureBigInt(amount); + this.amountWithoutPendingRewards = ensureBigInt( + amountWithoutPendingRewards + ); + this.pendingRewards = ensureBigInt(pendingRewards); + this.rewards = ensureBigInt(rewards); + this.round = ensureBigInt(round); this.status = status; - this.totalAppsOptedIn = totalAppsOptedIn; - this.totalAssetsOptedIn = totalAssetsOptedIn; - this.totalBoxBytes = totalBoxBytes; - this.totalBoxes = totalBoxes; - this.totalCreatedApps = totalCreatedApps; - this.totalCreatedAssets = totalCreatedAssets; + this.totalAppsOptedIn = ensureSafeInteger(totalAppsOptedIn); + this.totalAssetsOptedIn = ensureSafeInteger(totalAssetsOptedIn); + this.totalBoxBytes = ensureSafeInteger(totalBoxBytes); + this.totalBoxes = ensureSafeInteger(totalBoxes); + this.totalCreatedApps = ensureSafeInteger(totalCreatedApps); + this.totalCreatedAssets = ensureSafeInteger(totalCreatedAssets); this.appsLocalState = appsLocalState; - this.appsTotalExtraPages = appsTotalExtraPages; + this.appsTotalExtraPages = + typeof appsTotalExtraPages === 'undefined' + ? undefined + : ensureSafeInteger(appsTotalExtraPages); this.appsTotalSchema = appsTotalSchema; this.assets = assets; this.authAddr = authAddr; - this.closedAtRound = closedAtRound; + this.closedAtRound = + typeof closedAtRound === 'undefined' + ? undefined + : ensureBigInt(closedAtRound); this.createdApps = createdApps; this.createdAssets = createdAssets; - this.createdAtRound = createdAtRound; + this.createdAtRound = + typeof createdAtRound === 'undefined' + ? undefined + : ensureBigInt(createdAtRound); this.deleted = deleted; this.participation = participation; - this.rewardBase = rewardBase; + this.rewardBase = + typeof rewardBase === 'undefined' ? undefined : ensureBigInt(rewardBase); this.sigType = sigType; this.attribute_map = { @@ -446,17 +459,17 @@ export class AccountParticipation extends BaseModel { /** * (voteFst) First round for which this participation is valid. */ - public voteFirstValid: number | bigint; + public voteFirstValid: bigint; /** * (voteKD) Number of subkeys in each batch of participation keys. */ - public voteKeyDilution: number | bigint; + public voteKeyDilution: bigint; /** * (voteLst) Last round for which this participation is valid. */ - public voteLastValid: number | bigint; + public voteLastValid: bigint; /** * (vote) root participation public key (if any) currently registered for this @@ -499,9 +512,9 @@ export class AccountParticipation extends BaseModel { typeof selectionParticipationKey === 'string' ? base64ToBytes(selectionParticipationKey) : selectionParticipationKey; - this.voteFirstValid = voteFirstValid; - this.voteKeyDilution = voteKeyDilution; - this.voteLastValid = voteLastValid; + this.voteFirstValid = ensureBigInt(voteFirstValid); + this.voteKeyDilution = ensureBigInt(voteKeyDilution); + this.voteLastValid = ensureBigInt(voteLastValid); this.voteParticipationKey = typeof voteParticipationKey === 'string' ? base64ToBytes(voteParticipationKey) @@ -572,7 +585,7 @@ export class AccountResponse extends BaseModel { /** * Round at which the results were computed. */ - public currentRound: number | bigint; + public currentRound: bigint; /** * Creates a new `AccountResponse` object. @@ -590,7 +603,7 @@ export class AccountResponse extends BaseModel { }) { super(); this.account = account; - this.currentRound = currentRound; + this.currentRound = ensureBigInt(currentRound); this.attribute_map = { account: 'account', @@ -674,7 +687,7 @@ export class AccountsResponse extends BaseModel { /** * Round at which the results were computed. */ - public currentRound: number | bigint; + public currentRound: bigint; /** * Used for pagination, when making another request provide this token with the @@ -700,7 +713,7 @@ export class AccountsResponse extends BaseModel { }) { super(); this.accounts = accounts; - this.currentRound = currentRound; + this.currentRound = ensureBigInt(currentRound); this.nextToken = nextToken; this.attribute_map = { @@ -737,7 +750,7 @@ export class Application extends BaseModel { /** * (appidx) application index. */ - public id: number | bigint; + public id: bigint; /** * (appparams) application parameters. @@ -747,7 +760,7 @@ export class Application extends BaseModel { /** * Round when this application was created. */ - public createdAtRound?: number | bigint; + public createdAtRound?: bigint; /** * Whether or not this application is currently deleted. @@ -757,7 +770,7 @@ export class Application extends BaseModel { /** * Round when this application was deleted. */ - public deletedAtRound?: number | bigint; + public deletedAtRound?: bigint; /** * Creates a new `Application` object. @@ -781,11 +794,17 @@ export class Application extends BaseModel { deletedAtRound?: number | bigint; }) { super(); - this.id = id; + this.id = ensureBigInt(id); this.params = params; - this.createdAtRound = createdAtRound; + this.createdAtRound = + typeof createdAtRound === 'undefined' + ? undefined + : ensureBigInt(createdAtRound); this.deleted = deleted; - this.deletedAtRound = deletedAtRound; + this.deletedAtRound = + typeof deletedAtRound === 'undefined' + ? undefined + : ensureBigInt(deletedAtRound); this.attribute_map = { id: 'id', @@ -821,7 +840,7 @@ export class ApplicationLocalState extends BaseModel { /** * The application which this local state is for. */ - public id: number | bigint; + public id: bigint; /** * (hsch) schema. @@ -831,7 +850,7 @@ export class ApplicationLocalState extends BaseModel { /** * Round when account closed out of the application. */ - public closedOutAtRound?: number | bigint; + public closedOutAtRound?: bigint; /** * Whether or not the application local state is currently deleted from its @@ -847,7 +866,7 @@ export class ApplicationLocalState extends BaseModel { /** * Round when the account opted into the application. */ - public optedInAtRound?: number | bigint; + public optedInAtRound?: bigint; /** * Creates a new `ApplicationLocalState` object. @@ -875,12 +894,18 @@ export class ApplicationLocalState extends BaseModel { optedInAtRound?: number | bigint; }) { super(); - this.id = id; + this.id = ensureBigInt(id); this.schema = schema; - this.closedOutAtRound = closedOutAtRound; + this.closedOutAtRound = + typeof closedOutAtRound === 'undefined' + ? undefined + : ensureBigInt(closedOutAtRound); this.deleted = deleted; this.keyValue = keyValue; - this.optedInAtRound = optedInAtRound; + this.optedInAtRound = + typeof optedInAtRound === 'undefined' + ? undefined + : ensureBigInt(optedInAtRound); this.attribute_map = { id: 'id', @@ -925,7 +950,7 @@ export class ApplicationLocalStatesResponse extends BaseModel { /** * Round at which the results were computed. */ - public currentRound: number | bigint; + public currentRound: bigint; /** * Used for pagination, when making another request provide this token with the @@ -951,7 +976,7 @@ export class ApplicationLocalStatesResponse extends BaseModel { }) { super(); this.appsLocalStates = appsLocalStates; - this.currentRound = currentRound; + this.currentRound = ensureBigInt(currentRound); this.nextToken = nextToken; this.attribute_map = { @@ -1039,12 +1064,12 @@ export class ApplicationLogsResponse extends BaseModel { /** * (appidx) application index. */ - public applicationId: number | bigint; + public applicationId: bigint; /** * Round at which the results were computed. */ - public currentRound: number | bigint; + public currentRound: bigint; public logData?: ApplicationLogData[]; @@ -1074,8 +1099,8 @@ export class ApplicationLogsResponse extends BaseModel { nextToken?: string; }) { super(); - this.applicationId = applicationId; - this.currentRound = currentRound; + this.applicationId = ensureBigInt(applicationId); + this.currentRound = ensureBigInt(currentRound); this.logData = logData; this.nextToken = nextToken; @@ -1136,7 +1161,7 @@ export class ApplicationParams extends BaseModel { /** * (epp) the amount of extra program pages available to this app. */ - public extraProgramPages?: number | bigint; + public extraProgramPages?: number; /** * [\gs) global schema @@ -1191,7 +1216,10 @@ export class ApplicationParams extends BaseModel { ? base64ToBytes(clearStateProgram) : clearStateProgram; this.creator = creator; - this.extraProgramPages = extraProgramPages; + this.extraProgramPages = + typeof extraProgramPages === 'undefined' + ? undefined + : ensureSafeInteger(extraProgramPages); this.globalState = globalState; this.globalStateSchema = globalStateSchema; this.localStateSchema = localStateSchema; @@ -1251,7 +1279,7 @@ export class ApplicationResponse extends BaseModel { /** * Round at which the results were computed. */ - public currentRound: number | bigint; + public currentRound: bigint; /** * Application index and its parameters @@ -1271,7 +1299,7 @@ export class ApplicationResponse extends BaseModel { application?: Application; }) { super(); - this.currentRound = currentRound; + this.currentRound = ensureBigInt(currentRound); this.application = application; this.attribute_map = { @@ -1305,12 +1333,12 @@ export class ApplicationStateSchema extends BaseModel { /** * (nbs) num of byte slices. */ - public numByteSlice: number | bigint; + public numByteSlice: number; /** * (nui) num of uints. */ - public numUint: number | bigint; + public numUint: number; /** * Creates a new `ApplicationStateSchema` object. @@ -1325,8 +1353,8 @@ export class ApplicationStateSchema extends BaseModel { numUint: number | bigint; }) { super(); - this.numByteSlice = numByteSlice; - this.numUint = numUint; + this.numByteSlice = ensureSafeInteger(numByteSlice); + this.numUint = ensureSafeInteger(numUint); this.attribute_map = { numByteSlice: 'num-byte-slice', @@ -1362,7 +1390,7 @@ export class ApplicationsResponse extends BaseModel { /** * Round at which the results were computed. */ - public currentRound: number | bigint; + public currentRound: bigint; /** * Used for pagination, when making another request provide this token with the @@ -1388,7 +1416,7 @@ export class ApplicationsResponse extends BaseModel { }) { super(); this.applications = applications; - this.currentRound = currentRound; + this.currentRound = ensureBigInt(currentRound); this.nextToken = nextToken; this.attribute_map = { @@ -1427,7 +1455,7 @@ export class Asset extends BaseModel { /** * unique asset identifier */ - public index: number | bigint; + public index: bigint; /** * AssetParams specifies the parameters for an asset. @@ -1440,7 +1468,7 @@ export class Asset extends BaseModel { /** * Round during which this asset was created. */ - public createdAtRound?: number | bigint; + public createdAtRound?: bigint; /** * Whether or not this asset is currently deleted. @@ -1450,7 +1478,7 @@ export class Asset extends BaseModel { /** * Round during which this asset was destroyed. */ - public destroyedAtRound?: number | bigint; + public destroyedAtRound?: bigint; /** * Creates a new `Asset` object. @@ -1477,11 +1505,17 @@ export class Asset extends BaseModel { destroyedAtRound?: number | bigint; }) { super(); - this.index = index; + this.index = ensureBigInt(index); this.params = params; - this.createdAtRound = createdAtRound; + this.createdAtRound = + typeof createdAtRound === 'undefined' + ? undefined + : ensureBigInt(createdAtRound); this.deleted = deleted; - this.destroyedAtRound = destroyedAtRound; + this.destroyedAtRound = + typeof destroyedAtRound === 'undefined' + ? undefined + : ensureBigInt(destroyedAtRound); this.attribute_map = { index: 'index', @@ -1519,7 +1553,7 @@ export class AssetBalancesResponse extends BaseModel { /** * Round at which the results were computed. */ - public currentRound: number | bigint; + public currentRound: bigint; /** * Used for pagination, when making another request provide this token with the @@ -1545,7 +1579,7 @@ export class AssetBalancesResponse extends BaseModel { }) { super(); this.balances = balances; - this.currentRound = currentRound; + this.currentRound = ensureBigInt(currentRound); this.nextToken = nextToken; this.attribute_map = { @@ -1586,12 +1620,12 @@ export class AssetHolding extends BaseModel { /** * (a) number of units held. */ - public amount: number | bigint; + public amount: bigint; /** * Asset ID of the holding. */ - public assetId: number | bigint; + public assetId: bigint; /** * (f) whether or not the holding is frozen. @@ -1606,12 +1640,12 @@ export class AssetHolding extends BaseModel { /** * Round during which the account opted into this asset holding. */ - public optedInAtRound?: number | bigint; + public optedInAtRound?: bigint; /** * Round during which the account opted out of this asset holding. */ - public optedOutAtRound?: number | bigint; + public optedOutAtRound?: bigint; /** * Creates a new `AssetHolding` object. @@ -1638,12 +1672,18 @@ export class AssetHolding extends BaseModel { optedOutAtRound?: number | bigint; }) { super(); - this.amount = amount; - this.assetId = assetId; + this.amount = ensureBigInt(amount); + this.assetId = ensureBigInt(assetId); this.isFrozen = isFrozen; this.deleted = deleted; - this.optedInAtRound = optedInAtRound; - this.optedOutAtRound = optedOutAtRound; + this.optedInAtRound = + typeof optedInAtRound === 'undefined' + ? undefined + : ensureBigInt(optedInAtRound); + this.optedOutAtRound = + typeof optedOutAtRound === 'undefined' + ? undefined + : ensureBigInt(optedOutAtRound); this.attribute_map = { amount: 'amount', @@ -1687,7 +1727,7 @@ export class AssetHoldingsResponse extends BaseModel { /** * Round at which the results were computed. */ - public currentRound: number | bigint; + public currentRound: bigint; /** * Used for pagination, when making another request provide this token with the @@ -1713,7 +1753,7 @@ export class AssetHoldingsResponse extends BaseModel { }) { super(); this.assets = assets; - this.currentRound = currentRound; + this.currentRound = ensureBigInt(currentRound); this.nextToken = nextToken; this.attribute_map = { @@ -1765,12 +1805,12 @@ export class AssetParams extends BaseModel { * tenths. If 2, the base unit of the asset is in hundredths, and so on. This value * must be between 0 and 19 (inclusive). */ - public decimals: number | bigint; + public decimals: number; /** * (t) The total number of units of this asset. */ - public total: number | bigint; + public total: bigint; /** * (c) Address of account used to clawback holdings of this asset. If empty, @@ -1902,8 +1942,8 @@ export class AssetParams extends BaseModel { }) { super(); this.creator = creator; - this.decimals = decimals; - this.total = total; + this.decimals = ensureSafeInteger(decimals); + this.total = ensureBigInt(total); this.clawback = clawback; this.defaultFrozen = defaultFrozen; this.freeze = freeze; @@ -1985,7 +2025,7 @@ export class AssetResponse extends BaseModel { /** * Round at which the results were computed. */ - public currentRound: number | bigint; + public currentRound: bigint; /** * Creates a new `AssetResponse` object. @@ -2001,7 +2041,7 @@ export class AssetResponse extends BaseModel { }) { super(); this.asset = asset; - this.currentRound = currentRound; + this.currentRound = ensureBigInt(currentRound); this.attribute_map = { asset: 'asset', @@ -2035,7 +2075,7 @@ export class AssetsResponse extends BaseModel { /** * Round at which the results were computed. */ - public currentRound: number | bigint; + public currentRound: bigint; /** * Used for pagination, when making another request provide this token with the @@ -2061,7 +2101,7 @@ export class AssetsResponse extends BaseModel { }) { super(); this.assets = assets; - this.currentRound = currentRound; + this.currentRound = ensureBigInt(currentRound); this.nextToken = nextToken; this.attribute_map = { @@ -2115,7 +2155,7 @@ export class Block extends BaseModel { /** * (rnd) Current round on which this block was appended to the chain. */ - public round: number | bigint; + public round: bigint; /** * (seed) Sortition seed. @@ -2125,7 +2165,7 @@ export class Block extends BaseModel { /** * (ts) Block creation timestamp in seconds since eposh */ - public timestamp: number | bigint; + public timestamp: number; /** * (txn) TransactionsRoot authenticates the set of transactions appearing in the @@ -2172,7 +2212,7 @@ export class Block extends BaseModel { * committed after this block. It is 0 when no transactions have ever been * committed (since TxnCounter started being supported). */ - public txnCounter?: number | bigint; + public txnCounter?: number; /** * Fields relating to a protocol upgrade. @@ -2257,9 +2297,9 @@ export class Block extends BaseModel { typeof previousBlockHash === 'string' ? base64ToBytes(previousBlockHash) : previousBlockHash; - this.round = round; + this.round = ensureBigInt(round); this.seed = typeof seed === 'string' ? base64ToBytes(seed) : seed; - this.timestamp = timestamp; + this.timestamp = ensureSafeInteger(timestamp); this.transactionsRoot = typeof transactionsRoot === 'string' ? base64ToBytes(transactionsRoot) @@ -2272,7 +2312,10 @@ export class Block extends BaseModel { this.rewards = rewards; this.stateProofTracking = stateProofTracking; this.transactions = transactions; - this.txnCounter = txnCounter; + this.txnCounter = + typeof txnCounter === 'undefined' + ? undefined + : ensureSafeInteger(txnCounter); this.upgradeState = upgradeState; this.upgradeVote = upgradeVote; @@ -2382,13 +2425,13 @@ export class BlockRewards extends BaseModel { * (rwcalr) number of leftover MicroAlgos after the distribution of rewards-rate * MicroAlgos for every reward unit in the next round. */ - public rewardsCalculationRound: number | bigint; + public rewardsCalculationRound: bigint; /** * (earn) How many rewards, in MicroAlgos, have been distributed to each RewardUnit * of MicroAlgos since genesis. */ - public rewardsLevel: number | bigint; + public rewardsLevel: bigint; /** * (rwd) accepts periodic injections from the fee-sink and continually @@ -2400,13 +2443,13 @@ export class BlockRewards extends BaseModel { * (rate) Number of new MicroAlgos added to the participation stake from rewards at * the next round. */ - public rewardsRate: number | bigint; + public rewardsRate: bigint; /** * (frac) Number of leftover MicroAlgos after the distribution of * RewardsRate/rewardUnits MicroAlgos for every reward unit in the next round. */ - public rewardsResidue: number | bigint; + public rewardsResidue: bigint; /** * Creates a new `BlockRewards` object. @@ -2439,11 +2482,11 @@ export class BlockRewards extends BaseModel { }) { super(); this.feeSink = feeSink; - this.rewardsCalculationRound = rewardsCalculationRound; - this.rewardsLevel = rewardsLevel; + this.rewardsCalculationRound = ensureBigInt(rewardsCalculationRound); + this.rewardsLevel = ensureBigInt(rewardsLevel); this.rewardsPool = rewardsPool; - this.rewardsRate = rewardsRate; - this.rewardsResidue = rewardsResidue; + this.rewardsRate = ensureBigInt(rewardsRate); + this.rewardsResidue = ensureBigInt(rewardsResidue); this.attribute_map = { feeSink: 'fee-sink', @@ -2509,18 +2552,18 @@ export class BlockUpgradeState extends BaseModel { /** * (nextyes) Number of blocks which approved the protocol upgrade. */ - public nextProtocolApprovals?: number | bigint; + public nextProtocolApprovals?: number; /** * (nextswitch) Round on which the protocol upgrade will take effect. */ - public nextProtocolSwitchOn?: number | bigint; + public nextProtocolSwitchOn?: bigint; /** * (nextbefore) Deadline round for this protocol upgrade (No votes will be consider * after this round). */ - public nextProtocolVoteBefore?: number | bigint; + public nextProtocolVoteBefore?: bigint; /** * Creates a new `BlockUpgradeState` object. @@ -2547,9 +2590,18 @@ export class BlockUpgradeState extends BaseModel { super(); this.currentProtocol = currentProtocol; this.nextProtocol = nextProtocol; - this.nextProtocolApprovals = nextProtocolApprovals; - this.nextProtocolSwitchOn = nextProtocolSwitchOn; - this.nextProtocolVoteBefore = nextProtocolVoteBefore; + this.nextProtocolApprovals = + typeof nextProtocolApprovals === 'undefined' + ? undefined + : ensureSafeInteger(nextProtocolApprovals); + this.nextProtocolSwitchOn = + typeof nextProtocolSwitchOn === 'undefined' + ? undefined + : ensureBigInt(nextProtocolSwitchOn); + this.nextProtocolVoteBefore = + typeof nextProtocolVoteBefore === 'undefined' + ? undefined + : ensureBigInt(nextProtocolVoteBefore); this.attribute_map = { currentProtocol: 'current-protocol', @@ -2590,7 +2642,7 @@ export class BlockUpgradeVote extends BaseModel { /** * (upgradedelay) Indicates the time between acceptance and execution. */ - public upgradeDelay?: number | bigint; + public upgradeDelay?: bigint; /** * (upgradeprop) Indicates a proposed upgrade. @@ -2614,7 +2666,10 @@ export class BlockUpgradeVote extends BaseModel { }) { super(); this.upgradeApprove = upgradeApprove; - this.upgradeDelay = upgradeDelay; + this.upgradeDelay = + typeof upgradeDelay === 'undefined' + ? undefined + : ensureBigInt(upgradeDelay); this.upgradePropose = upgradePropose; this.attribute_map = { @@ -2648,7 +2703,7 @@ export class Box extends BaseModel { /** * The round for which this information is relevant */ - public round: number | bigint; + public round: bigint; /** * (value) box value, base64 encoded. @@ -2672,7 +2727,7 @@ export class Box extends BaseModel { }) { super(); this.name = typeof name === 'string' ? base64ToBytes(name) : name; - this.round = round; + this.round = ensureBigInt(round); this.value = typeof value === 'string' ? base64ToBytes(value) : value; this.attribute_map = { @@ -2741,7 +2796,7 @@ export class BoxesResponse extends BaseModel { /** * (appidx) application index. */ - public applicationId: number | bigint; + public applicationId: bigint; public boxes: BoxDescriptor[]; @@ -2768,7 +2823,7 @@ export class BoxesResponse extends BaseModel { nextToken?: string; }) { super(); - this.applicationId = applicationId; + this.applicationId = ensureBigInt(applicationId); this.boxes = boxes; this.nextToken = nextToken; @@ -2849,7 +2904,7 @@ export class EvalDelta extends BaseModel { /** * (at) delta action. */ - public action: number | bigint; + public action: number; /** * (bs) bytes value. @@ -2859,7 +2914,7 @@ export class EvalDelta extends BaseModel { /** * (ui) uint value. */ - public uint?: number | bigint; + public uint?: bigint; /** * Creates a new `EvalDelta` object. @@ -2877,9 +2932,9 @@ export class EvalDelta extends BaseModel { uint?: number | bigint; }) { super(); - this.action = action; + this.action = ensureSafeInteger(action); this.bytes = bytes; - this.uint = uint; + this.uint = typeof uint === 'undefined' ? undefined : ensureBigInt(uint); this.attribute_map = { action: 'action', @@ -2948,7 +3003,7 @@ export class HashFactory extends BaseModel { /** * (t) */ - public hashType?: number | bigint; + public hashType?: number; /** * Creates a new `HashFactory` object. @@ -2956,7 +3011,8 @@ export class HashFactory extends BaseModel { */ constructor({ hashType }: { hashType?: number | bigint }) { super(); - this.hashType = hashType; + this.hashType = + typeof hashType === 'undefined' ? undefined : ensureSafeInteger(hashType); this.attribute_map = { hashType: 'hash-type', @@ -2983,7 +3039,7 @@ export class HealthCheck extends BaseModel { public message: string; - public round: number | bigint; + public round: bigint; /** * Current version. @@ -3025,7 +3081,7 @@ export class HealthCheck extends BaseModel { this.dbAvailable = dbAvailable; this.isMigrating = isMigrating; this.message = message; - this.round = round; + this.round = ensureBigInt(round); this.version = version; this.data = data; this.errors = errors; @@ -3080,17 +3136,17 @@ export class IndexerStateProofMessage extends BaseModel { /** * (f) */ - public firstAttestedRound?: number | bigint; + public firstAttestedRound?: bigint; /** * (l) */ - public latestAttestedRound?: number | bigint; + public latestAttestedRound?: bigint; /** * (P) */ - public lnProvenWeight?: number | bigint; + public lnProvenWeight?: bigint; /** * (v) @@ -3123,9 +3179,18 @@ export class IndexerStateProofMessage extends BaseModel { typeof blockHeadersCommitment === 'string' ? base64ToBytes(blockHeadersCommitment) : blockHeadersCommitment; - this.firstAttestedRound = firstAttestedRound; - this.latestAttestedRound = latestAttestedRound; - this.lnProvenWeight = lnProvenWeight; + this.firstAttestedRound = + typeof firstAttestedRound === 'undefined' + ? undefined + : ensureBigInt(firstAttestedRound); + this.latestAttestedRound = + typeof latestAttestedRound === 'undefined' + ? undefined + : ensureBigInt(latestAttestedRound); + this.lnProvenWeight = + typeof lnProvenWeight === 'undefined' + ? undefined + : ensureBigInt(lnProvenWeight); this.votersCommitment = typeof votersCommitment === 'string' ? base64ToBytes(votersCommitment) @@ -3167,7 +3232,7 @@ export class MerkleArrayProof extends BaseModel { /** * (td) */ - public treeDepth?: number | bigint; + public treeDepth?: number; /** * Creates a new `MerkleArrayProof` object. @@ -3187,7 +3252,10 @@ export class MerkleArrayProof extends BaseModel { super(); this.hashFactory = hashFactory; this.path = path; - this.treeDepth = treeDepth; + this.treeDepth = + typeof treeDepth === 'undefined' + ? undefined + : ensureSafeInteger(treeDepth); this.attribute_map = { hashFactory: 'hash-factory', @@ -3217,7 +3285,7 @@ export class MerkleArrayProof extends BaseModel { export class MiniAssetHolding extends BaseModel { public address: string; - public amount: number | bigint; + public amount: bigint; public isFrozen: boolean; @@ -3229,12 +3297,12 @@ export class MiniAssetHolding extends BaseModel { /** * Round during which the account opted into the asset. */ - public optedInAtRound?: number | bigint; + public optedInAtRound?: bigint; /** * Round during which the account opted out of the asset. */ - public optedOutAtRound?: number | bigint; + public optedOutAtRound?: bigint; /** * Creates a new `MiniAssetHolding` object. @@ -3262,11 +3330,17 @@ export class MiniAssetHolding extends BaseModel { }) { super(); this.address = address; - this.amount = amount; + this.amount = ensureBigInt(amount); this.isFrozen = isFrozen; this.deleted = deleted; - this.optedInAtRound = optedInAtRound; - this.optedOutAtRound = optedOutAtRound; + this.optedInAtRound = + typeof optedInAtRound === 'undefined' + ? undefined + : ensureBigInt(optedInAtRound); + this.optedOutAtRound = + typeof optedOutAtRound === 'undefined' + ? undefined + : ensureBigInt(optedOutAtRound); this.attribute_map = { address: 'address', @@ -3355,7 +3429,7 @@ export class StateProofFields extends BaseModel { /** * (pr) Sequence of reveal positions. */ - public positionsToReveal?: (number | bigint)[]; + public positionsToReveal?: bigint[]; /** * (r) Note that this is actually stored as a map[uint64] - Reveal in the actual @@ -3366,7 +3440,7 @@ export class StateProofFields extends BaseModel { /** * (v) Salt version of the merkle signature. */ - public saltVersion?: number | bigint; + public saltVersion?: number; /** * (c) @@ -3381,7 +3455,7 @@ export class StateProofFields extends BaseModel { /** * (w) */ - public signedWeight?: number | bigint; + public signedWeight?: bigint; /** * Creates a new `StateProofFields` object. @@ -3413,13 +3487,22 @@ export class StateProofFields extends BaseModel { }) { super(); this.partProofs = partProofs; - this.positionsToReveal = positionsToReveal; + this.positionsToReveal = + typeof positionsToReveal === 'undefined' + ? undefined + : positionsToReveal.map(ensureBigInt); this.reveals = reveals; - this.saltVersion = saltVersion; + this.saltVersion = + typeof saltVersion === 'undefined' + ? undefined + : ensureSafeInteger(saltVersion); this.sigCommit = typeof sigCommit === 'string' ? base64ToBytes(sigCommit) : sigCommit; this.sigProofs = sigProofs; - this.signedWeight = signedWeight; + this.signedWeight = + typeof signedWeight === 'undefined' + ? undefined + : ensureBigInt(signedWeight); this.attribute_map = { partProofs: 'part-proofs', @@ -3466,7 +3549,7 @@ export class StateProofParticipant extends BaseModel { /** * (w) */ - public weight?: number | bigint; + public weight?: bigint; /** * Creates a new `StateProofParticipant` object. @@ -3482,7 +3565,8 @@ export class StateProofParticipant extends BaseModel { }) { super(); this.verifier = verifier; - this.weight = weight; + this.weight = + typeof weight === 'undefined' ? undefined : ensureBigInt(weight); this.attribute_map = { verifier: 'verifier', @@ -3516,7 +3600,7 @@ export class StateProofReveal extends BaseModel { * The position in the signature and participants arrays corresponding to this * entry. */ - public position?: number | bigint; + public position?: bigint; /** * (s) @@ -3541,7 +3625,8 @@ export class StateProofReveal extends BaseModel { }) { super(); this.participant = participant; - this.position = position; + this.position = + typeof position === 'undefined' ? undefined : ensureBigInt(position); this.sigSlot = sigSlot; this.attribute_map = { @@ -3573,7 +3658,7 @@ export class StateProofSigSlot extends BaseModel { /** * (l) The total weight of signatures in the lower-numbered slots. */ - public lowerSigWeight?: number | bigint; + public lowerSigWeight?: bigint; public signature?: StateProofSignature; @@ -3590,7 +3675,10 @@ export class StateProofSigSlot extends BaseModel { signature?: StateProofSignature; }) { super(); - this.lowerSigWeight = lowerSigWeight; + this.lowerSigWeight = + typeof lowerSigWeight === 'undefined' + ? undefined + : ensureBigInt(lowerSigWeight); this.signature = signature; this.attribute_map = { @@ -3616,7 +3704,7 @@ export class StateProofSigSlot extends BaseModel { export class StateProofSignature extends BaseModel { public falconSignature?: Uint8Array; - public merkleArrayIndex?: number | bigint; + public merkleArrayIndex?: number; public proof?: MerkleArrayProof; @@ -3648,7 +3736,10 @@ export class StateProofSignature extends BaseModel { typeof falconSignature === 'string' ? base64ToBytes(falconSignature) : falconSignature; - this.merkleArrayIndex = merkleArrayIndex; + this.merkleArrayIndex = + typeof merkleArrayIndex === 'undefined' + ? undefined + : ensureSafeInteger(merkleArrayIndex); this.proof = proof; this.verifyingKey = typeof verifyingKey === 'string' @@ -3683,18 +3774,18 @@ export class StateProofTracking extends BaseModel { /** * (n) Next round for which we will accept a state proof transaction. */ - public nextRound?: number | bigint; + public nextRound?: bigint; /** * (t) The total number of microalgos held by the online accounts during the * StateProof round. */ - public onlineTotalWeight?: number | bigint; + public onlineTotalWeight?: bigint; /** * State Proof Type. Note the raw object uses map with this as key. */ - public type?: number | bigint; + public type?: number; /** * (v) Root of a vector commitment containing online accounts that will help sign @@ -3723,9 +3814,14 @@ export class StateProofTracking extends BaseModel { votersCommitment?: string | Uint8Array; }) { super(); - this.nextRound = nextRound; - this.onlineTotalWeight = onlineTotalWeight; - this.type = type; + this.nextRound = + typeof nextRound === 'undefined' ? undefined : ensureBigInt(nextRound); + this.onlineTotalWeight = + typeof onlineTotalWeight === 'undefined' + ? undefined + : ensureBigInt(onlineTotalWeight); + this.type = + typeof type === 'undefined' ? undefined : ensureSafeInteger(type); this.votersCommitment = typeof votersCommitment === 'string' ? base64ToBytes(votersCommitment) @@ -3761,7 +3857,7 @@ export class StateProofVerifier extends BaseModel { /** * (lf) Key lifetime. */ - public keyLifetime?: number | bigint; + public keyLifetime?: bigint; /** * Creates a new `StateProofVerifier` object. @@ -3778,7 +3874,10 @@ export class StateProofVerifier extends BaseModel { super(); this.commitment = typeof commitment === 'string' ? base64ToBytes(commitment) : commitment; - this.keyLifetime = keyLifetime; + this.keyLifetime = + typeof keyLifetime === 'undefined' + ? undefined + : ensureBigInt(keyLifetime); this.attribute_map = { commitment: 'commitment', @@ -3807,12 +3906,12 @@ export class StateSchema extends BaseModel { /** * Maximum number of TEAL byte slices that may be stored in the key/value store. */ - public numByteSlice: number | bigint; + public numByteSlice: number; /** * Maximum number of TEAL uints that may be stored in the key/value store. */ - public numUint: number | bigint; + public numUint: number; /** * Creates a new `StateSchema` object. @@ -3827,8 +3926,8 @@ export class StateSchema extends BaseModel { numUint: number | bigint; }) { super(); - this.numByteSlice = numByteSlice; - this.numUint = numUint; + this.numByteSlice = ensureSafeInteger(numByteSlice); + this.numUint = ensureSafeInteger(numUint); this.attribute_map = { numByteSlice: 'num-byte-slice', @@ -3907,12 +4006,12 @@ export class TealValue extends BaseModel { /** * (tt) value type. Value `1` refers to **bytes**, value `2` refers to **uint** */ - public type: number | bigint; + public type: number; /** * (ui) uint value. */ - public uint: number | bigint; + public uint: bigint; /** * Creates a new `TealValue` object. @@ -3931,8 +4030,8 @@ export class TealValue extends BaseModel { }) { super(); this.bytes = bytes; - this.type = type; - this.uint = uint; + this.type = ensureSafeInteger(type); + this.uint = ensureBigInt(uint); this.attribute_map = { bytes: 'bytes', @@ -3970,17 +4069,17 @@ export class Transaction extends BaseModel { /** * (fee) Transaction fee. */ - public fee: number | bigint; + public fee: bigint; /** * (fv) First valid round for this transaction. */ - public firstValid: number | bigint; + public firstValid: bigint; /** * (lv) Last valid round for this transaction. */ - public lastValid: number | bigint; + public lastValid: bigint; /** * (snd) Sender's address. @@ -4027,28 +4126,28 @@ export class Transaction extends BaseModel { /** * (rc) rewards applied to close-remainder-to account. */ - public closeRewards?: number | bigint; + public closeRewards?: bigint; /** * (ca) closing amount for transaction. */ - public closingAmount?: number | bigint; + public closingAmount?: bigint; /** * Round when the transaction was confirmed. */ - public confirmedRound?: number | bigint; + public confirmedRound?: bigint; /** * Specifies an application index (ID) if an application was created with this * transaction. */ - public createdApplicationIndex?: number | bigint; + public createdApplicationIndex?: bigint; /** * Specifies an asset index (ID) if an asset was created with this transaction. */ - public createdAssetIndex?: number | bigint; + public createdAssetIndex?: bigint; /** * (gh) Hash of genesis block. @@ -4086,7 +4185,7 @@ export class Transaction extends BaseModel { /** * Offset into the round where this transaction was confirmed. */ - public intraRoundOffset?: number | bigint; + public intraRoundOffset?: number; /** * Fields for a keyreg transaction. @@ -4130,7 +4229,7 @@ export class Transaction extends BaseModel { /** * (rr) rewards applied to receiver account. */ - public receiverRewards?: number | bigint; + public receiverRewards?: bigint; /** * (rekey) when included in a valid transaction, the accounts auth addr will be @@ -4142,12 +4241,12 @@ export class Transaction extends BaseModel { /** * Time when the block this transaction is in was confirmed. */ - public roundTime?: number | bigint; + public roundTime?: number; /** * (rs) rewards applied to sender account. */ - public senderRewards?: number | bigint; + public senderRewards?: bigint; /** * Validation signature associated with some data. Only one of the signatures @@ -4324,20 +4423,35 @@ export class Transaction extends BaseModel { txType?: string; }) { super(); - this.fee = fee; - this.firstValid = firstValid; - this.lastValid = lastValid; + this.fee = ensureBigInt(fee); + this.firstValid = ensureBigInt(firstValid); + this.lastValid = ensureBigInt(lastValid); this.sender = sender; this.applicationTransaction = applicationTransaction; this.assetConfigTransaction = assetConfigTransaction; this.assetFreezeTransaction = assetFreezeTransaction; this.assetTransferTransaction = assetTransferTransaction; this.authAddr = authAddr; - this.closeRewards = closeRewards; - this.closingAmount = closingAmount; - this.confirmedRound = confirmedRound; - this.createdApplicationIndex = createdApplicationIndex; - this.createdAssetIndex = createdAssetIndex; + this.closeRewards = + typeof closeRewards === 'undefined' + ? undefined + : ensureBigInt(closeRewards); + this.closingAmount = + typeof closingAmount === 'undefined' + ? undefined + : ensureBigInt(closingAmount); + this.confirmedRound = + typeof confirmedRound === 'undefined' + ? undefined + : ensureBigInt(confirmedRound); + this.createdApplicationIndex = + typeof createdApplicationIndex === 'undefined' + ? undefined + : ensureBigInt(createdApplicationIndex); + this.createdAssetIndex = + typeof createdAssetIndex === 'undefined' + ? undefined + : ensureBigInt(createdAssetIndex); this.genesisHash = typeof genesisHash === 'string' ? base64ToBytes(genesisHash) @@ -4347,17 +4461,29 @@ export class Transaction extends BaseModel { this.group = typeof group === 'string' ? base64ToBytes(group) : group; this.id = id; this.innerTxns = innerTxns; - this.intraRoundOffset = intraRoundOffset; + this.intraRoundOffset = + typeof intraRoundOffset === 'undefined' + ? undefined + : ensureSafeInteger(intraRoundOffset); this.keyregTransaction = keyregTransaction; this.lease = typeof lease === 'string' ? base64ToBytes(lease) : lease; this.localStateDelta = localStateDelta; this.logs = logs; this.note = typeof note === 'string' ? base64ToBytes(note) : note; this.paymentTransaction = paymentTransaction; - this.receiverRewards = receiverRewards; + this.receiverRewards = + typeof receiverRewards === 'undefined' + ? undefined + : ensureBigInt(receiverRewards); this.rekeyTo = rekeyTo; - this.roundTime = roundTime; - this.senderRewards = senderRewards; + this.roundTime = + typeof roundTime === 'undefined' + ? undefined + : ensureSafeInteger(roundTime); + this.senderRewards = + typeof senderRewards === 'undefined' + ? undefined + : ensureBigInt(senderRewards); this.signature = signature; this.stateProofTransaction = stateProofTransaction; this.txType = txType; @@ -4513,7 +4639,7 @@ export class TransactionApplication extends BaseModel { /** * (apid) ID of the application being configured or empty if creating. */ - public applicationId: number | bigint; + public applicationId: bigint; /** * (apat) List of accounts in addition to the sender that may be accessed from the @@ -4546,20 +4672,20 @@ export class TransactionApplication extends BaseModel { /** * (epp) specifies the additional app program len requested in pages. */ - public extraProgramPages?: number | bigint; + public extraProgramPages?: number; /** * (apfa) Lists the applications in addition to the application-id whose global * states may be accessed by this application's approval-program and * clear-state-program. The access is read-only. */ - public foreignApps?: (number | bigint)[]; + public foreignApps?: bigint[]; /** * (apas) lists the assets whose parameters may be accessed by this application's * ApprovalProgram and ClearStateProgram. The access is read-only. */ - public foreignAssets?: (number | bigint)[]; + public foreignAssets?: bigint[]; /** * Represents a (apls) local-state or (apgs) global-state schema. These schemas @@ -4655,7 +4781,7 @@ export class TransactionApplication extends BaseModel { onCompletion?: string; }) { super(); - this.applicationId = applicationId; + this.applicationId = ensureBigInt(applicationId); this.accounts = accounts; this.applicationArgs = applicationArgs; this.approvalProgram = @@ -4666,9 +4792,18 @@ export class TransactionApplication extends BaseModel { typeof clearStateProgram === 'string' ? base64ToBytes(clearStateProgram) : clearStateProgram; - this.extraProgramPages = extraProgramPages; - this.foreignApps = foreignApps; - this.foreignAssets = foreignAssets; + this.extraProgramPages = + typeof extraProgramPages === 'undefined' + ? undefined + : ensureSafeInteger(extraProgramPages); + this.foreignApps = + typeof foreignApps === 'undefined' + ? undefined + : foreignApps.map(ensureBigInt); + this.foreignAssets = + typeof foreignAssets === 'undefined' + ? undefined + : foreignAssets.map(ensureBigInt); this.globalStateSchema = globalStateSchema; this.localStateSchema = localStateSchema; this.onCompletion = onCompletion; @@ -4731,7 +4866,7 @@ export class TransactionAssetConfig extends BaseModel { /** * (xaid) ID of the asset being configured or empty if creating. */ - public assetId?: number | bigint; + public assetId?: bigint; /** * AssetParams specifies the parameters for an asset. @@ -4757,7 +4892,8 @@ export class TransactionAssetConfig extends BaseModel { params?: AssetParams; }) { super(); - this.assetId = assetId; + this.assetId = + typeof assetId === 'undefined' ? undefined : ensureBigInt(assetId); this.params = params; this.attribute_map = { @@ -4796,7 +4932,7 @@ export class TransactionAssetFreeze extends BaseModel { /** * (faid) ID of the asset being frozen or thawed. */ - public assetId: number | bigint; + public assetId: bigint; /** * (afrz) The new freeze status. @@ -4820,7 +4956,7 @@ export class TransactionAssetFreeze extends BaseModel { }) { super(); this.address = address; - this.assetId = assetId; + this.assetId = ensureBigInt(assetId); this.newFreezeStatus = newFreezeStatus; this.attribute_map = { @@ -4862,12 +4998,12 @@ export class TransactionAssetTransfer extends BaseModel { * (aamt) Amount of asset to transfer. A zero amount transferred to self allocates * that asset in the account's Assets map. */ - public amount: number | bigint; + public amount: bigint; /** * (xaid) ID of the asset being transferred. */ - public assetId: number | bigint; + public assetId: bigint; /** * (arcv) Recipient address of the transfer. @@ -4877,7 +5013,7 @@ export class TransactionAssetTransfer extends BaseModel { /** * Number of assets transferred to the close-to account as part of the transaction. */ - public closeAmount?: number | bigint; + public closeAmount?: bigint; /** * (aclose) Indicates that the asset should be removed from the account's Assets @@ -4923,10 +5059,13 @@ export class TransactionAssetTransfer extends BaseModel { sender?: string; }) { super(); - this.amount = amount; - this.assetId = assetId; + this.amount = ensureBigInt(amount); + this.assetId = ensureBigInt(assetId); this.receiver = receiver; - this.closeAmount = closeAmount; + this.closeAmount = + typeof closeAmount === 'undefined' + ? undefined + : ensureBigInt(closeAmount); this.closeTo = closeTo; this.sender = sender; @@ -4988,17 +5127,17 @@ export class TransactionKeyreg extends BaseModel { /** * (votefst) First round this participation key is valid. */ - public voteFirstValid?: number | bigint; + public voteFirstValid?: bigint; /** * (votekd) Number of subkeys in each batch of participation keys. */ - public voteKeyDilution?: number | bigint; + public voteKeyDilution?: bigint; /** * (votelst) Last round this participation key is valid. */ - public voteLastValid?: number | bigint; + public voteLastValid?: bigint; /** * (votekey) Participation public key used in key registration transactions. @@ -5043,9 +5182,18 @@ export class TransactionKeyreg extends BaseModel { typeof stateProofKey === 'string' ? base64ToBytes(stateProofKey) : stateProofKey; - this.voteFirstValid = voteFirstValid; - this.voteKeyDilution = voteKeyDilution; - this.voteLastValid = voteLastValid; + this.voteFirstValid = + typeof voteFirstValid === 'undefined' + ? undefined + : ensureBigInt(voteFirstValid); + this.voteKeyDilution = + typeof voteKeyDilution === 'undefined' + ? undefined + : ensureBigInt(voteKeyDilution); + this.voteLastValid = + typeof voteLastValid === 'undefined' + ? undefined + : ensureBigInt(voteLastValid); this.voteParticipationKey = typeof voteParticipationKey === 'string' ? base64ToBytes(voteParticipationKey) @@ -5087,7 +5235,7 @@ export class TransactionPayment extends BaseModel { /** * (amt) number of MicroAlgos intended to be transferred. */ - public amount: number | bigint; + public amount: bigint; /** * (rcv) receiver's address. @@ -5098,7 +5246,7 @@ export class TransactionPayment extends BaseModel { * Number of MicroAlgos that were sent to the close-remainder-to address when * closing the sender account. */ - public closeAmount?: number | bigint; + public closeAmount?: bigint; /** * (close) when set, indicates that the sending account should be closed and all @@ -5127,9 +5275,12 @@ export class TransactionPayment extends BaseModel { closeRemainderTo?: string; }) { super(); - this.amount = amount; + this.amount = ensureBigInt(amount); this.receiver = receiver; - this.closeAmount = closeAmount; + this.closeAmount = + typeof closeAmount === 'undefined' + ? undefined + : ensureBigInt(closeAmount); this.closeRemainderTo = closeRemainderTo; this.attribute_map = { @@ -5164,7 +5315,7 @@ export class TransactionResponse extends BaseModel { /** * Round at which the results were computed. */ - public currentRound: number | bigint; + public currentRound: bigint; /** * Contains all fields common to all transactions and serves as an envelope to all @@ -5192,7 +5343,7 @@ export class TransactionResponse extends BaseModel { transaction: Transaction; }) { super(); - this.currentRound = currentRound; + this.currentRound = ensureBigInt(currentRound); this.transaction = transaction; this.attribute_map = { @@ -5396,12 +5547,12 @@ export class TransactionSignatureMultisig extends BaseModel { /** * (thr) */ - public threshold?: number | bigint; + public threshold?: number; /** * (v) */ - public version?: number | bigint; + public version?: number; /** * Creates a new `TransactionSignatureMultisig` object. @@ -5420,8 +5571,12 @@ export class TransactionSignatureMultisig extends BaseModel { }) { super(); this.subsignature = subsignature; - this.threshold = threshold; - this.version = version; + this.threshold = + typeof threshold === 'undefined' + ? undefined + : ensureSafeInteger(threshold); + this.version = + typeof version === 'undefined' ? undefined : ensureSafeInteger(version); this.attribute_map = { subsignature: 'subsignature', @@ -5519,7 +5674,7 @@ export class TransactionStateProof extends BaseModel { * (sptype) Type of the state proof. Integer representing an entry defined in * protocol/stateproof.go */ - public stateProofType?: number | bigint; + public stateProofType?: number; /** * Creates a new `TransactionStateProof` object. @@ -5542,7 +5697,10 @@ export class TransactionStateProof extends BaseModel { super(); this.message = message; this.stateProof = stateProof; - this.stateProofType = stateProofType; + this.stateProofType = + typeof stateProofType === 'undefined' + ? undefined + : ensureSafeInteger(stateProofType); this.attribute_map = { message: 'message', @@ -5578,7 +5736,7 @@ export class TransactionsResponse extends BaseModel { /** * Round at which the results were computed. */ - public currentRound: number | bigint; + public currentRound: bigint; public transactions: Transaction[]; @@ -5605,7 +5763,7 @@ export class TransactionsResponse extends BaseModel { nextToken?: string; }) { super(); - this.currentRound = currentRound; + this.currentRound = ensureBigInt(currentRound); this.transactions = transactions; this.nextToken = nextToken; diff --git a/src/client/v2/indexer/searchForApplicationBoxes.ts b/src/client/v2/indexer/searchForApplicationBoxes.ts index 4eee8de22..3903855bb 100644 --- a/src/client/v2/indexer/searchForApplicationBoxes.ts +++ b/src/client/v2/indexer/searchForApplicationBoxes.ts @@ -1,6 +1,5 @@ import JSONRequest from '../jsonrequest.js'; import { HTTPClient } from '../../client.js'; -import IntDecoding from '../../../types/intDecoding.js'; import { BoxesResponse } from './models/types.js'; export default class SearchForApplicationBoxes extends JSONRequest< @@ -35,10 +34,9 @@ export default class SearchForApplicationBoxes extends JSONRequest< */ constructor( c: HTTPClient, - intDecoding: IntDecoding, private index: number ) { - super(c, intDecoding); + super(c); } /** diff --git a/src/client/v2/jsonrequest.ts b/src/client/v2/jsonrequest.ts index 96da8ef76..3997474b4 100644 --- a/src/client/v2/jsonrequest.ts +++ b/src/client/v2/jsonrequest.ts @@ -14,18 +14,13 @@ export default abstract class JSONRequest< > { c: HTTPClient; query: Record; - intDecoding: IntDecoding; /** * @param client - HTTPClient object. - * @param intDecoding - The method to use - * for decoding integers from this request's response. See the setIntDecoding method for more - * details. */ - constructor(client: HTTPClient, intDecoding?: IntDecoding) { + constructor(client: HTTPClient) { this.c = client; this.query = {}; - this.intDecoding = intDecoding || IntDecoding.DEFAULT; } /** @@ -54,11 +49,13 @@ export default abstract class JSONRequest< * @category JSONRequest */ async do(headers: Record = {}): Promise { - const jsonOptions: Record = {}; - if (this.intDecoding !== 'default') { - jsonOptions.intDecoding = this.intDecoding; - } - const res = await this.c.get(this.path(), this.query, headers, jsonOptions); + const res = await this.c.get({ + relativePath: this.path(), + parseBody: true, + jsonOptions: { intDecoding: IntDecoding.BIGINT }, + query: this.query, + requestHeaders: headers, + }); return this.prepare(res.body); } @@ -69,35 +66,13 @@ export default abstract class JSONRequest< * @category JSONRequest */ async doRaw(headers: Record = {}): Promise { - const res = await this.c.get(this.path(), this.query, headers, {}, false); + const res = await this.c.get({ + relativePath: this.path(), + parseBody: false, + jsonOptions: { intDecoding: IntDecoding.BIGINT }, + query: this.query, + requestHeaders: headers, + }); return res.body; } - - /** - * Configure how integers in this request's JSON response will be decoded. - * - * The options are: - * * "default": Integers will be decoded according to JSON.parse, meaning they will all be - * Numbers and any values greater than Number.MAX_SAFE_INTEGER will lose precision. - * * "safe": All integers will be decoded as Numbers, but if any values are greater than - * Number.MAX_SAFE_INTEGER an error will be thrown. - * * "mixed": Integers will be decoded as Numbers if they are less than or equal to - * Number.MAX_SAFE_INTEGER, otherwise they will be decoded as BigInts. - * * "bigint": All integers will be decoded as BigInts. - * - * @param method - The method to use when parsing the - * response for this request. Must be one of "default", "safe", "mixed", or "bigint". - * @category JSONRequest - */ - setIntDecoding(method: IntDecoding) { - if ( - method !== 'default' && - method !== 'safe' && - method !== 'mixed' && - method !== 'bigint' - ) - throw new Error(`Invalid method for int decoding: ${method}`); - this.intDecoding = method; - return this; - } } diff --git a/src/client/v2/serviceClient.ts b/src/client/v2/serviceClient.ts index b325964a7..504d74a00 100644 --- a/src/client/v2/serviceClient.ts +++ b/src/client/v2/serviceClient.ts @@ -1,5 +1,4 @@ import { HTTPClient } from '../client.js'; -import IntDecoding from '../../types/intDecoding.js'; import { BaseHTTPClient } from '../baseHTTPClient.js'; import { TokenHeader } from '../urlTokenBaseHTTPClient.js'; @@ -38,8 +37,6 @@ function isBaseHTTPClient( export default abstract class ServiceClient { /** @ignore */ c: HTTPClient; - /** @ignore */ - intDecoding: IntDecoding; constructor( tokenHeaderIdentifier: TokenHeaderIdentifier, @@ -66,24 +63,5 @@ export default abstract class ServiceClient { this.c = new HTTPClient(tokenHeader, baseServer, port, defaultHeaders); } - - this.intDecoding = IntDecoding.DEFAULT; - } - - /** - * Set the default int decoding method for all JSON requests this client creates. - * @param method - \{"default" | "safe" | "mixed" | "bigint"\} method The method to use when parsing the - * response for request. Must be one of "default", "safe", "mixed", or "bigint". See - * JSONRequest.setIntDecoding for more details about what each method does. - */ - setIntEncoding(method: IntDecoding) { - this.intDecoding = method; - } - - /** - * Get the default int decoding method for all JSON requests this client creates. - */ - getIntEncoding() { - return this.intDecoding; } } diff --git a/src/composer.ts b/src/composer.ts index 12f12dad4..5f3cd6a48 100644 --- a/src/composer.ts +++ b/src/composer.ts @@ -33,7 +33,7 @@ import { OnApplicationComplete, SuggestedParams, } from './types/transactions/base.js'; -import { arrayEqual, ensureUint64 } from './utils/utils.js'; +import { arrayEqual, stringifyJSON, ensureUint64 } from './utils/utils.js'; import { waitForConfirmation } from './wait.js'; // First 4 bytes of SHA-512/256 hash of "return" @@ -799,7 +799,7 @@ export class AtomicTransactionComposer { const logs = pendingInfo.logs || []; if (logs.length === 0) { throw new Error( - `App call transaction did not log a return value ${JSON.stringify( + `App call transaction did not log a return value ${stringifyJSON( pendingInfo )}` ); @@ -810,7 +810,7 @@ export class AtomicTransactionComposer { !arrayEqual(lastLog.slice(0, 4), RETURN_PREFIX) ) { throw new Error( - `App call transaction did not log a ABI return value ${JSON.stringify( + `App call transaction did not log a ABI return value ${stringifyJSON( pendingInfo )}` ); diff --git a/src/dryrun.ts b/src/dryrun.ts index 04f971ae4..cd03a7e35 100644 --- a/src/dryrun.ts +++ b/src/dryrun.ts @@ -1,19 +1,20 @@ import { AlgodClient } from './client/v2/algod/algod.js'; import { Account, - AccountStateDelta, Application, ApplicationParams, ApplicationStateSchema, DryrunRequest, DryrunSource, - EvalDeltaKeyValue, + DryrunTxnResult, + DryrunState, TealValue, } from './client/v2/algod/models/types.js'; import { getApplicationAddress } from './encoding/address.js'; import { base64ToBytes, bytesToHex } from './encoding/binarydata.js'; import { SignedTransaction } from './transaction.js'; import { TransactionType } from './types/transactions/index.js'; +import { stringifyJSON } from './utils/utils.js'; const defaultAppId = 1380011588; const defaultMaxWidth = 30; @@ -148,79 +149,7 @@ export async function createDryrun({ }); } -interface StackValueResponse { - type: number; - bytes: string; - uint: number; -} - -class DryrunStackValue { - type: number = 0; - bytes: string = ''; - uint: number = 0; - - constructor(sv: StackValueResponse) { - this.type = sv.type; - this.bytes = sv.bytes; - this.uint = sv.uint; - } - - toString(): string { - if (this.type === 1) { - return `0x${bytesToHex(base64ToBytes(this.bytes))}`; - } - return this.uint.toString(); - } -} - -interface DryrunTraceLineResponse { - error: string; - line: number; - pc: number; - scratch: TealValue[]; - stack: StackValueResponse[]; -} - -class DryrunTraceLine { - error: string = ''; - line: number = 0; - pc: number = 0; - scratch: TealValue[] = []; - stack: DryrunStackValue[] = []; - - constructor(line: DryrunTraceLineResponse) { - this.error = line.error === undefined ? '' : line.error; - this.line = line.line; - this.pc = line.pc; - this.scratch = line.scratch; - this.stack = line.stack.map( - (sv: StackValueResponse) => new DryrunStackValue(sv) - ); - } -} - -class DryrunTrace { - trace: DryrunTraceLine[] = []; - constructor(t: DryrunTraceLineResponse[]) { - if (t == null) return; - this.trace = t.map((line) => new DryrunTraceLine(line)); - } -} - -interface DryrunTransactionResultResponse { - disassembly: string[]; - appCallMessages: string[] | undefined; - localDeltas: AccountStateDelta[] | undefined; - globalDelta: EvalDeltaKeyValue[] | undefined; - cost: number | undefined; - logicSigMessages: string[] | undefined; - logicSigDisassembly: string[] | undefined; - logs: string[] | undefined; - appCallTrace: DryrunTrace | undefined; - logicSigTrace: DryrunTrace | undefined; -} - -interface StackPrinterConfig { +export interface StackPrinterConfig { maxValueWidth: number | undefined; topOfStackFirst: boolean | undefined; } @@ -245,7 +174,7 @@ function scratchToString( continue; } - if (JSON.stringify(prevScratch[idx]) !== JSON.stringify(currScratch[idx])) { + if (stringifyJSON(prevScratch[idx]) !== stringifyJSON(currScratch[idx])) { newScratchIdx = idx; } } @@ -262,7 +191,7 @@ function scratchToString( } function stackToString( - stack: DryrunStackValue[], + stack: TealValue[], reverse: boolean | undefined ): string { const svs = reverse ? stack.reverse() : stack; @@ -280,167 +209,86 @@ function stackToString( .join(', ')}]`; } -class DryrunTransactionResult { - disassembly: string[] = []; - appCallMessages: string[] | undefined = []; - localDeltas: AccountStateDelta[] | undefined = []; - globalDelta: EvalDeltaKeyValue[] | undefined = []; - cost: number | undefined = 0; - logicSigMessages: string[] | undefined = []; - logicSigDisassembly: string[] | undefined = []; - logs: string[] | undefined = []; - - appCallTrace: DryrunTrace | undefined = undefined; - logicSigTrace: DryrunTrace | undefined = undefined; - - required = ['disassembly']; - optionals = [ - 'app-call-messages', - 'local-deltas', - 'global-delta', - 'cost', - 'logic-sig-messages', - 'logic-sig-disassembly', - 'logs', - ]; - - traces = ['app-call-trace', 'logic-sig-trace']; - - constructor(dtr: DryrunTransactionResultResponse | any) { - // Temporary type fix, will be unnecessary in following PR - this.disassembly = dtr.disassembly; - this.appCallMessages = dtr['app-call-messages']; - this.localDeltas = dtr['local-deltas']; - this.globalDelta = dtr['global-delta']; - this.cost = dtr.cost; - this.logicSigMessages = dtr['logic-sig-messages']; - this.logicSigDisassembly = dtr['logic-sig-disassembly']; - this.logs = dtr.logs; - this.appCallTrace = new DryrunTrace(dtr['app-call-trace']); - this.logicSigTrace = new DryrunTrace(dtr['logic-sig-trace']); - } - - appCallRejected(): boolean { - return ( - this.appCallMessages !== undefined && - this.appCallMessages.includes('REJECT') - ); - } - - logicSigRejected(): boolean { - return ( - this.logicSigMessages !== undefined && - this.logicSigMessages.includes('REJECT') - ); - } - - static trace( - drt: DryrunTrace, - disassembly: string[], - spc: StackPrinterConfig - ): string { - const maxWidth = spc.maxValueWidth || defaultMaxWidth; - - // Create the array of arrays, each sub array contains N columns - const lines = [['pc#', 'ln#', 'source', 'scratch', 'stack']]; - for (let idx = 0; idx < drt.trace.length; idx++) { - const { line, error, pc, scratch, stack } = drt.trace[idx]; - - const currScratch = scratch !== undefined ? scratch : []; - const prevScratch = - idx > 0 && drt.trace[idx - 1].scratch !== undefined - ? drt.trace[idx - 1].scratch - : []; - - const src = error === '' ? disassembly[line] : `!! ${error} !!`; - - lines.push([ - pc.toString().padEnd(3, ' '), - line.toString().padEnd(3, ' '), - truncate(src, maxWidth), - truncate(scratchToString(prevScratch, currScratch), maxWidth), - truncate(stackToString(stack, spc.topOfStackFirst), maxWidth), - ]); - } - - // Get the max length for each column - const maxLengths = lines.reduce((prev, curr) => { - const newVal = new Array(lines[0].length).fill(0); - for (let idx = 0; idx < prev.length; idx++) { - newVal[idx] = - curr[idx].length > prev[idx] ? curr[idx].length : prev[idx]; - } - return newVal; - }, new Array(lines[0].length).fill(0)); - - return `${lines - .map((line) => - line - .map((v, idx) => v.padEnd(maxLengths[idx] + 1, ' ')) - .join('|') - .trim() - ) - .join('\n')}\n`; +function dryrunTrace( + trace: DryrunState[], + disassembly: string[], + spc: StackPrinterConfig +): string { + const maxWidth = spc.maxValueWidth || defaultMaxWidth; + + // Create the array of arrays, each sub array contains N columns + const lines = [['pc#', 'ln#', 'source', 'scratch', 'stack']]; + for (let idx = 0; idx < trace.length; idx++) { + const { line, error, pc, scratch, stack } = trace[idx]; + + const currScratch = scratch !== undefined ? scratch : []; + const prevScratch = + idx > 0 && trace[idx - 1].scratch !== undefined + ? trace[idx - 1].scratch! + : []; + + const src = !error ? disassembly[line] : `!! ${error} !!`; + + lines.push([ + pc.toString().padEnd(3, ' '), + line.toString().padEnd(3, ' '), + truncate(src, maxWidth), + truncate(scratchToString(prevScratch, currScratch), maxWidth), + truncate(stackToString(stack, spc.topOfStackFirst), maxWidth), + ]); } - appTrace(spc?: StackPrinterConfig): string { - if (this.appCallTrace === undefined || !this.disassembly) return ''; - - let conf = spc; - if (spc !== undefined) conf = spc; - else { - conf = { - maxValueWidth: defaultMaxWidth, - topOfStackFirst: false, - }; + // Get the max length for each column + const maxLengths = lines.reduce((prev, curr) => { + const newVal = new Array(lines[0].length).fill(0); + for (let idx = 0; idx < prev.length; idx++) { + newVal[idx] = curr[idx].length > prev[idx] ? curr[idx].length : prev[idx]; } - - return DryrunTransactionResult.trace( - this.appCallTrace, - this.disassembly, - conf - ); - } - - lsigTrace(spc?: StackPrinterConfig): string { - if ( - this.logicSigTrace === undefined || - this.logicSigDisassembly === undefined + return newVal; + }, new Array(lines[0].length).fill(0)); + + return `${lines + .map((line) => + line + .map((v, idx) => v.padEnd(maxLengths[idx] + 1, ' ')) + .join('|') + .trim() ) - return ''; - - let conf: StackPrinterConfig; - if (spc !== undefined) conf = spc; - else { - conf = { - maxValueWidth: defaultMaxWidth, - topOfStackFirst: true, - }; - } + .join('\n')}\n`; +} - return DryrunTransactionResult.trace( - this.logicSigTrace, - this.logicSigDisassembly, - conf - ); +export function dryrunTxnResultAppTrace( + result: DryrunTxnResult, + spc?: StackPrinterConfig +): string { + if (!result.appCallTrace || !result.disassembly) return ''; + + let conf = spc; + if (spc !== undefined) conf = spc; + else { + conf = { + maxValueWidth: defaultMaxWidth, + topOfStackFirst: false, + }; } -} -interface DryrunResultResponse { - ['error']: string; - ['protocol-version']: string; - ['txns']: DryrunTransactionResultResponse[]; + return dryrunTrace(result.appCallTrace, result.disassembly, conf); } -export class DryrunResult { - error: string = ''; - protocolVersion: string = ''; - txns: DryrunTransactionResult[] = []; - constructor(drrResp: DryrunResultResponse) { - this.error = drrResp.error; - this.protocolVersion = drrResp['protocol-version']; - this.txns = drrResp.txns.map( - (txn: DryrunTransactionResultResponse) => new DryrunTransactionResult(txn) - ); +export function dryrunTxnResultLogicSigTrace( + result: DryrunTxnResult, + spc?: StackPrinterConfig +): string { + if (!result.logicSigTrace || !result.logicSigDisassembly) return ''; + + let conf: StackPrinterConfig; + if (spc !== undefined) conf = spc; + else { + conf = { + maxValueWidth: defaultMaxWidth, + topOfStackFirst: true, + }; } + + return dryrunTrace(result.logicSigTrace, result.logicSigDisassembly, conf); } diff --git a/src/main.ts b/src/main.ts index 4d86829e0..2e0d9a552 100644 --- a/src/main.ts +++ b/src/main.ts @@ -125,6 +125,7 @@ export { hexToBytes, } from './encoding/binarydata.js'; export { encodeUint64, decodeUint64 } from './encoding/uint64.js'; +export { parseJSON, ParseJSONOptions, stringifyJSON } from './utils/utils.js'; export { default as generateAccount } from './account.js'; export * as modelsv2 from './client/v2/algod/models/types.js'; export * as indexerModels from './client/v2/indexer/models/types.js'; diff --git a/src/types/intDecoding.ts b/src/types/intDecoding.ts index e974b050a..e15659c16 100644 --- a/src/types/intDecoding.ts +++ b/src/types/intDecoding.ts @@ -6,7 +6,7 @@ enum IntDecoding { * All integers will be decoded as Numbers, meaning any values greater than * Number.MAX_SAFE_INTEGER will lose precision. */ - DEFAULT = 'default', + UNSAFE = 'unsafe', /** * All integers will be decoded as Numbers, but if any values are greater than diff --git a/src/utils/utils.ts b/src/utils/utils.ts index 4b085b644..65bedde3d 100644 --- a/src/utils/utils.ts +++ b/src/utils/utils.ts @@ -6,30 +6,25 @@ const JSONbig = JSONbigWithoutConfig({ strict: true, }); -export interface JSONOptions { - intDecoding?: IntDecoding; +export interface ParseJSONOptions { + intDecoding: IntDecoding; } /** * Parse JSON with additional options. * @param str - The JSON string to parse. - * @param options - Options object to configure how integers in - * this request's JSON response will be decoded. Use the `intDecoding` - * property with one of the following options: - * - * * "default": All integers will be decoded as Numbers, meaning any values greater than - * Number.MAX_SAFE_INTEGER will lose precision. - * * "safe": All integers will be decoded as Numbers, but if any values are greater than - * Number.MAX_SAFE_INTEGER an error will be thrown. - * * "mixed": Integers will be decoded as Numbers if they are less than or equal to - * Number.MAX_SAFE_INTEGER, otherwise they will be decoded as BigInts. - * * "bigint": All integers will be decoded as BigInts. - * - * Defaults to "default" if not included. + * @param options - Configures how integers in this JSON string will be decoded. See the + * `IntDecoding` enum for more details. */ -export function parseJSON(str: string, options?: JSONOptions) { - const intDecoding = - options && options.intDecoding ? options.intDecoding : IntDecoding.DEFAULT; +export function parseJSON(str: string, { intDecoding }: ParseJSONOptions) { + if ( + intDecoding !== IntDecoding.SAFE && + intDecoding !== IntDecoding.UNSAFE && + intDecoding !== IntDecoding.BIGINT && + intDecoding !== IntDecoding.MIXED + ) { + throw new Error(`Invalid intDecoding option: ${intDecoding}`); + } return JSONbig.parse(str, (_, value) => { if ( value != null && @@ -42,14 +37,14 @@ export function parseJSON(str: string, options?: JSONOptions) { } if (typeof value === 'bigint') { - if (intDecoding === 'safe' && value > Number.MAX_SAFE_INTEGER) { + if (intDecoding === IntDecoding.SAFE && value > Number.MAX_SAFE_INTEGER) { throw new Error( `Integer exceeds maximum safe integer: ${value.toString()}. Try parsing with a different intDecoding option.` ); } if ( - intDecoding === 'bigint' || - (intDecoding === 'mixed' && value > Number.MAX_SAFE_INTEGER) + intDecoding === IntDecoding.BIGINT || + (intDecoding === IntDecoding.MIXED && value > Number.MAX_SAFE_INTEGER) ) { return value; } @@ -59,7 +54,7 @@ export function parseJSON(str: string, options?: JSONOptions) { } if (typeof value === 'number') { - if (intDecoding === 'bigint' && Number.isInteger(value)) { + if (intDecoding === IntDecoding.BIGINT && Number.isInteger(value)) { return BigInt(value); } } @@ -68,6 +63,25 @@ export function parseJSON(str: string, options?: JSONOptions) { }); } +/** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * + * This functions differs from the built-in JSON.stringify in that it supports serializing BigInts. + * + * This function takes the same arguments as the built-in JSON.stringify function. + * + * @param value - A JavaScript value, usually an object or array, to be converted. + * @param replacer - A function that transforms the results. + * @param space - Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ +export function stringifyJSON( + value: any, + replacer?: (this: any, key: string, value: any) => any, + space?: string | number +): string { + return JSONbig.stringify(value, replacer, space); +} + /** * ArrayEqual takes two arrays and return true if equal, false otherwise */ diff --git a/tests/2.Encoding.ts b/tests/2.Encoding.ts index 08c7ade19..f9f4e4c39 100644 --- a/tests/2.Encoding.ts +++ b/tests/2.Encoding.ts @@ -359,12 +359,12 @@ describe('encoding', () => { }); }); - describe('JSON parse BigInt', () => { + describe('JSON BigInt', () => { it('should parse null', () => { const input = 'null'; for (const intDecoding of [ - algosdk.IntDecoding.DEFAULT, + algosdk.IntDecoding.UNSAFE, algosdk.IntDecoding.SAFE, algosdk.IntDecoding.MIXED, algosdk.IntDecoding.BIGINT, @@ -377,6 +377,13 @@ describe('encoding', () => { expected, `Error when intDecoding = ${intDecoding}` ); + + const roundtrip = utils.stringifyJSON(actual); + assert.deepStrictEqual( + roundtrip, + input, + `Error when intDecoding = ${intDecoding}` + ); } }); @@ -384,19 +391,28 @@ describe('encoding', () => { const inputs = ['17', '9007199254740991']; for (const input of inputs) { for (const intDecoding of [ - algosdk.IntDecoding.DEFAULT, + algosdk.IntDecoding.UNSAFE, algosdk.IntDecoding.SAFE, algosdk.IntDecoding.MIXED, algosdk.IntDecoding.BIGINT, ]) { const actual = utils.parseJSON(input, { intDecoding }); const expected = - intDecoding === 'bigint' ? BigInt(input) : Number(input); + intDecoding === algosdk.IntDecoding.BIGINT + ? BigInt(input) + : Number(input); assert.deepStrictEqual( actual, expected, `Error when intDecoding = ${intDecoding}` ); + + const roundtrip = utils.stringifyJSON(actual); + assert.deepStrictEqual( + roundtrip, + input, + `Error when intDecoding = ${intDecoding}` + ); } } }); @@ -406,7 +422,7 @@ describe('encoding', () => { '"IRK7XSCO7LPIBQKIUJXTQ5I7XBP3362ACPME5SOUUIJXN77T44RG4FZSLI"'; for (const intDecoding of [ - algosdk.IntDecoding.DEFAULT, + algosdk.IntDecoding.UNSAFE, algosdk.IntDecoding.SAFE, algosdk.IntDecoding.MIXED, algosdk.IntDecoding.BIGINT, @@ -423,6 +439,13 @@ describe('encoding', () => { expected, `Error when intDecoding = ${intDecoding}` ); + + const roundtrip = utils.stringifyJSON(actual); + assert.deepStrictEqual( + roundtrip, + input, + `Error when intDecoding = ${intDecoding}` + ); } }); @@ -430,7 +453,7 @@ describe('encoding', () => { const input = '{}'; for (const intDecoding of [ - algosdk.IntDecoding.DEFAULT, + algosdk.IntDecoding.UNSAFE, algosdk.IntDecoding.SAFE, algosdk.IntDecoding.MIXED, algosdk.IntDecoding.BIGINT, @@ -443,6 +466,13 @@ describe('encoding', () => { expected, `Error when intDecoding = ${intDecoding}` ); + + const roundtrip = utils.stringifyJSON(actual); + assert.deepStrictEqual( + roundtrip, + input, + `Error when intDecoding = ${intDecoding}` + ); } }); @@ -450,7 +480,7 @@ describe('encoding', () => { const input = '{"a":1,"b":"value","c":[1,2,3],"d":null,"e":{},"f":true}'; for (const intDecoding of [ - algosdk.IntDecoding.DEFAULT, + algosdk.IntDecoding.UNSAFE, algosdk.IntDecoding.SAFE, algosdk.IntDecoding.MIXED, algosdk.IntDecoding.BIGINT, @@ -458,7 +488,7 @@ describe('encoding', () => { const actual = utils.parseJSON(input, { intDecoding }); let expected; - if (intDecoding === 'bigint') { + if (intDecoding === algosdk.IntDecoding.BIGINT) { expected = { a: 1n, b: 'value', @@ -483,6 +513,13 @@ describe('encoding', () => { expected, `Error when intDecoding = ${intDecoding}` ); + + const roundtrip = utils.stringifyJSON(actual); + assert.deepStrictEqual( + roundtrip, + input, + `Error when intDecoding = ${intDecoding}` + ); } }); @@ -495,21 +532,21 @@ describe('encoding', () => { ); for (const intDecoding of [ - algosdk.IntDecoding.DEFAULT, + algosdk.IntDecoding.UNSAFE, algosdk.IntDecoding.MIXED, algosdk.IntDecoding.BIGINT, ]) { const actual = utils.parseJSON(input, { intDecoding }); let expected; - if (intDecoding === 'bigint') { + if (intDecoding === algosdk.IntDecoding.BIGINT) { expected = { a: 0n, b: 9007199254740991n, c: 9007199254740992n, d: 9223372036854775807n, }; - } else if (intDecoding === 'mixed') { + } else if (intDecoding === algosdk.IntDecoding.MIXED) { expected = { a: 0, b: 9007199254740991, @@ -530,6 +567,15 @@ describe('encoding', () => { expected, `Error when intDecoding = ${intDecoding}` ); + + if (intDecoding !== algosdk.IntDecoding.UNSAFE) { + const roundtrip = utils.stringifyJSON(actual); + assert.deepStrictEqual( + roundtrip, + input, + `Error when intDecoding = ${intDecoding}` + ); + } } }); @@ -537,7 +583,7 @@ describe('encoding', () => { const input = '[]'; for (const intDecoding of [ - algosdk.IntDecoding.DEFAULT, + algosdk.IntDecoding.UNSAFE, algosdk.IntDecoding.SAFE, algosdk.IntDecoding.MIXED, algosdk.IntDecoding.BIGINT, @@ -550,6 +596,13 @@ describe('encoding', () => { expected, `Error when intDecoding = ${intDecoding}` ); + + const roundtrip = utils.stringifyJSON(actual); + assert.deepStrictEqual( + roundtrip, + input, + `Error when intDecoding = ${intDecoding}` + ); } }); @@ -557,7 +610,7 @@ describe('encoding', () => { const input = '["test",2,null,[7],{"a":9.5},true]'; for (const intDecoding of [ - algosdk.IntDecoding.DEFAULT, + algosdk.IntDecoding.UNSAFE, algosdk.IntDecoding.SAFE, algosdk.IntDecoding.MIXED, algosdk.IntDecoding.BIGINT, @@ -576,6 +629,13 @@ describe('encoding', () => { expected, `Error when intDecoding = ${intDecoding}` ); + + const roundtrip = utils.stringifyJSON(actual); + assert.deepStrictEqual( + roundtrip, + input, + `Error when intDecoding = ${intDecoding}` + ); } }); @@ -587,21 +647,21 @@ describe('encoding', () => { ); for (const intDecoding of [ - algosdk.IntDecoding.DEFAULT, + algosdk.IntDecoding.UNSAFE, algosdk.IntDecoding.MIXED, algosdk.IntDecoding.BIGINT, ]) { const actual = utils.parseJSON(input, { intDecoding }); let expected; - if (intDecoding === 'bigint') { + if (intDecoding === algosdk.IntDecoding.BIGINT) { expected = [ 0n, 9007199254740991n, 9007199254740992n, 9223372036854775807n, ]; - } else if (intDecoding === 'mixed') { + } else if (intDecoding === algosdk.IntDecoding.MIXED) { expected = [ 0, 9007199254740991, @@ -622,8 +682,35 @@ describe('encoding', () => { expected, `Error when intDecoding = ${intDecoding}` ); + + if (intDecoding !== algosdk.IntDecoding.UNSAFE) { + const roundtrip = utils.stringifyJSON(actual); + assert.deepStrictEqual( + roundtrip, + input, + `Error when intDecoding = ${intDecoding}` + ); + } } }); + + it('should stringify with spacing', () => { + const input = { a: 1, b: 'value', c: [1, 2, 3], d: null, e: {}, f: true }; + const actual = utils.stringifyJSON(input, undefined, 2); + const expected = `{ + "a": 1, + "b": "value", + "c": [ + 1, + 2, + 3 + ], + "d": null, + "e": {}, + "f": true +}`; + assert.strictEqual(actual, expected); + }); }); describe('Base64 decoding utilities', () => { diff --git a/tests/7.AlgoSDK.ts b/tests/7.AlgoSDK.ts index 86d70cd5b..ec0414ec2 100644 --- a/tests/7.AlgoSDK.ts +++ b/tests/7.AlgoSDK.ts @@ -1052,7 +1052,7 @@ describe('Algosdk (AKA end to end)', () => { it('should be properly serialized to JSON', () => { const forEncoding = req.get_obj_for_encoding(); - const actual = JSON.stringify(forEncoding, null, 2); + const actual = algosdk.stringifyJSON(forEncoding, undefined, 2); const expected = `{ "accounts": [ @@ -1110,8 +1110,12 @@ describe('Algosdk (AKA end to end)', () => { ] }`; // Cannot directly compare JSON strings because order of keys is not guaranteed - const actualDecoded = JSON.parse(actual); - const expectedDecoded = JSON.parse(expected); + const actualDecoded = algosdk.parseJSON(actual, { + intDecoding: algosdk.IntDecoding.BIGINT, + }); + const expectedDecoded = algosdk.parseJSON(expected, { + intDecoding: algosdk.IntDecoding.BIGINT, + }); assert.deepStrictEqual(actualDecoded, expectedDecoded); }); diff --git a/tests/9.Client.ts b/tests/9.Client.ts index 53f4116f3..f49d1eceb 100644 --- a/tests/9.Client.ts +++ b/tests/9.Client.ts @@ -68,29 +68,31 @@ describe('client', () => { it('should encode and decode values correctly', () => { const j = '{"total":18446744073709551615, "base":42}'; - let options = { - // intDecoding: IntDecoding.DEFAULT, + let options: utils.ParseJSONOptions = { + intDecoding: IntDecoding.BIGINT, }; let actual = HTTPClient.parseJSON(j, 200, options); - let expected = JSON.parse(j); - assert.strictEqual(actual.total, expected.total); - assert.strictEqual(typeof actual.total, 'number'); + let expected = utils.parseJSON(j, options); + assert.deepStrictEqual(actual, expected); + assert.strictEqual(typeof actual.total, 'bigint'); + assert.strictEqual(typeof actual.base, 'bigint'); options = { - intDecoding: IntDecoding.BIGINT, + intDecoding: IntDecoding.MIXED, }; actual = HTTPClient.parseJSON(j, 200, options); expected = utils.parseJSON(j, options); - assert.strictEqual(actual.total, expected.total); + assert.deepStrictEqual(actual, expected); assert.strictEqual(typeof actual.total, 'bigint'); + assert.strictEqual(typeof actual.base, 'number'); options = { - intDecoding: IntDecoding.MIXED, + intDecoding: IntDecoding.UNSAFE, }; actual = HTTPClient.parseJSON(j, 200, options); expected = utils.parseJSON(j, options); - assert.strictEqual(actual.total, expected.total); - assert.strictEqual(typeof actual.total, 'bigint'); + assert.deepStrictEqual(actual, expected); + assert.strictEqual(typeof actual.total, 'number'); assert.strictEqual(typeof actual.base, 'number'); options = { diff --git a/tests/cucumber/steps/steps.js b/tests/cucumber/steps/steps.js index a1f06889e..107d72aab 100644 --- a/tests/cucumber/steps/steps.js +++ b/tests/cucumber/steps/steps.js @@ -991,7 +991,7 @@ module.exports = function getSteps(options) { this.lv = this.params.lastValid; this.note = undefined; this.gh = this.params.genesisHash; - const parsedIssuance = parseInt(issuance); + const parsedIssuance = BigInt(issuance); const decimals = 0; const defaultFrozen = false; const assetName = this.assetTestFixture.name; @@ -1517,8 +1517,12 @@ module.exports = function getSteps(options) { // them before comparing, which is why we chain encoding/decoding below. if (responseFormat === 'json') { assert.strictEqual( - JSON.stringify(JSON.parse(expectedMockResponse)), - JSON.stringify(this.actualMockResponse) + algosdk.stringifyJSON( + algosdk.parseJSON(expectedMockResponse, { + intDecoding: algosdk.IntDecoding.MIXED, + }) + ), + algosdk.stringifyJSON(this.actualMockResponse) ); } else { assert.deepStrictEqual( @@ -1849,10 +1853,7 @@ module.exports = function getSteps(options) { Then( 'the parsed Node Status response should have a last round of {int}', (lastRound) => { - assert.strictEqual( - lastRound.toString(), - anyNodeStatusResponse.lastRound.toString() - ); + assert.strictEqual(BigInt(lastRound), anyNodeStatusResponse.lastRound); } ); @@ -1866,17 +1867,14 @@ module.exports = function getSteps(options) { 'the parsed Ledger Supply response should have totalMoney {int} onlineMoney {int} on round {int}', (totalMoney, onlineMoney, round) => { assert.strictEqual( - totalMoney.toString(), - anyLedgerSupplyResponse.totalMoney.toString() + BigInt(totalMoney), + anyLedgerSupplyResponse.totalMoney ); assert.strictEqual( - onlineMoney.toString(), - anyLedgerSupplyResponse.onlineMoney.toString() - ); - assert.strictEqual( - round.toString(), - anyLedgerSupplyResponse.currentRound.toString() + BigInt(onlineMoney), + anyLedgerSupplyResponse.onlineMoney ); + assert.strictEqual(BigInt(round), anyLedgerSupplyResponse.currentRound); } ); @@ -1887,10 +1885,7 @@ module.exports = function getSteps(options) { Then( 'the parsed Status After Block response should have a last round of {int}', (lastRound) => { - assert.strictEqual( - lastRound.toString(), - anyNodeStatusResponse.lastRound.toString() - ); + assert.strictEqual(BigInt(lastRound), anyNodeStatusResponse.lastRound); } ); @@ -2393,7 +2388,6 @@ module.exports = function getSteps(options) { When('we make any LookupAssetBalances call', async function () { anyLookupAssetBalancesResponse = await this.indexerClient .lookupAssetBalances() - .setIntDecoding('mixed') .do(); }); @@ -2401,12 +2395,12 @@ module.exports = function getSteps(options) { 'the parsed LookupAssetBalances response should be valid on round {int}, and contain an array of len {int} and element number {int} should have address {string} amount {int} and frozen state {string}', (round, length, idx, address, amount, frozenStateAsString) => { assert.strictEqual( - round, - anyLookupAssetBalancesResponse['current-round'] + anyLookupAssetBalancesResponse['current-round'], + BigInt(round) ); assert.strictEqual( - length, - anyLookupAssetBalancesResponse.balances.length + anyLookupAssetBalancesResponse.balances.length, + length ); if (length === 0) { return; @@ -2416,12 +2410,12 @@ module.exports = function getSteps(options) { frozenState = true; } assert.strictEqual( - amount, - anyLookupAssetBalancesResponse.balances[idx].amount + anyLookupAssetBalancesResponse.balances[idx].amount, + BigInt(amount) ); assert.strictEqual( - frozenState, - anyLookupAssetBalancesResponse.balances[idx]['is-frozen'] + anyLookupAssetBalancesResponse.balances[idx]['is-frozen'], + frozenState ); } ); @@ -2483,7 +2477,6 @@ module.exports = function getSteps(options) { When('we make any LookupAssetTransactions call', async function () { anyLookupAssetTransactionsResponse = await this.indexerClient .lookupAssetTransactions() - .setIntDecoding('mixed') .do(); }); @@ -2491,19 +2484,19 @@ module.exports = function getSteps(options) { 'the parsed LookupAssetTransactions response should be valid on round {int}, and contain an array of len {int} and element number {int} should have sender {string}', (round, length, idx, sender) => { assert.strictEqual( - round, - anyLookupAssetTransactionsResponse['current-round'] + anyLookupAssetTransactionsResponse['current-round'], + BigInt(round) ); assert.strictEqual( - length, - anyLookupAssetTransactionsResponse.transactions.length + anyLookupAssetTransactionsResponse.transactions.length, + length ); if (length === 0) { return; } assert.strictEqual( - sender, - anyLookupAssetTransactionsResponse.transactions[idx].sender + anyLookupAssetTransactionsResponse.transactions[idx].sender, + sender ); } ); @@ -2577,12 +2570,11 @@ module.exports = function getSteps(options) { When('we make any LookupAssetByID call', async function () { anyLookupAssetByIDResponse = await this.indexerClient .lookupAssetByID() - .setIntDecoding('mixed') .do(); }); Then('the parsed LookupAssetByID response should have index {int}', (idx) => { - assert.strictEqual(idx, anyLookupAssetByIDResponse.asset.index); + assert.strictEqual(anyLookupAssetByIDResponse.asset.index, BigInt(idx)); }); let anySearchAccountsResponse; @@ -2726,7 +2718,15 @@ module.exports = function getSteps(options) { let dryrunResponse; When('we make any Dryrun call', async function () { - const dr = new algosdk.modelsv2.DryrunRequest({}); + const dr = new algosdk.modelsv2.DryrunRequest({ + accounts: [], + apps: [], + latestTimestamp: 7, + protocolVersion: 'future', + round: 100, + sources: [], + txns: [], + }); dryrunResponse = await this.v2Client.dryrun(dr).do(); }); @@ -2773,6 +2773,7 @@ module.exports = function getSteps(options) { fieldName: 'lsig', source: new TextDecoder().decode(data), txnIndex: 0, + appIndex: 0, }), ]; break; @@ -2781,6 +2782,11 @@ module.exports = function getSteps(options) { } const dr = new algosdk.modelsv2.DryrunRequest({ + accounts: [], + apps: [], + latestTimestamp: 0, + protocolVersion: '', + round: 0, txns, sources, }); @@ -4390,17 +4396,18 @@ module.exports = function getSteps(options) { 'a dryrun response file {string} and a transaction at index {string}', async function (drrFile, txId) { const drContents = await loadResourceAsJson(drrFile); - const drr = new algosdk.DryrunResult(drContents); + const drr = + algosdk.modelsv2.DryrunResponse.from_obj_for_encoding(drContents); this.txtrace = drr.txns[parseInt(txId)]; } ); Then('calling app trace produces {string}', async function (expected) { - const traceString = this.txtrace.appTrace(); + const traceString = algosdk.dryrunTxnResultAppTrace(this.txtrace); const expectedString = new TextDecoder().decode( await loadResource(expected) ); - assert.deepStrictEqual(traceString, expectedString); + assert.strictEqual(traceString, expectedString); }); When( @@ -4642,7 +4649,7 @@ module.exports = function getSteps(options) { .compile(tealSrc) .sourcemap(true) .do(); - this.rawSourceMap = JSON.stringify(compiledResponse.sourcemap); + this.rawSourceMap = algosdk.stringifyJSON(compiledResponse.sourcemap); } ); diff --git a/v2_TO_v3_MIGRATION_GUIDE.md b/v2_TO_v3_MIGRATION_GUIDE.md index 83cb82751..4f33fe08b 100644 --- a/v2_TO_v3_MIGRATION_GUIDE.md +++ b/v2_TO_v3_MIGRATION_GUIDE.md @@ -273,3 +273,42 @@ We expect most users to not be affected by this, since if you use Algod to get s ### Auction Bids Auction bids have been removed from the library in v3, as they were only relevant to the launch of MainNet. + +### Algod and Indexer Clients + +In v2, the `Algodv2` and `Indexer` clients, as well as each individual request class, had a `setIntDecoding` method which could be used to configure how integers in the response were parsed into either a JavaScript `number` or `bigint`. These methods have been removed in v3. + +Instead, Algod responses are now fully typed, and individual fields are typed as either `number` or `bigint`. The types defined in the `modelsv2` namespace have been updated to reflect this. In v2, these classes used `number | bigint` for all numeric fields, but in v3, they will use either `number` or `bigint` depending on the field. + +Generally speaking, the fields will be `bigint` based on the following criteria: + +- If the field represents an amount of microAlgos or ASA units, it will be `bigint` +- If the field represents a round/block number, it will be `bigint` +- If the field represents an asset or application ID, it will be `bigint` +- If the field represents a timestamp measured in nanoseconds, it will be `bigint` +- If the field can be any value in the uint64 range, it will be `bigint` +- Other fields which are guaranteed to be small will be `number` + +Indexer responses are not yet typed, and all numeric fields are returned as `bigint`. + +### JSON Operations + +In order to facilitate `bigint` as a first-class type in this SDK, additional JSON conversion utilities have been added in v3. These are the `parseJSON` and `stringifyJSON` functions. + +`parseJSON` can be used to parse a JSON string into a JavaScript object, with support for parsing numeric fields as `bigint`s, depending on the provided configuration. + +`stringifyJSON` can be used to convert a JavaScript object containing `bigint`s into a JSON string, something `JSON.stringify` cannot do. + +If your v2 code uses `JSON.parse` or `JSON.stringify` on types which can now contain `bigint`s in v3, such as `Transaction` representations or REST API responses, consider using these new functions instead. + +### IntDecoding + +The `IntDecoding.DEFAULT` option has been renamed to `IntDecoding.UNSAFE` in v3. It behaves identically to the v2 `IntDecoding.DEFAULT` option, but the name has been changed to better reflect the fact that other options should be preferred. + +### Dryrun Utilities + +Due to the fully-typed Algod responses in v3, some of the redundant dryrun types have been removed. + +Specifically, the `DryrunResult` class and its dependent types have been removed in favor of the Algod response model, `modelsv2.DryrunResponse`. + +The `DryrunTransactionResult` class, which made up the elements of the v2 `DryrunResult.txns` array, used to have methods `appTrace` and `lsigTrace`. These have been replaced by the new `dryrunTxnResultAppTrace` and `dryrunTxnResultLogicSigTrace` functions, which accept a `DryrunTxnResult`. These new functions should produce identical results to the old ones.