diff --git a/schemas/allow.js b/schemas/allow.js index ec8dd72..36b0e68 100644 --- a/schemas/allow.js +++ b/schemas/allow.js @@ -27,7 +27,7 @@ const allowSchema = { }, txID: { type: 'string', - pattern: '^[a-zA-Z0-9_-]{43}$' + pattern: '^[a-zA-Z0-9_-]{43}$', }, }, required: ['qty', 'txID'], diff --git a/schemas/claim.js b/schemas/claim.js index 3c022d5..70bc2b1 100644 --- a/schemas/claim.js +++ b/schemas/claim.js @@ -27,7 +27,7 @@ const claimSchema = { }, txID: { type: 'string', - pattern: '^[a-zA-Z0-9_-]{43}$' + pattern: '^[a-zA-Z0-9_-]{43}$', }, }, required: ['qty', 'txID'], diff --git a/schemas/reject.js b/schemas/reject.js index 08ef4ac..17bf5ba 100644 --- a/schemas/reject.js +++ b/schemas/reject.js @@ -27,9 +27,9 @@ const rejectSchema = { pattern: '^[a-zA-Z0-9_-]{43}$', }, qty: { - type: 'number', - minimum: 1, - } + type: 'number', + minimum: 1, + }, }, required: ['tx', 'qty'], additionalProperties: false, diff --git a/schemas/transfer.js b/schemas/transfer.js index 2da00f9..9411c5c 100644 --- a/schemas/transfer.js +++ b/schemas/transfer.js @@ -28,7 +28,7 @@ const transferSchema = { }, }, required: ['target'], - additionalProperties: false, + additionalProperties: true, }; module.exports = { diff --git a/src/actions/write/allow.ts b/src/actions/write/allow.ts index 9930ed2..e246b69 100644 --- a/src/actions/write/allow.ts +++ b/src/actions/write/allow.ts @@ -14,11 +14,10 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ -import { of, Left, Right } from '../../lib/either' +import { Left, Right, of } from '../../lib/either'; -export const allow = (state, action) => of({ state, action }) - .chain(validate) - .map(update) +export const allow = (state, action) => + of({ state, action }).chain(validate).map(update); function update({ state, action }) { state.balances[action.caller] -= action.input.qty; @@ -35,29 +34,26 @@ function update({ state, action }) { } function validate({ state, action }) { - if ( - !Number.isInteger(action.input.qty) || - action.input.qty === undefined - ) { - return Left("Invalid value for quantity. Must be an integer."); + if (!Number.isInteger(action.input.qty) || action.input.qty === undefined) { + return Left('Invalid value for quantity. Must be an integer.'); } if (!action?.input?.target) { - return Left("No target specified."); + return Left('No target specified.'); } if (action.input.target.length !== 43) { - return Left("Target is not valid!"); + return Left('Target is not valid!'); } if (action.input.target === SmartWeave.transaction.id) { - return Left("Cant setup claim to transfer a balance to itself"); + return Left('Cant setup claim to transfer a balance to itself'); } if (action.caller === action.input.target) { - return Left("Invalid balance transfer"); + return Left('Invalid balance transfer'); } if (!state.balances[action.caller]) { - return Left("Caller does not have a balance"); + return Left('Caller does not have a balance'); } if (state.balances[action.caller] < action.input.qty) { - return Left("Caller balance is not high enough."); + return Left('Caller balance is not high enough.'); } return Right({ state, action }); -} \ No newline at end of file +} diff --git a/src/actions/write/claim.ts b/src/actions/write/claim.ts index 7d1c1ea..d1be162 100644 --- a/src/actions/write/claim.ts +++ b/src/actions/write/claim.ts @@ -14,11 +14,10 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ -import { of, Left, Right } from '../../lib/either' +import { Left, Right, of } from '../../lib/either'; -export const claim = (state, action) => of({ state, action }) - .chain(validate) - .map(update) +export const claim = (state, action) => + of({ state, action }).chain(validate).map(update); function update({ state, action, idx }) { if (!state.balances[action.caller]) { @@ -33,28 +32,26 @@ function update({ state, action, idx }) { function validate({ state, action }) { if (!action.input.txID) { - return Left("txID is not found."); + return Left('txID is not found.'); } if (!action.input.qty) { - return Left("claim quantity is not specified."); + return Left('claim quantity is not specified.'); } - const idx = state.claimable.findIndex( - (c) => c.txID === action.input.txID - ); + const idx = state.claimable.findIndex((c) => c.txID === action.input.txID); if (idx < 0) { - return Left("claimable not found."); + return Left('claimable not found.'); } if (state.claimable[idx].qty !== action.input.qty) { - return Left("claimable qty is not equal to claim qty."); + return Left('claimable qty is not equal to claim qty.'); } if (state.claimable[idx].to !== action.caller) { - return Left("claim is not addressed to caller."); + return Left('claim is not addressed to caller.'); } return Right({ state, action, idx }); -} \ No newline at end of file +} diff --git a/src/actions/write/constructor.ts b/src/actions/write/constructor.ts index c1013e6..4b05784 100644 --- a/src/actions/write/constructor.ts +++ b/src/actions/write/constructor.ts @@ -16,27 +16,29 @@ */ export function constructor(state, action) { if (action.input.args) { - state = { - records: {...state.records}, - controllers: [...state.controllers], - ...action.input.args} + state = { + records: state.records, + controllers: state.controllers, + ...action.input.args, + }; } if (!state.claimable) { - state.claimable = [] + state.claimable = []; } if (!state.balances) { - state.balances = {} + state.balances = {}; } if (!action.input?.args?.balances) { - state.balances[action.caller] = 100 + state.balances[action.caller] = 100; } - state.name = action.input?.args?.name ? action.input.args.name : 'AtomicAsset' - state.ticker = action.input?.args?.ticker ? action.input.args.ticker : 'AA' + state.name = action.input?.args?.name + ? action.input.args.name + : 'AtomicAsset'; + state.ticker = action.input?.args?.ticker ? action.input.args.ticker : 'AA'; - return { state } - -} \ No newline at end of file + return { state }; +} diff --git a/src/actions/write/reject.ts b/src/actions/write/reject.ts index 5f7d816..c917da7 100644 --- a/src/actions/write/reject.ts +++ b/src/actions/write/reject.ts @@ -14,49 +14,50 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ -import { AntAction, ANTState } from 'src/types' -import { fromNullable, Left, Right } from '../../lib/either' +import { ANTState, AntAction } from 'src/types'; -export function reject(state: ANTState, action: AntAction) { +import { Left, Right, fromNullable } from '../../lib/either'; - return fromNullable({state, action}) - .chain(validate) - .map(update) +export function reject(state: ANTState, action: AntAction) { + return fromNullable({ state, action }).chain(validate).map(update); } -function update({state, action}) { - const claim = state.claimable.find(c => c.txID === action.input.tx) - +function update({ state, action }) { + const claim = state.claimable.find((c) => c.txID === action.input.tx); + if (!state.balances[claim.from]) { - state.balances[claim.from] = 0 + state.balances[claim.from] = 0; } // add claim amount back to balance - state.balances[claim.from] += claim.qty - + state.balances[claim.from] += claim.qty; + // remove claim - state.claimable = state.claimable.filter(c => c.txID !== claim.txID) - return {state} + state.claimable = state.claimable.filter((c) => c.txID !== claim.txID); + return { state }; } -function validate({state, action}) { +function validate({ state, action }) { if (!action.input.tx) { - return Left('tx is required!') + return Left('tx is required!'); } if (!action.input.qty) { - return Left('qty is required!') + return Left('qty is required!'); } if (action.input.tx.length !== 43) { - return Left('tx is not valid') + return Left('tx is not valid'); } if (!Number.isInteger(action.input.qty)) { - return Left('qty must be an integer') + return Left('qty must be an integer'); } if (state.claimable.filter((c) => c.txID === action.input.tx).length !== 1) { - return Left('claim not found') + return Left('claim not found'); } - if (state.claimable.filter((c) => c.txID === action.input.tx)[0]?.to !== action.caller) { - return Left('claim in not addressed to caller') + if ( + state.claimable.filter((c) => c.txID === action.input.tx)[0]?.to !== + action.caller + ) { + return Left('claim in not addressed to caller'); } - return Right({state, action}) -} \ No newline at end of file + return Right({ state, action }); +} diff --git a/src/actions/write/transferTokens.ts b/src/actions/write/transferTokens.ts index 6a32196..83c2489 100644 --- a/src/actions/write/transferTokens.ts +++ b/src/actions/write/transferTokens.ts @@ -14,10 +14,7 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ -import { - INVALID_INPUT_MESSAGE, - NON_CONTRACT_OWNER_MESSAGE, -} from '../../constants'; +import { INVALID_INPUT_MESSAGE } from '../../constants'; import { ANTState, AntAction, ContractResult } from '../../types'; // composed by ajv at build import { validateTransferTokens } from '../../validations'; @@ -41,10 +38,6 @@ export const transferTokens = async ( throw new ContractError('Invalid token transfer'); } - if (caller !== owner) { - throw new ContractError(NON_CONTRACT_OWNER_MESSAGE); - } - if ( !balances[caller] || balances[caller] == undefined || @@ -58,6 +51,7 @@ export const transferTokens = async ( throw new ContractError(`Caller does not have a token balance!`); } + delete balances[owner]; state.owner = target; delete balances[caller]; balances[target] = 1; diff --git a/src/contract-ucm.ts b/src/contract-ucm.ts index c9bbe1e..03ebc4e 100644 --- a/src/contract-ucm.ts +++ b/src/contract-ucm.ts @@ -32,11 +32,11 @@ import { ANTState, AntAction, ContractResult } from './types'; declare const ContractError; function identity(v) { - return v + return v; } function handleError(msg) { - throw new ContractError(msg) + throw new ContractError(msg); } export async function handle( @@ -46,18 +46,18 @@ export async function handle( const input = action.input; switch (input.function) { - case 'noop': - return { state } + case 'noop': + return { state }; case '__init': return constructor(state, action); case 'allow': - return allow(state, action).fold(handleError, identity) + return allow(state, action).fold(handleError, identity); case 'reject': - return reject(state, action).fold(handleError, identity) + return reject(state, action).fold(handleError, identity); case 'claim': - return claim(state, action).fold(handleError, identity) + return claim(state, action).fold(handleError, identity); case 'transfer': - // atomic token has its own version, the ANT one should work as well. + // atomic token has its own version, the ANT one should work as well. return await transferTokens(state, action); case 'setRecord': return await setRecord(state, action); diff --git a/src/lib/either.ts b/src/lib/either.ts index 7dd1548..8e6d524 100644 --- a/src/lib/either.ts +++ b/src/lib/either.ts @@ -33,10 +33,8 @@ * @returns {Either} */ - /* eslint-disable @typescript-eslint/no-unused-vars */ - export const Right = (x) => ({ isLeft: false, chain: (f) => f(x), @@ -46,7 +44,7 @@ export const Right = (x) => ({ concat: (other) => other.fold( (x) => other, - (y) => Right(x.concat(y)) + (y) => Right(x.concat(y)), ), traverse: (of, f) => f(x).map(Right), map: (f) => Right(f(x)), @@ -106,4 +104,3 @@ export const Either = { }; /* eslint-enable @typescript-eslint/no-unused-vars */ - diff --git a/tests/setup.jest.ts b/tests/setup.jest.ts index 685d19f..e27c844 100644 --- a/tests/setup.jest.ts +++ b/tests/setup.jest.ts @@ -22,8 +22,6 @@ import { arweave, createLocalWallet, deployANTContract, - deployUCMContract, - deployUContract, warp, } from './utils/helper'; @@ -49,25 +47,6 @@ module.exports = async function () { wallet, }); - const {contractTxId: ucmContractTxId, srcTxId: ucmSrcTxId} = await deployUCMContract({ - warp, - owner, - wallet, - }) - - const {contractTxId: uContractTxId, srcTxId: uSrcTxId} = await deployUContract({ - warp, - owner, - wallet, - }) - process.env.ANT_CONTRACT_TX_ID = contractTxId; process.env.ANT_SRC_TX_ID = srcTxId; - - process.env.UCM_CONTRACT_TX_ID = ucmContractTxId; - process.env.UCM_SRC_TX_ID = ucmSrcTxId; - - process.env.U_CONTRACT_TX_ID = uContractTxId; - process.env.U_SRC_TX_ID = uSrcTxId; - }; diff --git a/tests/ucm.test.ts b/tests/ucm.test.ts index 2d4cc6a..f799f9b 100644 --- a/tests/ucm.test.ts +++ b/tests/ucm.test.ts @@ -14,32 +14,146 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ +import { Contract, SourceType } from 'warp-contracts'; -import { ANTState } from "../src/types"; -import { arweave, deployANTUCMContract, getLocalWallet, warp } from "./utils/helper"; +import { ANTState } from '../src/types'; +import { + arweave, + createLocalWallet, + deployANTUCMContract, + deployUCMContract, + deployUContract, + warp, +} from './utils/helper'; describe('ucm', () => { - + let owner: string; + let ownerWallet; + let buyer: string; + let buyerWallet; let antContractTxId: string; - let antContractOwnerAddress: string; - let contract; - - beforeAll(async () => { - - const { wallet, address: owner } = await getLocalWallet(arweave); - const {contractTxId} = await deployANTUCMContract({ - warp, - owner, - wallet, - }) - - antContractTxId = contractTxId; - contract = warp.contract(antContractTxId).connect(wallet); - antContractOwnerAddress = owner; - - }) - - it('should add ANT to trading pair with U', () => { - expect(true).toBe(true) - }) -}) \ No newline at end of file + let antContract: Contract; + let ucmContractTxId: string; + let ucmContract: Contract; + let uContractTxId: string; + let uContract: Contract; + + beforeAll(async () => { + const { wallet: _ownerWallet, address: _owner } = + await createLocalWallet(arweave); + const { wallet: _buyerWallet, address: _buyer } = + await createLocalWallet(arweave); + const { contractTxId } = await deployANTUCMContract({ + warp, + owner: _owner, + wallet: _ownerWallet, + }); + + const { contractTxId: uContractId } = await deployUContract({ + warp, + owner, + wallet: _ownerWallet, + balances: { + [_owner]: 1000000000, + [_buyer]: 1000000000, + }, + }); + + const { contractTxId: ucmContractId } = await deployUCMContract({ + warp, + owner, + wallet: _ownerWallet, + uContractId, + }); + + antContractTxId = contractTxId; + antContract = warp + .contract(antContractTxId) + .setEvaluationOptions({ + sourceType: 'arweave' as SourceType, + unsafeClient: 'skip', + allowBigInt: true, + internalWrites: true, + useConstructor: true, + }); + + ucmContractTxId = ucmContractId; + ucmContract = warp.contract(ucmContractTxId).setEvaluationOptions({ + sourceType: 'arweave' as SourceType, + unsafeClient: 'skip', + allowBigInt: true, + internalWrites: true, + }); + + uContractTxId = uContractId; + uContract = warp.contract(uContractTxId).setEvaluationOptions({ + sourceType: 'both' as SourceType, + internalWrites: true, + unsafeClient: 'skip', + allowBigInt: true, + }); + + owner = _owner; + ownerWallet = _ownerWallet; + + buyer = _buyer; + buyerWallet = _buyerWallet; + }); + + it('should trade ant on the UCM', async () => { + const addPairRes = await ucmContract.connect(ownerWallet).writeInteraction({ + function: 'addPair', + pair: [antContractTxId, uContractTxId], + }); + expect(addPairRes?.originalTxId).toBeDefined(); + + const allowRes = await antContract.connect(ownerWallet).writeInteraction({ + function: 'allow', + target: ucmContractTxId, + qty: 1, + }); + expect(allowRes?.originalTxId).toBeDefined(); + + const sellOrderRes = await ucmContract + .connect(ownerWallet) + .writeInteraction({ + function: 'createOrder', + pair: [antContractTxId, uContractTxId], + transaction: allowRes?.originalTxId, + qty: 1, + price: 1, + }); + expect(sellOrderRes?.originalTxId).toBeDefined(); + + const allowUSpendingRes = await uContract + .connect(buyerWallet) + .writeInteraction({ + function: 'allow', + target: ucmContractTxId, + qty: 1, + }); + expect(allowUSpendingRes?.originalTxId).toBeDefined(); + + const buyOrderRes = await ucmContract + .connect(buyerWallet) + .writeInteraction({ + function: 'createOrder', + pair: [uContractTxId, antContractTxId], + transaction: allowUSpendingRes?.originalTxId, + qty: 1, + }); + expect(buyOrderRes?.originalTxId).toBeDefined(); + + const claimRes = await antContract.connect(buyerWallet).writeInteraction({ + function: 'claim', + txID: buyOrderRes?.originalTxId, + qty: 1, + }); + expect(claimRes?.originalTxId).toBeDefined(); + + const antState = await antContract.readState(); + + expect(antState.cachedValue.state.balances[buyer]).toEqual(1); + expect(antState.cachedValue.state.balances[owner]).not.toBeDefined(); + }); +}); diff --git a/tests/utils/constants.ts b/tests/utils/constants.ts index 719e90c..ad0c1e7 100644 --- a/tests/utils/constants.ts +++ b/tests/utils/constants.ts @@ -56,7 +56,7 @@ export const baselineAntState: ANTState = { ticker: 'ANT-TEST', }; -export const baselineAntUcmState: ANTState & {claimable: any[]} = { +export const baselineAntUcmState: ANTState & { claimable: any[] } = { owner: 'test', evolve: 'test', controllers: ['test'], diff --git a/tests/utils/helper.ts b/tests/utils/helper.ts index 2e22973..a133c41 100644 --- a/tests/utils/helper.ts +++ b/tests/utils/helper.ts @@ -19,7 +19,13 @@ import Arweave from 'arweave'; import { JWKInterface } from 'arweave/node/lib/wallet'; import * as fs from 'fs'; import path from 'path'; -import { LoggerFactory, SourceType, Tag, Warp, WarpFactory } from 'warp-contracts'; +import { + LoggerFactory, + SourceType, + Tag, + Warp, + WarpFactory, +} from 'warp-contracts'; import { DeployPlugin } from 'warp-contracts-plugin-deploy'; import { ANTState } from '../../src/types'; @@ -166,7 +172,6 @@ export async function deployANTContract({ }; } - export async function deployANTUCMContract({ warp, owner, @@ -206,9 +211,18 @@ export async function deployANTUCMContract({ src: sourceCode, initState: JSON.stringify(ownerState), wallet, - tags: buildANTUCMTags() + tags: buildANTUCMTags(), + evaluationManifest: { + evaluationOptions: { + sourceType: 'arweave' as SourceType, + unsafeClient: 'skip', + allowBigInt: true, + internalWrites: true, + useConstructor: true, + }, + }, }, - true, + true, ); return { contractTxId, @@ -220,10 +234,12 @@ export async function deployUCMContract({ warp, owner, wallet, + uContractId, }: { owner: string; warp: Warp; wallet: JWKInterface; + uContractId: string; }): Promise<{ contractTxId: string; srcTxId: string; @@ -236,12 +252,12 @@ export async function deployUCMContract({ path.join(__dirname, './ucm/state.json'), 'utf8', ); - const localHeight = global.arweave.blocks.getCurrent(); + const localHeight = (await arweave.blocks.getCurrent()).height; const ownerState = { ...JSON.parse(initState), creator: owner, originHeight: localHeight, - + U: uContractId, }; const { contractTxId, srcTxId } = await warp.deploy( { @@ -253,9 +269,8 @@ export async function deployUCMContract({ sourceType: 'arweave' as SourceType, unsafeClient: 'skip', allowBigInt: true, - - } - } + }, + }, }, true, ); @@ -265,15 +280,16 @@ export async function deployUCMContract({ }; } - export async function deployUContract({ warp, owner, wallet, + balances, }: { owner: string; warp: Warp; wallet: JWKInterface; + balances: Record; }): Promise<{ contractTxId: string; srcTxId: string; @@ -289,10 +305,7 @@ export async function deployUContract({ const ownerState = { ...JSON.parse(initState), owner: owner, - balances: { - owner: 1000000000 - } - + balances, }; const { contractTxId, srcTxId } = await warp.deploy( { @@ -305,9 +318,8 @@ export async function deployUContract({ internalWrites: true, unsafeClient: 'skip', allowBigInt: true, - - } - } + }, + }, }, true, ); @@ -320,15 +332,14 @@ export async function deployUContract({ export function buildANTUCMTags( title = 'ANT UCM Contract', description = 'ANT UCM Contract. This contract allows for registration of names on the Arweave Name System (ArNS). See more at https://ar.io/arns', - contentType = 'application/json' + contentType = 'application/json', ): Tag[] { return [ { name: 'Content-Type', value: contentType }, { name: 'Title', value: title }, - { name: 'Description', value: description}, + { name: 'Description', value: description }, { name: 'Topic:ANT', value: 'ANT' }, { name: 'Topic:ArNS', value: 'ArNS' }, - { name: 'Type', value: 'token' } - ].map((t)=> new Tag(t.name, t.value)); + { name: 'Type', value: 'token' }, + ].map((t) => new Tag(t.name, t.value)); } - diff --git a/tests/utils/u/source.js b/tests/utils/u/source.js index 8cfa439..ba8968d 100644 --- a/tests/utils/u/source.js +++ b/tests/utils/u/source.js @@ -6,8 +6,8 @@ async function balance(state, action) { result: { target: addr, ticker: state.ticker, - balance: state.balances[addr] || 0 - } + balance: state.balances[addr] || 0, + }, }; } @@ -18,15 +18,16 @@ var Right = (x) => ({ ap: (other) => other.map(x), alt: (other) => Right(x), extend: (f) => f(Right(x)), - concat: (other) => other.fold( - (x2) => other, - (y) => Right(x.concat(y)) - ), + concat: (other) => + other.fold( + (x2) => other, + (y) => Right(x.concat(y)), + ), traverse: (of2, f) => f(x).map(Right), map: (f) => Right(f(x)), fold: (_, g) => g(x), toString: () => `Right(${x})`, - extract: () => x + extract: () => x, }); var Left = (x) => ({ isLeft: true, @@ -39,57 +40,86 @@ var Left = (x) => ({ map: (_) => Left(x), fold: (f, _) => f(x), toString: () => `Left(${x})`, - extract: () => x + extract: () => x, }); var of = Right; -var fromNullable = (x) => x != null ? Right(x) : Left(x); +var fromNullable = (x) => (x != null ? Right(x) : Left(x)); // node_modules/bignumber.js/bignumber.mjs var isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i; var mathceil = Math.ceil; var mathfloor = Math.floor; -var bignumberError = "[BigNumber Error] "; -var tooManyDigits = bignumberError + "Number primitive has more than 15 significant digits: "; +var bignumberError = '[BigNumber Error] '; +var tooManyDigits = + bignumberError + 'Number primitive has more than 15 significant digits: '; var BASE = 1e14; var LOG_BASE = 14; var MAX_SAFE_INTEGER = 9007199254740991; -var POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13]; +var POWS_TEN = [ + 1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, +]; var SQRT_BASE = 1e7; var MAX = 1e9; function clone(configObject) { - var div, convertBase, parseNumeric, P = BigNumber2.prototype = { constructor: BigNumber2, toString: null, valueOf: null }, ONE = new BigNumber2(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { - prefix: "", - groupSize: 3, - secondaryGroupSize: 0, - groupSeparator: ",", - decimalSeparator: ".", - fractionGroupSize: 0, - fractionGroupSeparator: "\xA0", - // non-breaking space - suffix: "" - }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true; + var div, + convertBase, + parseNumeric, + P = (BigNumber2.prototype = { + constructor: BigNumber2, + toString: null, + valueOf: null, + }), + ONE = new BigNumber2(1), + DECIMAL_PLACES = 20, + ROUNDING_MODE = 4, + TO_EXP_NEG = -7, + TO_EXP_POS = 21, + MIN_EXP = -1e7, + MAX_EXP = 1e7, + CRYPTO = false, + MODULO_MODE = 1, + POW_PRECISION = 0, + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', + // non-breaking space + suffix: '', + }, + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz', + alphabetHasNormalDecimalDigits = true; function BigNumber2(v, b) { - var alphabet, c, caseChanged, e, i, isNum, len, str, x = this; - if (!(x instanceof BigNumber2)) - return new BigNumber2(v, b); + var alphabet, + c, + caseChanged, + e, + i, + isNum, + len, + str, + x = this; + if (!(x instanceof BigNumber2)) return new BigNumber2(v, b); if (b == null) { if (v && v._isBigNumber === true) { x.s = v.s; if (!v.c || v.e > MAX_EXP) { x.c = x.e = null; } else if (v.e < MIN_EXP) { - x.c = [x.e = 0]; + x.c = [(x.e = 0)]; } else { x.e = v.e; x.c = v.c.slice(); } return; } - if ((isNum = typeof v == "number") && v * 0 == 0) { - x.s = 1 / v < 0 ? (v = -v, -1) : 1; + if ((isNum = typeof v == 'number') && v * 0 == 0) { + x.s = 1 / v < 0 ? ((v = -v), -1) : 1; if (v === ~~v) { - for (e = 0, i = v; i >= 10; i /= 10, e++) - ; + for (e = 0, i = v; i >= 10; i /= 10, e++); if (e > MAX_EXP) { x.c = x.e = null; } else { @@ -100,48 +130,48 @@ function clone(configObject) { } str = String(v); } else { - if (!isNumeric.test(str = String(v))) + if (!isNumeric.test((str = String(v)))) return parseNumeric(x, str, isNum); - x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + x.s = str.charCodeAt(0) == 45 ? ((str = str.slice(1)), -1) : 1; } - if ((e = str.indexOf(".")) > -1) - str = str.replace(".", ""); + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); if ((i = str.search(/e/i)) > 0) { - if (e < 0) - e = i; + if (e < 0) e = i; e += +str.slice(i + 1); str = str.substring(0, i); } else if (e < 0) { e = str.length; } } else { - intCheck(b, 2, ALPHABET.length, "Base"); + intCheck(b, 2, ALPHABET.length, 'Base'); if (b == 10 && alphabetHasNormalDecimalDigits) { x = new BigNumber2(v); return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); } str = String(v); - if (isNum = typeof v == "number") { - if (v * 0 != 0) - return parseNumeric(x, str, isNum, b); - x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; - if (BigNumber2.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { + if ((isNum = typeof v == 'number')) { + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); + x.s = 1 / v < 0 ? ((str = str.slice(1)), -1) : 1; + if (BigNumber2.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { throw Error(tooManyDigits + v); } } else { - x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + x.s = str.charCodeAt(0) === 45 ? ((str = str.slice(1)), -1) : 1; } alphabet = ALPHABET.slice(0, b); e = i = 0; for (len = str.length; i < len; i++) { - if (alphabet.indexOf(c = str.charAt(i)) < 0) { - if (c == ".") { + if (alphabet.indexOf((c = str.charAt(i))) < 0) { + if (c == '.') { if (i > e) { e = len; continue; } } else if (!caseChanged) { - if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { + if ( + (str == str.toUpperCase() && (str = str.toLowerCase())) || + (str == str.toLowerCase() && (str = str.toUpperCase())) + ) { caseChanged = true; i = -1; e = 0; @@ -153,46 +183,44 @@ function clone(configObject) { } isNum = false; str = convertBase(str, b, 10, x.s); - if ((e = str.indexOf(".")) > -1) - str = str.replace(".", ""); - else - e = str.length; + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; } - for (i = 0; str.charCodeAt(i) === 48; i++) - ; - for (len = str.length; str.charCodeAt(--len) === 48; ) - ; - if (str = str.slice(i, ++len)) { + for (i = 0; str.charCodeAt(i) === 48; i++); + for (len = str.length; str.charCodeAt(--len) === 48; ); + if ((str = str.slice(i, ++len))) { len -= i; - if (isNum && BigNumber2.DEBUG && len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + if ( + isNum && + BigNumber2.DEBUG && + len > 15 && + (v > MAX_SAFE_INTEGER || v !== mathfloor(v)) + ) { throw Error(tooManyDigits + x.s * v); } if ((e = e - i - 1) > MAX_EXP) { x.c = x.e = null; } else if (e < MIN_EXP) { - x.c = [x.e = 0]; + x.c = [(x.e = 0)]; } else { x.e = e; x.c = []; i = (e + 1) % LOG_BASE; - if (e < 0) - i += LOG_BASE; + if (e < 0) i += LOG_BASE; if (i < len) { - if (i) - x.c.push(+str.slice(0, i)); + if (i) x.c.push(+str.slice(0, i)); for (len -= LOG_BASE; i < len; ) { - x.c.push(+str.slice(i, i += LOG_BASE)); + x.c.push(+str.slice(i, (i += LOG_BASE))); } i = LOG_BASE - (str = str.slice(i)).length; } else { i -= len; } - for (; i--; str += "0") - ; + for (; i--; str += '0'); x.c.push(+str); } } else { - x.c = [x.e = 0]; + x.c = [(x.e = 0)]; } } BigNumber2.clone = clone; @@ -206,21 +234,21 @@ function clone(configObject) { BigNumber2.ROUND_HALF_CEIL = 7; BigNumber2.ROUND_HALF_FLOOR = 8; BigNumber2.EUCLID = 9; - BigNumber2.config = BigNumber2.set = function(obj) { + BigNumber2.config = BigNumber2.set = function (obj) { var p, v; if (obj != null) { - if (typeof obj == "object") { - if (obj.hasOwnProperty(p = "DECIMAL_PLACES")) { + if (typeof obj == 'object') { + if (obj.hasOwnProperty((p = 'DECIMAL_PLACES'))) { v = obj[p]; intCheck(v, 0, MAX, p); DECIMAL_PLACES = v; } - if (obj.hasOwnProperty(p = "ROUNDING_MODE")) { + if (obj.hasOwnProperty((p = 'ROUNDING_MODE'))) { v = obj[p]; intCheck(v, 0, 8, p); ROUNDING_MODE = v; } - if (obj.hasOwnProperty(p = "EXPONENTIAL_AT")) { + if (obj.hasOwnProperty((p = 'EXPONENTIAL_AT'))) { v = obj[p]; if (v && v.pop) { intCheck(v[0], -MAX, 0, p); @@ -232,7 +260,7 @@ function clone(configObject) { TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); } } - if (obj.hasOwnProperty(p = "RANGE")) { + if (obj.hasOwnProperty((p = 'RANGE'))) { v = obj[p]; if (v && v.pop) { intCheck(v[0], -MAX, -1, p); @@ -244,55 +272,57 @@ function clone(configObject) { if (v) { MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); } else { - throw Error(bignumberError + p + " cannot be zero: " + v); + throw Error(bignumberError + p + ' cannot be zero: ' + v); } } } - if (obj.hasOwnProperty(p = "CRYPTO")) { + if (obj.hasOwnProperty((p = 'CRYPTO'))) { v = obj[p]; if (v === !!v) { if (v) { - if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) { + if ( + typeof crypto != 'undefined' && + crypto && + (crypto.getRandomValues || crypto.randomBytes) + ) { CRYPTO = v; } else { CRYPTO = !v; - throw Error(bignumberError + "crypto unavailable"); + throw Error(bignumberError + 'crypto unavailable'); } } else { CRYPTO = v; } } else { - throw Error(bignumberError + p + " not true or false: " + v); + throw Error(bignumberError + p + ' not true or false: ' + v); } } - if (obj.hasOwnProperty(p = "MODULO_MODE")) { + if (obj.hasOwnProperty((p = 'MODULO_MODE'))) { v = obj[p]; intCheck(v, 0, 9, p); MODULO_MODE = v; } - if (obj.hasOwnProperty(p = "POW_PRECISION")) { + if (obj.hasOwnProperty((p = 'POW_PRECISION'))) { v = obj[p]; intCheck(v, 0, MAX, p); POW_PRECISION = v; } - if (obj.hasOwnProperty(p = "FORMAT")) { + if (obj.hasOwnProperty((p = 'FORMAT'))) { v = obj[p]; - if (typeof v == "object") - FORMAT = v; - else - throw Error(bignumberError + p + " not an object: " + v); + if (typeof v == 'object') FORMAT = v; + else throw Error(bignumberError + p + ' not an object: ' + v); } - if (obj.hasOwnProperty(p = "ALPHABET")) { + if (obj.hasOwnProperty((p = 'ALPHABET'))) { v = obj[p]; - if (typeof v == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { - alphabetHasNormalDecimalDigits = v.slice(0, 10) == "0123456789"; + if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { + alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789'; ALPHABET = v; } else { - throw Error(bignumberError + p + " invalid: " + v); + throw Error(bignumberError + p + ' invalid: ' + v); } } } else { - throw Error(bignumberError + "Object expected: " + obj); + throw Error(bignumberError + 'Object expected: ' + obj); } } return { @@ -304,64 +334,81 @@ function clone(configObject) { MODULO_MODE, POW_PRECISION, FORMAT, - ALPHABET + ALPHABET, }; }; - BigNumber2.isBigNumber = function(v) { - if (!v || v._isBigNumber !== true) - return false; - if (!BigNumber2.DEBUG) - return true; - var i, n, c = v.c, e = v.e, s = v.s; - out: - if ({}.toString.call(c) == "[object Array]") { - if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { - if (c[0] === 0) { - if (e === 0 && c.length === 1) - return true; - break out; - } - i = (e + 1) % LOG_BASE; - if (i < 1) - i += LOG_BASE; - if (String(c[0]).length == i) { - for (i = 0; i < c.length; i++) { - n = c[i]; - if (n < 0 || n >= BASE || n !== mathfloor(n)) - break out; - } - if (n !== 0) - return true; + BigNumber2.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber2.DEBUG) return true; + var i, + n, + c = v.c, + e = v.e, + s = v.s; + out: if ({}.toString.call(c) == '[object Array]') { + if ( + (s === 1 || s === -1) && + e >= -MAX && + e <= MAX && + e === mathfloor(e) + ) { + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; + if (String(c[0]).length == i) { + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; } + if (n !== 0) return true; } - } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { - return true; } - throw Error(bignumberError + "Invalid BigNumber: " + v); + } else if ( + c === null && + e === null && + (s === null || s === 1 || s === -1) + ) { + return true; + } + throw Error(bignumberError + 'Invalid BigNumber: ' + v); }; - BigNumber2.maximum = BigNumber2.max = function() { + BigNumber2.maximum = BigNumber2.max = function () { return maxOrMin(arguments, P.lt); }; - BigNumber2.minimum = BigNumber2.min = function() { + BigNumber2.minimum = BigNumber2.min = function () { return maxOrMin(arguments, P.gt); }; - BigNumber2.random = function() { + BigNumber2.random = (function () { var pow2_53 = 9007199254740992; - var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() { - return mathfloor(Math.random() * pow2_53); - } : function() { - return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0); - }; - return function(dp) { - var a, b, e, k, v, i = 0, c = [], rand = new BigNumber2(ONE); - if (dp == null) - dp = DECIMAL_PLACES; - else - intCheck(dp, 0, MAX); + var random53bitInt = + (Math.random() * pow2_53) & 2097151 + ? function () { + return mathfloor(Math.random() * pow2_53); + } + : function () { + return ( + ((Math.random() * 1073741824) | 0) * 8388608 + + ((Math.random() * 8388608) | 0) + ); + }; + return function (dp) { + var a, + b, + e, + k, + v, + i = 0, + c = [], + rand = new BigNumber2(ONE); + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); k = mathceil(dp / LOG_BASE); if (CRYPTO) { if (crypto.getRandomValues) { - a = crypto.getRandomValues(new Uint32Array(k *= 2)); + a = crypto.getRandomValues(new Uint32Array((k *= 2))); for (; i < k; ) { v = a[i] * 131072 + (a[i + 1] >>> 11); if (v >= 9e15) { @@ -375,9 +422,16 @@ function clone(configObject) { } i = k / 2; } else if (crypto.randomBytes) { - a = crypto.randomBytes(k *= 7); + a = crypto.randomBytes((k *= 7)); for (; i < k; ) { - v = (a[i] & 31) * 281474976710656 + a[i + 1] * 1099511627776 + a[i + 2] * 4294967296 + a[i + 3] * 16777216 + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + v = + (a[i] & 31) * 281474976710656 + + a[i + 1] * 1099511627776 + + a[i + 2] * 4294967296 + + a[i + 3] * 16777216 + + (a[i + 4] << 16) + + (a[i + 5] << 8) + + a[i + 6]; if (v >= 9e15) { crypto.randomBytes(7).copy(a, i); } else { @@ -388,14 +442,13 @@ function clone(configObject) { i = k / 7; } else { CRYPTO = false; - throw Error(bignumberError + "crypto unavailable"); + throw Error(bignumberError + 'crypto unavailable'); } } if (!CRYPTO) { for (; i < k; ) { v = random53bitInt(); - if (v < 9e15) - c[i++] = v % 1e14; + if (v < 9e15) c[i++] = v % 1e14; } } k = c[--i]; @@ -404,71 +457,85 @@ function clone(configObject) { v = POWS_TEN[LOG_BASE - dp]; c[i] = mathfloor(k / v) * v; } - for (; c[i] === 0; c.pop(), i--) - ; + for (; c[i] === 0; c.pop(), i--); if (i < 0) { - c = [e = 0]; + c = [(e = 0)]; } else { - for (e = -1; c[0] === 0; c.splice(0, 1), e -= LOG_BASE) - ; - for (i = 1, v = c[0]; v >= 10; v /= 10, i++) - ; - if (i < LOG_BASE) - e -= LOG_BASE - i; + for (e = -1; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + if (i < LOG_BASE) e -= LOG_BASE - i; } rand.e = e; rand.c = c; return rand; }; - }(); - BigNumber2.sum = function() { - var i = 1, args = arguments, sum = new BigNumber2(args[0]); - for (; i < args.length; ) - sum = sum.plus(args[i++]); + })(); + BigNumber2.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber2(args[0]); + for (; i < args.length; ) sum = sum.plus(args[i++]); return sum; }; - convertBase = function() { - var decimal = "0123456789"; + convertBase = (function () { + var decimal = '0123456789'; function toBaseOut(str, baseIn, baseOut, alphabet) { - var j, arr = [0], arrL, i = 0, len = str.length; + var j, + arr = [0], + arrL, + i = 0, + len = str.length; for (; i < len; ) { - for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) - ; + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); arr[0] += alphabet.indexOf(str.charAt(i++)); for (j = 0; j < arr.length; j++) { if (arr[j] > baseOut - 1) { - if (arr[j + 1] == null) - arr[j + 1] = 0; - arr[j + 1] += arr[j] / baseOut | 0; + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += (arr[j] / baseOut) | 0; arr[j] %= baseOut; } } } return arr.reverse(); } - return function(str, baseIn, baseOut, sign, callerIsToString) { - var alphabet, d, e, k, r, x, xc, y, i = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, + d, + e, + k, + r, + x, + xc, + y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; if (i >= 0) { k = POW_PRECISION; POW_PRECISION = 0; - str = str.replace(".", ""); + str = str.replace('.', ''); y = new BigNumber2(baseIn); x = y.pow(str.length - i); POW_PRECISION = k; y.c = toBaseOut( - toFixedPoint(coeffToString(x.c), x.e, "0"), + toFixedPoint(coeffToString(x.c), x.e, '0'), 10, baseOut, - decimal + decimal, ); y.e = y.c.length; } - xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet = ALPHABET, decimal) : (alphabet = decimal, ALPHABET)); + xc = toBaseOut( + str, + baseIn, + baseOut, + callerIsToString + ? ((alphabet = ALPHABET), decimal) + : ((alphabet = decimal), ALPHABET), + ); e = k = xc.length; - for (; xc[--k] == 0; xc.pop()) - ; - if (!xc[0]) - return alphabet.charAt(0); + for (; xc[--k] == 0; xc.pop()); + if (!xc[0]) return alphabet.charAt(0); if (i < 0) { --e; } else { @@ -484,9 +551,19 @@ function clone(configObject) { i = xc[d]; k = baseOut / 2; r = r || d < 0 || xc[d + 1] != null; - r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : i > k || i == k && (rm == 4 || r || rm == 6 && xc[d - 1] & 1 || rm == (x.s < 0 ? 8 : 7)); + r = + rm < 4 + ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || + (i == k && + (rm == 4 || + r || + (rm == 6 && xc[d - 1] & 1) || + rm == (x.s < 0 ? 8 : 7))); if (d < 1 || !xc[0]) { - str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + str = r + ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) + : alphabet.charAt(0); } else { xc.length = d; if (r) { @@ -498,28 +575,32 @@ function clone(configObject) { } } } - for (k = xc.length; !xc[--k]; ) - ; - for (i = 0, str = ""; i <= k; str += alphabet.charAt(xc[i++])) - ; + for (k = xc.length; !xc[--k]; ); + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); str = toFixedPoint(str, e, alphabet.charAt(0)); } return str; }; - }(); - div = function() { + })(); + div = (function () { function multiply(x, k, base) { - var m, temp, xlo, xhi, carry = 0, i = x.length, klo = k % SQRT_BASE, khi = k / SQRT_BASE | 0; + var m, + temp, + xlo, + xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = (k / SQRT_BASE) | 0; for (x = x.slice(); i--; ) { xlo = x[i] % SQRT_BASE; - xhi = x[i] / SQRT_BASE | 0; + xhi = (x[i] / SQRT_BASE) | 0; m = khi * xlo + xhi * klo; - temp = klo * xlo + m % SQRT_BASE * SQRT_BASE + carry; - carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + temp = klo * xlo + (m % SQRT_BASE) * SQRT_BASE + carry; + carry = ((temp / base) | 0) + ((m / SQRT_BASE) | 0) + khi * xhi; x[i] = temp % base; } - if (carry) - x = [carry].concat(x); + if (carry) x = [carry].concat(x); return x; } function compare2(a, b, aL, bL) { @@ -543,18 +624,38 @@ function clone(configObject) { i = a[aL] < b[aL] ? 1 : 0; a[aL] = i * base + a[aL] - b[aL]; } - for (; !a[0] && a.length > 1; a.splice(0, 1)) - ; + for (; !a[0] && a.length > 1; a.splice(0, 1)); } - return function(x, y, dp, rm, base) { - var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s = x.s == y.s ? 1 : -1, xc = x.c, yc = y.c; + return function (x, y, dp, rm, base) { + var cmp, + e, + i, + more, + n, + prod, + prodL, + q, + qc, + rem, + remL, + rem0, + xi, + xL, + yc0, + yL, + yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; if (!xc || !xc[0] || !yc || !yc[0]) { return new BigNumber2( // Return NaN if either NaN, or both Infinity or 0. - !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : ( - // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. - xc && xc[0] == 0 || !yc ? s * 0 : s / 0 - ) + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) + ? NaN + : // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + (xc && xc[0] == 0) || !yc + ? s * 0 + : s / 0, ); } q = new BigNumber2(s); @@ -564,12 +665,10 @@ function clone(configObject) { if (!base) { base = BASE; e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); - s = s / LOG_BASE | 0; + s = (s / LOG_BASE) | 0; } - for (i = 0; yc[i] == (xc[i] || 0); i++) - ; - if (yc[i] > (xc[i] || 0)) - e--; + for (i = 0; yc[i] == (xc[i] || 0); i++); + if (yc[i] > (xc[i] || 0)) e--; if (s < 0) { qc.push(1); more = true; @@ -588,24 +687,20 @@ function clone(configObject) { xi = yL; rem = xc.slice(0, yL); remL = rem.length; - for (; remL < yL; rem[remL++] = 0) - ; + for (; remL < yL; rem[remL++] = 0); yz = yc.slice(); yz = [0].concat(yz); yc0 = yc[0]; - if (yc[1] >= base / 2) - yc0++; + if (yc[1] >= base / 2) yc0++; do { n = 0; cmp = compare2(yc, rem, yL, remL); if (cmp < 0) { rem0 = rem[0]; - if (yL != remL) - rem0 = rem0 * base + (rem[1] || 0); + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); n = mathfloor(rem0 / yc0); if (n > 1) { - if (n >= base) - n = base - 1; + if (n >= base) n = base - 1; prod = multiply(yc, n, base); prodL = prod.length; remL = rem.length; @@ -622,8 +717,7 @@ function clone(configObject) { prod = yc.slice(); prodL = prod.length; } - if (prodL < remL) - prod = [0].concat(prod); + if (prodL < remL) prod = [0].concat(prod); subtract(rem, prod, remL, base); remL = rem.length; if (cmp == -1) { @@ -646,12 +740,10 @@ function clone(configObject) { } } while ((xi++ < xL || rem[0] != null) && s--); more = rem[0] != null; - if (!qc[0]) - qc.splice(0, 1); + if (!qc[0]) qc.splice(0, 1); } if (base == BASE) { - for (i = 1, s = qc[0]; s >= 10; s /= 10, i++) - ; + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); } else { q.e = e; @@ -659,51 +751,48 @@ function clone(configObject) { } return q; }; - }(); + })(); function format(n, i, rm, id) { var c0, e, ne, len, str; - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck(rm, 0, 8); - if (!n.c) - return n.toString(); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + if (!n.c) return n.toString(); c0 = n.c[0]; ne = n.e; if (i == null) { str = coeffToString(n.c); - str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential(str, ne) : toFixedPoint(str, ne, "0"); + str = + id == 1 || (id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS)) + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); } else { n = round(new BigNumber2(n), i, rm); e = n.e; str = coeffToString(n.c); len = str.length; - if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { - for (; len < i; str += "0", len++) - ; + if (id == 1 || (id == 2 && (i <= e || e <= TO_EXP_NEG))) { + for (; len < i; str += '0', len++); str = toExponential(str, e); } else { i -= ne; - str = toFixedPoint(str, e, "0"); + str = toFixedPoint(str, e, '0'); if (e + 1 > len) { - if (--i > 0) - for (str += "."; i--; str += "0") - ; + if (--i > 0) for (str += '.'; i--; str += '0'); } else { i += e - len; if (i > 0) { - if (e + 1 == len) - str += "."; - for (; i--; str += "0") - ; + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); } } } } - return n.s < 0 && c0 ? "-" + str : str; + return n.s < 0 && c0 ? '-' + str : str; } function maxOrMin(args, method) { - var n, i = 1, m = new BigNumber2(args[0]); + var n, + i = 1, + m = new BigNumber2(args[0]); for (; i < args.length; i++) { n = new BigNumber2(args[i]); if (!n.s) { @@ -716,66 +805,81 @@ function clone(configObject) { return m; } function normalise(n, c, e) { - var i = 1, j = c.length; - for (; !c[--j]; c.pop()) - ; - for (j = c[0]; j >= 10; j /= 10, i++) - ; + var i = 1, + j = c.length; + for (; !c[--j]; c.pop()); + for (j = c[0]; j >= 10; j /= 10, i++); if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { n.c = n.e = null; } else if (e < MIN_EXP) { - n.c = [n.e = 0]; + n.c = [(n.e = 0)]; } else { n.e = e; n.c = c; } return n; } - parseNumeric = function() { - var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; - return function(x, str, isNum, b) { - var base, s = isNum ? str : str.replace(whitespaceOrPlus, ""); + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); if (isInfinityOrNaN.test(s)) { x.s = isNaN(s) ? null : s < 0 ? -1 : 1; } else { if (!isNum) { - s = s.replace(basePrefix, function(m, p1, p2) { - base = (p2 = p2.toLowerCase()) == "x" ? 16 : p2 == "b" ? 2 : 8; + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; return !b || b == base ? p1 : m; }); if (b) { base = b; - s = s.replace(dotAfter, "$1").replace(dotBefore, "0.$1"); + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); } - if (str != s) - return new BigNumber2(s, base); + if (str != s) return new BigNumber2(s, base); } if (BigNumber2.DEBUG) { - throw Error(bignumberError + "Not a" + (b ? " base " + b : "") + " number: " + str); + throw Error( + bignumberError + + 'Not a' + + (b ? ' base ' + b : '') + + ' number: ' + + str, + ); } x.s = null; } x.c = x.e = null; }; - }(); + })(); function round(x, sd, rm, r) { - var d, i, j, k, n, ni, rd, xc = x.c, pows10 = POWS_TEN; + var d, + i, + j, + k, + n, + ni, + rd, + xc = x.c, + pows10 = POWS_TEN; if (xc) { out: { - for (d = 1, k = xc[0]; k >= 10; k /= 10, d++) - ; + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); i = sd - d; if (i < 0) { i += LOG_BASE; j = sd; - n = xc[ni = 0]; - rd = n / pows10[d - j - 1] % 10 | 0; + n = xc[(ni = 0)]; + rd = (n / pows10[d - j - 1]) % 10 | 0; } else { ni = mathceil((i + 1) / LOG_BASE); if (ni >= xc.length) { if (r) { - for (; xc.length <= ni; xc.push(0)) - ; + for (; xc.length <= ni; xc.push(0)); n = rd = 0; d = 1; i %= LOG_BASE; @@ -785,24 +889,36 @@ function clone(configObject) { } } else { n = k = xc[ni]; - for (d = 1; k >= 10; k /= 10, d++) - ; + for (d = 1; k >= 10; k /= 10, d++); i %= LOG_BASE; j = i - LOG_BASE + d; - rd = j < 0 ? 0 : n / pows10[d - j - 1] % 10 | 0; + rd = j < 0 ? 0 : (n / pows10[d - j - 1]) % 10 | 0; } } - r = r || sd < 0 || // Are there any non-zero digits after the rounding digit? - // The expression n % pows10[d - j - 1] returns all digits of n to the right - // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. - xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); - r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd. - (i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x.s < 0 ? 8 : 7)); + r = + r || + sd < 0 || // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || + (j < 0 ? n : n % pows10[d - j - 1]); + r = + rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || + (rd == 5 && + (rm == 4 || + r || + (rm == 6 && // Check whether the digit to the left of the rounding digit is odd. + (i > 0 ? (j > 0 ? n / pows10[d - j] : 0) : xc[ni - 1]) % + 10 & + 1) || + rm == (x.s < 0 ? 8 : 7))); if (sd < 1 || !xc[0]) { xc.length = 0; if (r) { sd -= x.e + 1; - xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + xc[0] = pows10[(LOG_BASE - (sd % LOG_BASE)) % LOG_BASE]; x.e = -sd || 0; } else { xc[0] = x.e = 0; @@ -816,139 +932,149 @@ function clone(configObject) { } else { xc.length = ni + 1; k = pows10[LOG_BASE - i]; - xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + xc[ni] = j > 0 ? mathfloor((n / pows10[d - j]) % pows10[j]) * k : 0; } if (r) { - for (; ; ) { + for (;;) { if (ni == 0) { - for (i = 1, j = xc[0]; j >= 10; j /= 10, i++) - ; + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); j = xc[0] += k; - for (k = 1; j >= 10; j /= 10, k++) - ; + for (k = 1; j >= 10; j /= 10, k++); if (i != k) { x.e++; - if (xc[0] == BASE) - xc[0] = 1; + if (xc[0] == BASE) xc[0] = 1; } break; } else { xc[ni] += k; - if (xc[ni] != BASE) - break; + if (xc[ni] != BASE) break; xc[ni--] = 0; k = 1; } } } - for (i = xc.length; xc[--i] === 0; xc.pop()) - ; + for (i = xc.length; xc[--i] === 0; xc.pop()); } if (x.e > MAX_EXP) { x.c = x.e = null; } else if (x.e < MIN_EXP) { - x.c = [x.e = 0]; + x.c = [(x.e = 0)]; } } return x; } function valueOf(n) { - var str, e = n.e; - if (e === null) - return n.toString(); + var str, + e = n.e; + if (e === null) return n.toString(); str = coeffToString(n.c); - str = e <= TO_EXP_NEG || e >= TO_EXP_POS ? toExponential(str, e) : toFixedPoint(str, e, "0"); - return n.s < 0 ? "-" + str : str; + str = + e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + return n.s < 0 ? '-' + str : str; } - P.absoluteValue = P.abs = function() { + P.absoluteValue = P.abs = function () { var x = new BigNumber2(this); - if (x.s < 0) - x.s = 1; + if (x.s < 0) x.s = 1; return x; }; - P.comparedTo = function(y, b) { + P.comparedTo = function (y, b) { return compare(this, new BigNumber2(y, b)); }; - P.decimalPlaces = P.dp = function(dp, rm) { - var c, n, v, x = this; + P.decimalPlaces = P.dp = function (dp, rm) { + var c, + n, + v, + x = this; if (dp != null) { intCheck(dp, 0, MAX); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck(rm, 0, 8); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); return round(new BigNumber2(x), dp + x.e + 1, rm); } - if (!(c = x.c)) - return null; + if (!(c = x.c)) return null; n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; - if (v = c[v]) - for (; v % 10 == 0; v /= 10, n--) - ; - if (n < 0) - n = 0; + if ((v = c[v])) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; return n; }; - P.dividedBy = P.div = function(y, b) { + P.dividedBy = P.div = function (y, b) { return div(this, new BigNumber2(y, b), DECIMAL_PLACES, ROUNDING_MODE); }; - P.dividedToIntegerBy = P.idiv = function(y, b) { + P.dividedToIntegerBy = P.idiv = function (y, b) { return div(this, new BigNumber2(y, b), 0, 1); }; - P.exponentiatedBy = P.pow = function(n, m) { - var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, x = this; + P.exponentiatedBy = P.pow = function (n, m) { + var half, + isModExp, + i, + k, + more, + nIsBig, + nIsNeg, + nIsOdd, + y, + x = this; n = new BigNumber2(n); if (n.c && !n.isInteger()) { - throw Error(bignumberError + "Exponent not an integer: " + valueOf(n)); + throw Error(bignumberError + 'Exponent not an integer: ' + valueOf(n)); } - if (m != null) - m = new BigNumber2(m); + if (m != null) m = new BigNumber2(m); nIsBig = n.e > 14; - if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { - y = new BigNumber2(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n))); + if ( + !x.c || + !x.c[0] || + (x.c[0] == 1 && !x.e && x.c.length == 1) || + !n.c || + !n.c[0] + ) { + y = new BigNumber2( + Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n)), + ); return m ? y.mod(m) : y; } nIsNeg = n.s < 0; if (m) { - if (m.c ? !m.c[0] : !m.s) - return new BigNumber2(NaN); + if (m.c ? !m.c[0] : !m.s) return new BigNumber2(NaN); isModExp = !nIsNeg && x.isInteger() && m.isInteger(); - if (isModExp) - x = x.mod(m); - } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + if (isModExp) x = x.mod(m); + } else if ( + n.e > 9 && + (x.e > 0 || + x.e < -1 || + (x.e == 0 + ? x.c[0] > 1 || (nIsBig && x.c[1] >= 24e7) + : x.c[0] < 8e13 || (nIsBig && x.c[0] <= 9999975e7))) + ) { k = x.s < 0 && isOdd(n) ? -0 : 0; - if (x.e > -1) - k = 1 / k; + if (x.e > -1) k = 1 / k; return new BigNumber2(nIsNeg ? 1 / k : k); } else if (POW_PRECISION) { k = mathceil(POW_PRECISION / LOG_BASE + 2); } if (nIsBig) { half = new BigNumber2(0.5); - if (nIsNeg) - n.s = 1; + if (nIsNeg) n.s = 1; nIsOdd = isOdd(n); } else { i = Math.abs(+valueOf(n)); nIsOdd = i % 2; } y = new BigNumber2(ONE); - for (; ; ) { + for (;;) { if (nIsOdd) { y = y.times(x); - if (!y.c) - break; + if (!y.c) break; if (k) { - if (y.c.length > k) - y.c.length = k; + if (y.c.length > k) y.c.length = k; } else if (isModExp) { y = y.mod(m); } } if (i) { i = mathfloor(i / 2); - if (i === 0) - break; + if (i === 0) break; nIsOdd = i % 2; } else { n = n.times(half); @@ -957,92 +1083,99 @@ function clone(configObject) { nIsOdd = isOdd(n); } else { i = +valueOf(n); - if (i === 0) - break; + if (i === 0) break; nIsOdd = i % 2; } } x = x.times(x); if (k) { - if (x.c && x.c.length > k) - x.c.length = k; + if (x.c && x.c.length > k) x.c.length = k; } else if (isModExp) { x = x.mod(m); } } - if (isModExp) - return y; - if (nIsNeg) - y = ONE.div(y); + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; }; - P.integerValue = function(rm) { + P.integerValue = function (rm) { var n = new BigNumber2(this); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck(rm, 0, 8); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); return round(n, n.e + 1, rm); }; - P.isEqualTo = P.eq = function(y, b) { + P.isEqualTo = P.eq = function (y, b) { return compare(this, new BigNumber2(y, b)) === 0; }; - P.isFinite = function() { + P.isFinite = function () { return !!this.c; }; - P.isGreaterThan = P.gt = function(y, b) { + P.isGreaterThan = P.gt = function (y, b) { return compare(this, new BigNumber2(y, b)) > 0; }; - P.isGreaterThanOrEqualTo = P.gte = function(y, b) { + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { return (b = compare(this, new BigNumber2(y, b))) === 1 || b === 0; }; - P.isInteger = function() { + P.isInteger = function () { return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; }; - P.isLessThan = P.lt = function(y, b) { + P.isLessThan = P.lt = function (y, b) { return compare(this, new BigNumber2(y, b)) < 0; }; - P.isLessThanOrEqualTo = P.lte = function(y, b) { + P.isLessThanOrEqualTo = P.lte = function (y, b) { return (b = compare(this, new BigNumber2(y, b))) === -1 || b === 0; }; - P.isNaN = function() { + P.isNaN = function () { return !this.s; }; - P.isNegative = function() { + P.isNegative = function () { return this.s < 0; }; - P.isPositive = function() { + P.isPositive = function () { return this.s > 0; }; - P.isZero = function() { + P.isZero = function () { return !!this.c && this.c[0] == 0; }; - P.minus = function(y, b) { - var i, j, t, xLTy, x = this, a = x.s; + P.minus = function (y, b) { + var i, + j, + t, + xLTy, + x = this, + a = x.s; y = new BigNumber2(y, b); b = y.s; - if (!a || !b) - return new BigNumber2(NaN); + if (!a || !b) return new BigNumber2(NaN); if (a != b) { y.s = -b; return x.plus(y); } - var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c; + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; if (!xe || !ye) { if (!xc || !yc) - return xc ? (y.s = -b, y) : new BigNumber2(yc ? x : NaN); + return xc ? ((y.s = -b), y) : new BigNumber2(yc ? x : NaN); if (!xc[0] || !yc[0]) { - return yc[0] ? (y.s = -b, y) : new BigNumber2(xc[0] ? x : ( - // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity - ROUNDING_MODE == 3 ? -0 : 0 - )); + return yc[0] + ? ((y.s = -b), y) + : new BigNumber2( + xc[0] + ? x + : // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 + ? -0 + : 0, + ); } } xe = bitFloor(xe); ye = bitFloor(ye); xc = xc.slice(); - if (a = xe - ye) { - if (xLTy = a < 0) { + if ((a = xe - ye)) { + if ((xLTy = a < 0)) { a = -a; t = xc; } else { @@ -1050,8 +1183,7 @@ function clone(configObject) { t = yc; } t.reverse(); - for (b = a; b--; t.push(0)) - ; + for (b = a; b--; t.push(0)); t.reverse(); } else { j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; @@ -1062,37 +1194,34 @@ function clone(configObject) { } } } - if (xLTy) - t = xc, xc = yc, yc = t, y.s = -y.s; + if (xLTy) (t = xc), (xc = yc), (yc = t), (y.s = -y.s); b = (j = yc.length) - (i = xc.length); - if (b > 0) - for (; b--; xc[i++] = 0) - ; + if (b > 0) for (; b--; xc[i++] = 0); b = BASE - 1; for (; j > a; ) { if (xc[--j] < yc[j]) { - for (i = j; i && !xc[--i]; xc[i] = b) - ; + for (i = j; i && !xc[--i]; xc[i] = b); --xc[i]; xc[j] += BASE; } xc[j] -= yc[j]; } - for (; xc[0] == 0; xc.splice(0, 1), --ye) - ; + for (; xc[0] == 0; xc.splice(0, 1), --ye); if (!xc[0]) { y.s = ROUNDING_MODE == 3 ? -1 : 1; - y.c = [y.e = 0]; + y.c = [(y.e = 0)]; return y; } return normalise(y, xc, ye); }; - P.modulo = P.mod = function(y, b) { - var q, s, x = this; + P.modulo = P.mod = function (y, b) { + var q, + s, + x = this; y = new BigNumber2(y, b); - if (!x.c || !y.s || y.c && !y.c[0]) { + if (!x.c || !y.s || (y.c && !y.c[0])) { return new BigNumber2(NaN); - } else if (!y.c || x.c && !x.c[0]) { + } else if (!y.c || (x.c && !x.c[0])) { return new BigNumber2(x); } if (MODULO_MODE == 9) { @@ -1105,14 +1234,30 @@ function clone(configObject) { q = div(x, y, 0, MODULO_MODE); } y = x.minus(q.times(y)); - if (!y.c[0] && MODULO_MODE == 1) - y.s = x.s; + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; return y; }; - P.multipliedBy = P.times = function(y, b) { - var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, base, sqrtBase, x = this, xc = x.c, yc = (y = new BigNumber2(y, b)).c; + P.multipliedBy = P.times = function (y, b) { + var c, + e, + i, + j, + k, + m, + xcL, + xlo, + xhi, + ycL, + ylo, + yhi, + zc, + base, + sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber2(y, b)).c; if (!xc || !yc || !xc[0] || !yc[0]) { - if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + if (!x.s || !y.s || (xc && !xc[0] && !yc) || (yc && !yc[0] && !xc)) { y.c = y.e = y.s = null; } else { y.s *= x.s; @@ -1130,21 +1275,20 @@ function clone(configObject) { xcL = xc.length; ycL = yc.length; if (xcL < ycL) - zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i; - for (i = xcL + ycL, zc = []; i--; zc.push(0)) - ; + (zc = xc), (xc = yc), (yc = zc), (i = xcL), (xcL = ycL), (ycL = i); + for (i = xcL + ycL, zc = []; i--; zc.push(0)); base = BASE; sqrtBase = SQRT_BASE; for (i = ycL; --i >= 0; ) { c = 0; ylo = yc[i] % sqrtBase; - yhi = yc[i] / sqrtBase | 0; + yhi = (yc[i] / sqrtBase) | 0; for (k = xcL, j = i + k; j > i; ) { xlo = xc[--k] % sqrtBase; - xhi = xc[k] / sqrtBase | 0; + xhi = (xc[k] / sqrtBase) | 0; m = yhi * xlo + xhi * ylo; - xlo = ylo * xlo + m % sqrtBase * sqrtBase + zc[j] + c; - c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + xlo = ylo * xlo + (m % sqrtBase) * sqrtBase + zc[j] + c; + c = ((xlo / base) | 0) + ((m / sqrtBase) | 0) + yhi * xhi; zc[j--] = xlo % base; } zc[j] = c; @@ -1156,32 +1300,35 @@ function clone(configObject) { } return normalise(y, zc, e); }; - P.negated = function() { + P.negated = function () { var x = new BigNumber2(this); x.s = -x.s || null; return x; }; - P.plus = function(y, b) { - var t, x = this, a = x.s; + P.plus = function (y, b) { + var t, + x = this, + a = x.s; y = new BigNumber2(y, b); b = y.s; - if (!a || !b) - return new BigNumber2(NaN); + if (!a || !b) return new BigNumber2(NaN); if (a != b) { y.s = -b; return x.minus(y); } - var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c; + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; if (!xe || !ye) { - if (!xc || !yc) - return new BigNumber2(a / 0); + if (!xc || !yc) return new BigNumber2(a / 0); if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber2(xc[0] ? x : a * 0); } xe = bitFloor(xe); ye = bitFloor(ye); xc = xc.slice(); - if (a = xe - ye) { + if ((a = xe - ye)) { if (a > 0) { ye = xe; t = yc; @@ -1190,16 +1337,14 @@ function clone(configObject) { t = xc; } t.reverse(); - for (; a--; t.push(0)) - ; + for (; a--; t.push(0)); t.reverse(); } a = xc.length; b = yc.length; - if (a - b < 0) - t = yc, yc = xc, xc = t, b = a; + if (a - b < 0) (t = yc), (yc = xc), (xc = t), (b = a); for (a = 0; b; ) { - a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + a = ((xc[--b] = xc[b] + yc[b] + a) / BASE) | 0; xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; } if (a) { @@ -1208,69 +1353,78 @@ function clone(configObject) { } return normalise(y, xc, ye); }; - P.precision = P.sd = function(sd, rm) { - var c, n, v, x = this; + P.precision = P.sd = function (sd, rm) { + var c, + n, + v, + x = this; if (sd != null && sd !== !!sd) { intCheck(sd, 1, MAX); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck(rm, 0, 8); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); return round(new BigNumber2(x), sd, rm); } - if (!(c = x.c)) - return null; + if (!(c = x.c)) return null; v = c.length - 1; n = v * LOG_BASE + 1; - if (v = c[v]) { - for (; v % 10 == 0; v /= 10, n--) - ; - for (v = c[0]; v >= 10; v /= 10, n++) - ; + if ((v = c[v])) { + for (; v % 10 == 0; v /= 10, n--); + for (v = c[0]; v >= 10; v /= 10, n++); } - if (sd && x.e + 1 > n) - n = x.e + 1; + if (sd && x.e + 1 > n) n = x.e + 1; return n; }; - P.shiftedBy = function(k) { + P.shiftedBy = function (k) { intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); - return this.times("1e" + k); + return this.times('1e' + k); }; - P.squareRoot = P.sqrt = function() { - var m, n, r, rep, t, x = this, c = x.c, s = x.s, e = x.e, dp = DECIMAL_PLACES + 4, half = new BigNumber2("0.5"); + P.squareRoot = P.sqrt = function () { + var m, + n, + r, + rep, + t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber2('0.5'); if (s !== 1 || !c || !c[0]) { - return new BigNumber2(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + return new BigNumber2( + !s || (s < 0 && (!c || c[0])) ? NaN : c ? x : 1 / 0, + ); } s = Math.sqrt(+valueOf(x)); if (s == 0 || s == 1 / 0) { n = coeffToString(c); - if ((n.length + e) % 2 == 0) - n += "0"; + if ((n.length + e) % 2 == 0) n += '0'; s = Math.sqrt(+n); e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); if (s == 1 / 0) { - n = "5e" + e; + n = '5e' + e; } else { n = s.toExponential(); - n = n.slice(0, n.indexOf("e") + 1) + e; + n = n.slice(0, n.indexOf('e') + 1) + e; } r = new BigNumber2(n); } else { - r = new BigNumber2(s + ""); + r = new BigNumber2(s + ''); } if (r.c[0]) { e = r.e; s = e + dp; - if (s < 3) - s = 0; - for (; ; ) { + if (s < 3) s = 0; + for (;;) { t = r; r = half.times(t.plus(div(x, t, dp, 1))); - if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { - if (r.e < e) - --s; + if ( + coeffToString(t.c).slice(0, s) === + (n = coeffToString(r.c)).slice(0, s) + ) { + if (r.e < e) --s; n = n.slice(s - 3, s + 1); - if (n == "9999" || !rep && n == "4999") { + if (n == '9999' || (!rep && n == '4999')) { if (!rep) { round(t, t.e + DECIMAL_PLACES + 2, 0); if (t.times(t).eq(x)) { @@ -1282,7 +1436,7 @@ function clone(configObject) { s += 4; rep = 1; } else { - if (!+n || !+n.slice(1) && n.charAt(0) == "5") { + if (!+n || (!+n.slice(1) && n.charAt(0) == '5')) { round(r, r.e + DECIMAL_PLACES + 2, 1); m = !r.times(r).eq(x); } @@ -1293,88 +1447,117 @@ function clone(configObject) { } return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); }; - P.toExponential = function(dp, rm) { + P.toExponential = function (dp, rm) { if (dp != null) { intCheck(dp, 0, MAX); dp++; } return format(this, dp, rm, 1); }; - P.toFixed = function(dp, rm) { + P.toFixed = function (dp, rm) { if (dp != null) { intCheck(dp, 0, MAX); dp = dp + this.e + 1; } return format(this, dp, rm); }; - P.toFormat = function(dp, rm, format2) { - var str, x = this; + P.toFormat = function (dp, rm, format2) { + var str, + x = this; if (format2 == null) { - if (dp != null && rm && typeof rm == "object") { + if (dp != null && rm && typeof rm == 'object') { format2 = rm; rm = null; - } else if (dp && typeof dp == "object") { + } else if (dp && typeof dp == 'object') { format2 = dp; dp = rm = null; } else { format2 = FORMAT; } - } else if (typeof format2 != "object") { - throw Error(bignumberError + "Argument not an object: " + format2); + } else if (typeof format2 != 'object') { + throw Error(bignumberError + 'Argument not an object: ' + format2); } str = x.toFixed(dp, rm); if (x.c) { - var i, arr = str.split("."), g1 = +format2.groupSize, g2 = +format2.secondaryGroupSize, groupSeparator = format2.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; - if (g2) - i = g1, g1 = g2, g2 = i, len -= i; + var i, + arr = str.split('.'), + g1 = +format2.groupSize, + g2 = +format2.secondaryGroupSize, + groupSeparator = format2.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + if (g2) (i = g1), (g1 = g2), (g2 = i), (len -= i); if (g1 > 0 && len > 0) { i = len % g1 || g1; intPart = intDigits.substr(0, i); for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); - if (g2 > 0) - intPart += groupSeparator + intDigits.slice(i); - if (isNeg) - intPart = "-" + intPart; + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; } - str = fractionPart ? intPart + (format2.decimalSeparator || "") + ((g2 = +format2.fractionGroupSize) ? fractionPart.replace( - new RegExp("\\d{" + g2 + "}\\B", "g"), - "$&" + (format2.fractionGroupSeparator || "") - ) : fractionPart) : intPart; + str = fractionPart + ? intPart + + (format2.decimalSeparator || '') + + ((g2 = +format2.fractionGroupSize) + ? fractionPart.replace( + new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + (format2.fractionGroupSeparator || ''), + ) + : fractionPart) + : intPart; } - return (format2.prefix || "") + str + (format2.suffix || ""); + return (format2.prefix || '') + str + (format2.suffix || ''); }; - P.toFraction = function(md) { - var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, x = this, xc = x.c; + P.toFraction = function (md) { + var d, + d0, + d1, + d2, + e, + exp, + n, + n0, + n1, + q, + r, + s, + x = this, + xc = x.c; if (md != null) { n = new BigNumber2(md); - if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { - throw Error(bignumberError + "Argument " + (n.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n)); + if ((!n.isInteger() && (n.c || n.s !== 1)) || n.lt(ONE)) { + throw Error( + bignumberError + + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + + valueOf(n), + ); } } - if (!xc) - return new BigNumber2(x); + if (!xc) return new BigNumber2(x); d = new BigNumber2(ONE); n1 = d0 = new BigNumber2(ONE); d1 = n0 = new BigNumber2(ONE); s = coeffToString(xc); e = d.e = s.length - x.e - 1; d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; - md = !md || n.comparedTo(d) > 0 ? e > 0 ? d : n1 : n; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; exp = MAX_EXP; MAX_EXP = 1 / 0; n = new BigNumber2(s); n0.c[0] = 0; - for (; ; ) { + for (;;) { q = div(n, d, 0, 1); d2 = d0.plus(q.times(d1)); - if (d2.comparedTo(md) == 1) - break; + if (d2.comparedTo(md) == 1) break; d0 = d1; d1 = d2; - n1 = n0.plus(q.times(d2 = n1)); + n1 = n0.plus(q.times((d2 = n1))); n0 = d2; - d = n.minus(q.times(d2 = d)); + d = n.minus(q.times((d2 = d))); n = d2; } d2 = div(md.minus(d0), d1, 0, 1); @@ -1382,53 +1565,65 @@ function clone(configObject) { d0 = d0.plus(d2.times(d1)); n0.s = n1.s = x.s; e = e * 2; - r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( - div(n0, d0, e, ROUNDING_MODE).minus(x).abs() - ) < 1 ? [n1, d1] : [n0, d0]; + r = + div(n1, d1, e, ROUNDING_MODE) + .minus(x) + .abs() + .comparedTo(div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 + ? [n1, d1] + : [n0, d0]; MAX_EXP = exp; return r; }; - P.toNumber = function() { + P.toNumber = function () { return +valueOf(this); }; - P.toPrecision = function(sd, rm) { - if (sd != null) - intCheck(sd, 1, MAX); + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); return format(this, sd, rm, 2); }; - P.toString = function(b) { - var str, n = this, s = n.s, e = n.e; + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; if (e === null) { if (s) { - str = "Infinity"; - if (s < 0) - str = "-" + str; + str = 'Infinity'; + if (s < 0) str = '-' + str; } else { - str = "NaN"; + str = 'NaN'; } } else { if (b == null) { - str = e <= TO_EXP_NEG || e >= TO_EXP_POS ? toExponential(coeffToString(n.c), e) : toFixedPoint(coeffToString(n.c), e, "0"); + str = + e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(coeffToString(n.c), e) + : toFixedPoint(coeffToString(n.c), e, '0'); } else if (b === 10 && alphabetHasNormalDecimalDigits) { n = round(new BigNumber2(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); - str = toFixedPoint(coeffToString(n.c), n.e, "0"); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); } else { - intCheck(b, 2, ALPHABET.length, "Base"); - str = convertBase(toFixedPoint(coeffToString(n.c), e, "0"), 10, b, s, true); + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase( + toFixedPoint(coeffToString(n.c), e, '0'), + 10, + b, + s, + true, + ); } - if (s < 0 && n.c[0]) - str = "-" + str; + if (s < 0 && n.c[0]) str = '-' + str; } return str; }; - P.valueOf = P.toJSON = function() { + P.valueOf = P.toJSON = function () { return valueOf(this); }; P._isBigNumber = true; - P[Symbol.toStringTag] = "BigNumber"; - P[Symbol.for("nodejs.util.inspect.custom")] = P.valueOf; - if (configObject != null) - BigNumber2.set(configObject); + P[Symbol.toStringTag] = 'BigNumber'; + P[Symbol.for('nodejs.util.inspect.custom')] = P.valueOf; + if (configObject != null) BigNumber2.set(configObject); return BigNumber2; } function bitFloor(n) { @@ -1436,43 +1631,55 @@ function bitFloor(n) { return n > 0 || n === i ? i : i - 1; } function coeffToString(a) { - var s, z, i = 1, j = a.length, r = a[0] + ""; + var s, + z, + i = 1, + j = a.length, + r = a[0] + ''; for (; i < j; ) { - s = a[i++] + ""; + s = a[i++] + ''; z = LOG_BASE - s.length; - for (; z--; s = "0" + s) - ; + for (; z--; s = '0' + s); r += s; } - for (j = r.length; r.charCodeAt(--j) === 48; ) - ; + for (j = r.length; r.charCodeAt(--j) === 48; ); return r.slice(0, j + 1 || 1); } function compare(x, y) { - var a, b, xc = x.c, yc = y.c, i = x.s, j = y.s, k = x.e, l = y.e; - if (!i || !j) - return null; + var a, + b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + if (!i || !j) return null; a = xc && !xc[0]; b = yc && !yc[0]; - if (a || b) - return a ? b ? 0 : -j : i; - if (i != j) - return i; + if (a || b) return a ? (b ? 0 : -j) : i; + if (i != j) return i; a = i < 0; b = k == l; - if (!xc || !yc) - return b ? 0 : !xc ^ a ? 1 : -1; - if (!b) - return k > l ^ a ? 1 : -1; + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + if (!b) return (k > l) ^ a ? 1 : -1; j = (k = xc.length) < (l = yc.length) ? k : l; for (i = 0; i < j; i++) - if (xc[i] != yc[i]) - return xc[i] > yc[i] ^ a ? 1 : -1; - return k == l ? 0 : k > l ^ a ? 1 : -1; + if (xc[i] != yc[i]) return (xc[i] > yc[i]) ^ a ? 1 : -1; + return k == l ? 0 : (k > l) ^ a ? 1 : -1; } function intCheck(n, min, max, name) { if (n < min || n > max || n !== mathfloor(n)) { - throw Error(bignumberError + (name || "Argument") + (typeof n == "number" ? n < min || n > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n)); + throw Error( + bignumberError + + (name || 'Argument') + + (typeof n == 'number' + ? n < min || n > max + ? ' out of range: ' + : ' not an integer: ' + : ' not a primitive number: ') + + String(n), + ); } } function isOdd(n) { @@ -1480,22 +1687,24 @@ function isOdd(n) { return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; } function toExponential(str, e) { - return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e < 0 ? "e" : "e+") + e; + return ( + (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + + e + ); } function toFixedPoint(str, e, z) { var len, zs; if (e < 0) { - for (zs = z + "."; ++e; zs += z) - ; + for (zs = z + '.'; ++e; zs += z); str = zs + str; } else { len = str.length; if (++e > len) { - for (zs = z, e -= len; --e; zs += z) - ; + for (zs = z, e -= len; --e; zs += z); str += zs; } else if (e < len) { - str = str.slice(0, e) + "." + str.slice(e); + str = str.slice(0, e) + '.' + str.slice(e); } } return str; @@ -1504,16 +1713,18 @@ var BigNumberClone = clone(); var bignumber_default = BigNumberClone; // src/util.js -var ce = (flag, message) => (p) => flag ? Left(message) : Right(p); +var ce = (flag, message) => (p) => (flag ? Left(message) : Right(p)); function isInteger(v) { return new bignumber_default(v).isInteger(); } function roundDown(v) { - return new bignumber_default(v).integerValue(bignumber_default.ROUND_DOWN).toNumber(); + return new bignumber_default(v) + .integerValue(bignumber_default.ROUND_DOWN) + .toNumber(); } var addClaimBalanceTo = ({ state, action }) => { const indexToRemove = state.claimable.findIndex( - (claim3) => claim3.txID === action.input.txID + (claim3) => claim3.txID === action.input.txID, ); const claim2 = state.claimable[indexToRemove]; const balance2 = state.balances[claim2.to] || 0; @@ -1522,7 +1733,7 @@ var addClaimBalanceTo = ({ state, action }) => { }; var addClaimBalanceFrom = ({ state, action }) => { const indexToRemove = state.claimable.findIndex( - (claim3) => claim3.txID === action.input.tx + (claim3) => claim3.txID === action.input.tx, ); const claim2 = state.claimable[indexToRemove]; const balance2 = state.balances[claim2.from] || 0; @@ -1530,32 +1741,40 @@ var addClaimBalanceFrom = ({ state, action }) => { return indexToRemove; }; function isArweaveAddress(address) { - if (!address) - return void 0; + if (!address) return void 0; const addr = address.toString().trim(); return /[a-z0-9_-]{43}/i.test(addr); } // src/write/transfer.js function transfer(state, action) { - return of({ state, action }).chain(fromNullable).chain(ce(!action.input?.target, "Please specify a target.")).chain( - ce(action.input?.target === action.caller, "Target cannot be caller.") - ).chain(ce(!isArweaveAddress(action.input?.target), "Invalid target.")).chain(ce(!isInteger(action.input?.qty), "qty must be an integer.")).chain( - ce( - roundDown(action.input?.qty) < 1, - "Invalid token transfer. qty must be an integer greater than 0." + return of({ state, action }) + .chain(fromNullable) + .chain(ce(!action.input?.target, 'Please specify a target.')) + .chain( + ce(action.input?.target === action.caller, 'Target cannot be caller.'), ) - ).chain( - ce( - (state.balances[action.caller] || 0) < roundDown(action.input?.qty), - "Not enough tokens for transfer." + .chain(ce(!isArweaveAddress(action.input?.target), 'Invalid target.')) + .chain(ce(!isInteger(action.input?.qty), 'qty must be an integer.')) + .chain( + ce( + roundDown(action.input?.qty) < 1, + 'Invalid token transfer. qty must be an integer greater than 0.', + ), ) - ).map(updateBalances).fold( - (error) => { - throw new ContractError(error || "An error occurred."); - }, - () => ({ state }) - ); + .chain( + ce( + (state.balances[action.caller] || 0) < roundDown(action.input?.qty), + 'Not enough tokens for transfer.', + ), + ) + .map(updateBalances) + .fold( + (error) => { + throw new ContractError(error || 'An error occurred.'); + }, + () => ({ state }), + ); } var updateBalances = ({ state, action }) => { const safeQty = roundDown(action.input.qty); @@ -1566,65 +1785,86 @@ var updateBalances = ({ state, action }) => { // src/write/claim.js function claim(state, action) { - return of({ state, action }).chain(fromNullable).chain( - ce(!action.input?.txID, "txID must be passed to the claim function.") - ).chain(ce(!action.input?.qty, "A qty must be specified.")).chain( - ce( - state.claimable.filter((c) => c.txID === action.input.txID).length !== 1, - "There must be 1 claimable with this tx id." + return of({ state, action }) + .chain(fromNullable) + .chain( + ce(!action.input?.txID, 'txID must be passed to the claim function.'), ) - ).chain( - ce( - state.claimable.filter((c) => c.txID === action.input?.txID)[0]?.to !== action.caller, - "Claim not addressed to caller." + .chain(ce(!action.input?.qty, 'A qty must be specified.')) + .chain( + ce( + state.claimable.filter((c) => c.txID === action.input.txID).length !== + 1, + 'There must be 1 claimable with this tx id.', + ), ) - ).chain( - ce( - state.claimable.filter((c) => c.txID === action.input.txID)[0]?.qty !== action.input?.qty, - "Incorrect qty." + .chain( + ce( + state.claimable.filter((c) => c.txID === action.input?.txID)[0]?.to !== + action.caller, + 'Claim not addressed to caller.', + ), ) - ).map(addClaimBalanceTo).map((indexToRemove) => { - state.claimable.splice(indexToRemove, 1); - return state; - }).fold( - (msg) => { - throw new ContractError(msg || "An error occurred."); - }, - () => { - return { state }; - } - ); + .chain( + ce( + state.claimable.filter((c) => c.txID === action.input.txID)[0]?.qty !== + action.input?.qty, + 'Incorrect qty.', + ), + ) + .map(addClaimBalanceTo) + .map((indexToRemove) => { + state.claimable.splice(indexToRemove, 1); + return state; + }) + .fold( + (msg) => { + throw new ContractError(msg || 'An error occurred.'); + }, + () => { + return { state }; + }, + ); } // src/write/allow.js function allow(state, action) { - return of(action.caller).chain(fromNullable).chain(ce(!action.input?.target, "Please specify a target.")).chain( - ce(action.input?.target === action.caller, "Target cannot be caller.") - ).chain(ce(!isArweaveAddress(action.input?.target), "Invalid target.")).chain(ce(!isInteger(action.input?.qty), "qty must be an integer.")).chain( - ce( - roundDown(action.input?.qty) < 1, - "Invalid token transfer. qty must be an integer greater than 0." + return of(action.caller) + .chain(fromNullable) + .chain(ce(!action.input?.target, 'Please specify a target.')) + .chain( + ce(action.input?.target === action.caller, 'Target cannot be caller.'), ) - ).chain( - ce( - (state.balances[action.caller] || 0) < roundDown(action.input?.qty), - "Not enough tokens for transfer." + .chain(ce(!isArweaveAddress(action.input?.target), 'Invalid target.')) + .chain(ce(!isInteger(action.input?.qty), 'qty must be an integer.')) + .chain( + ce( + roundDown(action.input?.qty) < 1, + 'Invalid token transfer. qty must be an integer greater than 0.', + ), ) - ).map((caller) => { - const safeQty = roundDown(action.input.qty); - state.balances[caller] -= safeQty; - state.claimable.push({ - from: caller, - to: action.input.target, - qty: safeQty, - txID: SmartWeave.transaction.id - }); - }).fold( - (msg) => { - throw new ContractError(msg || "An error occurred."); - }, - () => ({ state }) - ); + .chain( + ce( + (state.balances[action.caller] || 0) < roundDown(action.input?.qty), + 'Not enough tokens for transfer.', + ), + ) + .map((caller) => { + const safeQty = roundDown(action.input.qty); + state.balances[caller] -= safeQty; + state.claimable.push({ + from: caller, + to: action.input.target, + qty: safeQty, + txID: SmartWeave.transaction.id, + }); + }) + .fold( + (msg) => { + throw new ContractError(msg || 'An error occurred.'); + }, + () => ({ state }), + ); } // src/write/mint.js @@ -1633,60 +1873,74 @@ function mint(state, action) { state.balances[action.caller] = 0; } state.balances[action.caller] += roundDown( - SmartWeave.transaction.reward / state.divisibility + SmartWeave.transaction.reward / state.divisibility, ); return { state }; } // src/write/reject.js function rejectClaimable(state, action) { - return of({ state, action }).chain(fromNullable).chain(ce(!action.input?.tx, "txID must be passed to the reject function.")).chain( - ce( - state.claimable.filter((c) => c.txID === action.input.tx).length !== 1, - "There must be 1 claimable with this tx id." + return of({ state, action }) + .chain(fromNullable) + .chain(ce(!action.input?.tx, 'txID must be passed to the reject function.')) + .chain( + ce( + state.claimable.filter((c) => c.txID === action.input.tx).length !== 1, + 'There must be 1 claimable with this tx id.', + ), ) - ).chain( - ce( - state.claimable.filter((c) => c.txID === action.input.tx)[0]?.to !== action.caller, - "Claim not addressed to caller." + .chain( + ce( + state.claimable.filter((c) => c.txID === action.input.tx)[0]?.to !== + action.caller, + 'Claim not addressed to caller.', + ), ) - ).map(addClaimBalanceFrom).map((indexToRemove) => { - state.claimable.splice(indexToRemove, 1); - return state; - }).fold( - (msg) => { - throw new ContractError(msg || "An error occurred."); - }, - (state2) => ({ state: state2 }) - ); + .map(addClaimBalanceFrom) + .map((indexToRemove) => { + state.claimable.splice(indexToRemove, 1); + return state; + }) + .fold( + (msg) => { + throw new ContractError(msg || 'An error occurred.'); + }, + (state2) => ({ state: state2 }), + ); } // src/contract.js export async function handle(state, action) { - if (["transfer", "allow", "claim", "reject"].includes( - action?.input?.function - ) && SmartWeave.transaction.origin === "L1") { + if ( + ['transfer', 'allow', 'claim', 'reject'].includes( + action?.input?.function, + ) && + SmartWeave.transaction.origin === 'L1' + ) { return { state }; } - if (action?.input?.function === "mint" && SmartWeave.transaction.origin === "L2") + if ( + action?.input?.function === 'mint' && + SmartWeave.transaction.origin === 'L2' + ) return { state }; switch (action?.input?.function) { - case "balance": + case 'balance': return balance(state, action); - case "reject": + case 'reject': return rejectClaimable(state, action); - case "transfer": + case 'transfer': return transfer(state, action); - case "allow": + case 'allow': return allow(state, action); - case "claim": + case 'claim': return claim(state, action); - case "mint": + case 'mint': return mint(state, action); default: throw new ContractError( - `No function supplied or function not recognized` + `No function supplied or function not recognized`, ); } } -/* eslint-enable */ \ No newline at end of file +/* eslint-enable */ diff --git a/tests/utils/u/state.json b/tests/utils/u/state.json index 0f3c066..0a2ab26 100644 --- a/tests/utils/u/state.json +++ b/tests/utils/u/state.json @@ -1,18 +1,28 @@ +/** + * Copyright (C) 2022-2024 Permanent Data Solutions, Inc. All Rights Reserved. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ { "name": "U", "owner": "9x24zjvs9DA5zAz2DmqBWAg6XcxrrE-8w3EkpwRm4e4", "ticker": "U", "balances": {}, "settings": [ - [ - "isTradeable", - true - ], - [ - "communityLogo", - "J3WXX4OGa6wP5E9oLhNyqlN4deYI7ARjrd5se740ftE" - ] + ["isTradeable", true], + ["communityLogo", "J3WXX4OGa6wP5E9oLhNyqlN4deYI7ARjrd5se740ftE"] ], "claimable": [], "divisibility": 1000000 -} \ No newline at end of file +} diff --git a/tests/utils/ucm/source.js b/tests/utils/ucm/source.js index b5c1313..d824cbb 100644 --- a/tests/utils/ucm/source.js +++ b/tests/utils/ucm/source.js @@ -6,15 +6,16 @@ var Right = (x) => ({ ap: (other) => other.map(x), alt: (other) => Right(x), extend: (f) => f(Right(x)), - concat: (other) => other.fold( - (x2) => other, - (y) => Right(x.concat(y)) - ), + concat: (other) => + other.fold( + (x2) => other, + (y) => Right(x.concat(y)), + ), traverse: (of2, f) => f(x).map(Right), map: (f) => Right(f(x)), fold: (_, g) => g(x), toString: () => `Right(${x})`, - extract: () => x + extract: () => x, }); var Left = (x) => ({ isLeft: true, @@ -27,7 +28,7 @@ var Left = (x) => ({ map: (_) => Left(x), fold: (f, _) => f(x), toString: () => `Left(${x})`, - extract: () => x + extract: () => x, }); var of = Right; @@ -38,7 +39,7 @@ function addPair(state, action) { function updatePairs({ state, action }) { state.pairs.push({ pair: action.input.pair, - orders: [] + orders: [], }); return { state }; } @@ -47,18 +48,22 @@ function validate({ state, action }) { state.pairs = []; } if (!action.input.pair) { - return Left("pair is required"); + return Left('pair is required'); } if (!action.input.pair[0].length === 43) { - return Left("Each pair must be a contract address"); + return Left('Each pair must be a contract address'); } if (!action.input.pair[1].length === 43) { - return Left("Each pair must be a contract address"); + return Left('Each pair must be a contract address'); } - if (state.pairs.find( - ({ pair: existingPair }) => existingPair.includes(action.input.pair[0]) && existingPair.includes(action.input.pair[1]) - )) { - return Left("Pair already exists"); + if ( + state.pairs.find( + ({ pair: existingPair }) => + existingPair.includes(action.input.pair[0]) && + existingPair.includes(action.input.pair[1]), + ) + ) { + return Left('Pair already exists'); } return Right({ state, action }); } @@ -82,7 +87,8 @@ function calculateStreak(lastHeight = 0, currentHeight = 0, streak = 0) { } // src/write/claim.js -var claim = (state, action) => of({ state, action }).chain(validate2).map(update); +var claim = (state, action) => + of({ state, action }).chain(validate2).map(update); function update({ state, action, idx }) { if (!state.balances[action.caller]) { state.balances[action.caller] = 0; @@ -93,26 +99,26 @@ function update({ state, action, idx }) { } function validate2({ state, action }) { if (!action.input.txID) { - return Left("txID is not found."); + return Left('txID is not found.'); } if (!action.input.qty) { - return Left("claim quantity is not specified."); + return Left('claim quantity is not specified.'); } const idx = state.claimable.findIndex((c) => c.txID === action.input.txID); if (idx < 0) { - return Left("claimable not found."); + return Left('claimable not found.'); } if (state.claimable[idx].qty !== action.input.qty) { - return Left("claimable qty is not equal to claim qty."); + return Left('claimable qty is not equal to claim qty.'); } if (state.claimable[idx].to !== action.caller) { - return Left("claim is not addressed to caller."); + return Left('claim is not addressed to caller.'); } return Right({ state, action, idx }); } // src/write/create-order.js -var U = "KTzTXT_ANmF84fWEKHzWURD1LWd9QaFR9yfYUwH2Lxw"; +var U = 'KTzTXT_ANmF84fWEKHzWURD1LWd9QaFR9yfYUwH2Lxw'; var CreateOrder = async (state, action) => { U = state.U; const caller = action.caller; @@ -126,42 +132,56 @@ var CreateOrder = async (state, action) => { let balances = state.balances; ContractAssert( isAddress(usedPair[0]) && isAddress(usedPair[1]), - "One of two supplied pair tokens is invalid" + 'One of two supplied pair tokens is invalid', ); if (price) { - ContractAssert(typeof price === "number", "Price must be a number"); + ContractAssert(typeof price === 'number', 'Price must be a number'); ContractAssert( price === void 0 || price === null || price > 0, - "Price must be greater than 0" + 'Price must be greater than 0', ); } if (!Number.isInteger(qty) || qty === void 0) { - throw new ContractError("Invalid value for quantity. Must be an integer."); + throw new ContractError('Invalid value for quantity. Must be an integer.'); } let contractID = usedPair[0]; if (contractID === SmartWeave.contract.id) { - tokenTx = "INTERNAL_TRANSFER"; + tokenTx = 'INTERNAL_TRANSFER'; if (qty <= 0 || caller === SmartWeave.contract.id) { - throw new ContractError("Invalid token transfer."); + throw new ContractError('Invalid token transfer.'); } - if (state.claimable.find((claim2) => claim2.from === action.caller && claim2.txID === action.input.transaction)) { - const claimResult = claim(state, { caller: SmartWeave.contract.id, input: { ...action.input, txID: action.input.transaction } }).fold((m) => { - throw new ContractError( - "ERROR trying to create order for PIXL: " + m - ); - }, (x) => x); - balances[SmartWeave.contract.id] = claimResult.state.balances[SmartWeave.contract.id]; + if ( + state.claimable.find( + (claim2) => + claim2.from === action.caller && + claim2.txID === action.input.transaction, + ) + ) { + const claimResult = claim(state, { + caller: SmartWeave.contract.id, + input: { ...action.input, txID: action.input.transaction }, + }).fold( + (m) => { + throw new ContractError( + 'ERROR trying to create order for PIXL: ' + m, + ); + }, + (x) => x, + ); + balances[SmartWeave.contract.id] = + claimResult.state.balances[SmartWeave.contract.id]; state.claimable = claimResult.state.claimable; } else { - throw new ContractError( - "Can not claim balance for PIXL" - ); + throw new ContractError('Can not claim balance for PIXL'); } - } else if (usedPair[1] === SmartWeave.contract.id && tokenTx === "INTERNAL_TRANSFER") { + } else if ( + usedPair[1] === SmartWeave.contract.id && + tokenTx === 'INTERNAL_TRANSFER' + ) { } else { if (tokenTx === void 0 || tokenTx === null) { throw new ContractError( - "No token transaction provided given the token in the order is from a different contract" + 'No token transaction provided given the token in the order is from a different contract', ); } await claimBalance(contractID, tokenTx, qty); @@ -176,15 +196,18 @@ var CreateOrder = async (state, action) => { } } else { await SmartWeave.contracts.write(contractID, { - function: "transfer", + function: 'transfer', target: caller, - qty + qty, }); } }; let pairIndex = -1; for (let i = 0; i < pairs.length; i++) { - if (pairs[i].pair[0] === usedPair[0] && pairs[i].pair[1] === usedPair[1] || pairs[i].pair[0] === usedPair[1] && pairs[i].pair[1] === usedPair[0]) { + if ( + (pairs[i].pair[0] === usedPair[0] && pairs[i].pair[1] === usedPair[1]) || + (pairs[i].pair[0] === usedPair[1] && pairs[i].pair[1] === usedPair[0]) + ) { pairIndex = i; } } @@ -193,15 +216,15 @@ var CreateOrder = async (state, action) => { return { state, result: { - status: "failure", - message: "This pair does not exist yet" - } + status: 'failure', + message: 'This pair does not exist yet', + }, }; } let sortedOrderbook; if (state.pairs[pairIndex].orders.length > 0) { - sortedOrderbook = state.pairs[pairIndex].orders.sort( - (a, b) => a.price > b.price ? 1 : -1 + sortedOrderbook = state.pairs[pairIndex].orders.sort((a, b) => + a.price > b.price ? 1 : -1, ); } else { sortedOrderbook = []; @@ -213,28 +236,32 @@ var CreateOrder = async (state, action) => { pair: { dominant: dominantToken, from: contractID, - to: usedPair.find((val) => val !== contractID) + to: usedPair.find((val) => val !== contractID), }, quantity: qty, creator: caller, transaction: SmartWeave.transaction.id, transfer: tokenTx, - price + price, }, - sortedOrderbook + sortedOrderbook, ); - const maxPrice = matches.reduce((a, v) => v.price > a ? v.price : a, 0); + const maxPrice = matches.reduce((a, v) => (v.price > a ? v.price : a), 0); if (maxPrice > max) { - throw new Error("can not purchase item it is greater than max bid"); + throw new Error('can not purchase item it is greater than max bid'); } state.pairs[pairIndex].orders = orderbook; if (matches.length > 0) { - const vwap = matches.map(({ qty: volume, price: price2 }) => volume * price2).reduce((a, b) => a + b, 0) / matches.map(({ qty: volume }) => volume).reduce((a, b) => a + b, 0); + const vwap = + matches + .map(({ qty: volume, price: price2 }) => volume * price2) + .reduce((a, b) => a + b, 0) / + matches.map(({ qty: volume }) => volume).reduce((a, b) => a + b, 0); state.pairs[pairIndex].priceData = { dominantToken, block: SmartWeave.block.height, vwap, - matchLogs: matches + matchLogs: matches, }; } else { state.pairs[pairIndex].priceData = void 0; @@ -259,17 +286,17 @@ var CreateOrder = async (state, action) => { const streakUpdate = calculateStreak( state.streaks[buyer].lastHeight, Number(SmartWeave.block.height), - state.streaks[buyer].days + state.streaks[buyer].days, ); state.streaks[buyer] = streakUpdate; } const result = await SmartWeave.contracts.write( foreignCalls[i].contract, - foreignCalls[i].input + foreignCalls[i].input, ); - if (result.type !== "ok") { + if (result.type !== 'ok') { throw new ContractError( - `Unable to fill order with txID: ${foreignCalls[i].txID}` + `Unable to fill order with txID: ${foreignCalls[i].txID}`, ); } } @@ -280,30 +307,31 @@ var CreateOrder = async (state, action) => { return { state, result: { - status: "success", - message: "Order created successfully" - } + status: 'success', + message: 'Order created successfully', + }, }; } catch (e) { await refundTransfer(); return { state, result: { - status: "failure", - message: e.message - } + status: 'failure', + message: e.message, + }, }; } }; function matchOrder(input, orderbook) { - const orderType = input.price ? "limit" : "market"; + const orderType = input.price ? 'limit' : 'market'; const foreignCalls = []; const matches = []; const reverseOrders = orderbook.filter( - (order) => input.pair.from !== order.token && order.id !== input.transaction + (order) => + input.pair.from !== order.token && order.id !== input.transaction, ); if (!reverseOrders.length) { - if (orderType !== "limit") + if (orderType !== 'limit') throw new Error('The first order for a pair can only be a "limit" order'); orderbook.push({ id: input.transaction, @@ -312,28 +340,30 @@ function matchOrder(input, orderbook) { token: input.pair.from, price: input.price, quantity: Math.round(input.quantity), - originalQuantity: input.quantity + originalQuantity: input.quantity, }); return { orderbook, foreignCalls, - matches + matches, }; } let fillAmount; let receiveAmount = 0; let remainingQuantity = input.quantity; const newOrderbook = orderbook.reduce((acc, currentOrder) => { - if (input.pair.from === currentOrder.token || currentOrder.id === input.transaction) { + if ( + input.pair.from === currentOrder.token || + currentOrder.id === input.transaction + ) { acc.push(currentOrder); return acc; } const reversePrice = 1 / currentOrder.price; - if (orderType === "limit" && input.price !== reversePrice) { + if (orderType === 'limit' && input.price !== reversePrice) { acc.push(currentOrder); return acc; } - ; fillAmount = Math.floor(remainingQuantity * (input.price ?? reversePrice)); let receiveFromCurrent = 0; if (fillAmount <= currentOrder.quantity) { @@ -345,10 +375,10 @@ function matchOrder(input, orderbook) { txID: SmartWeave.transaction.id, contract: input.pair.from, input: { - function: "transfer", + function: 'transfer', target: currentOrder.creator, - qty: Math.round(remainingQuantity * 0.995) - } + qty: Math.round(remainingQuantity * 0.995), + }, }); } remainingQuantity = 0; @@ -361,10 +391,10 @@ function matchOrder(input, orderbook) { txID: SmartWeave.transaction.id, contract: input.pair.from, input: { - function: "transfer", + function: 'transfer', target: currentOrder.creator, - qty: Math.round(sendAmount * 0.995) - } + qty: Math.round(sendAmount * 0.995), + }, }); currentOrder.quantity = 0; } @@ -378,7 +408,7 @@ function matchOrder(input, orderbook) { matches.push({ id: currentOrder.id, qty: receiveFromCurrent, - price: dominantPrice + price: dominantPrice, }); } if (currentOrder.quantity !== 0) { @@ -387,7 +417,7 @@ function matchOrder(input, orderbook) { return acc; }, []); if (remainingQuantity > 0) { - if (orderType === "limit") { + if (orderType === 'limit') { newOrderbook.push({ id: input.transaction, transfer: input.transfer, @@ -395,17 +425,17 @@ function matchOrder(input, orderbook) { token: input.pair.from, price: input.price, quantity: Math.round(remainingQuantity), - originalQuantity: input.quantity + originalQuantity: input.quantity, }); } else { foreignCalls.push({ txID: SmartWeave.transaction.id, contract: input.pair.from, input: { - function: "transfer", + function: 'transfer', target: input.creator, - qty: remainingQuantity - } + qty: remainingQuantity, + }, }); } } @@ -413,24 +443,24 @@ function matchOrder(input, orderbook) { txID: SmartWeave.transaction.id, contract: input.pair.to, input: { - function: "transfer", + function: 'transfer', target: input.creator, - qty: Math.round(receiveAmount * 0.995) - } + qty: Math.round(receiveAmount * 0.995), + }, }); return { orderbook: newOrderbook, foreignCalls, - matches + matches, }; } var claimBalance = async (tokenID, transferTx, qty) => { const result = await SmartWeave.contracts.write(tokenID, { - function: "claim", + function: 'claim', txID: transferTx, - qty + qty, }); - if (result.type !== "ok") { + if (result.type !== 'ok') { throw new ContractError(`Unable to make claim with txID: ${transferTx}`); } }; @@ -441,13 +471,13 @@ var CancelOrder = async (state, action) => { const caller = action.caller; const input = action.input; const orderTxID = input.orderID; - ContractAssert(isAddress2(orderTxID), "Invalid order ID"); + ContractAssert(isAddress2(orderTxID), 'Invalid order ID'); const allOrders = state.pairs.map((pair) => pair.orders).flat(1); const order = allOrders.find(({ id }) => id === orderTxID); - ContractAssert(order !== void 0, "Order does not exist"); + ContractAssert(order !== void 0, 'Order does not exist'); ContractAssert( order.creator === caller, - "Caller is not the creator of the order" + 'Caller is not the creator of the order', ); if (order.token === SmartWeave.contract.id) { state.balances[SmartWeave.contract.id] -= order.quantity; @@ -458,26 +488,26 @@ var CancelOrder = async (state, action) => { } } else { const result = await SmartWeave.contracts.write(order.token, { - function: "transfer", + function: 'transfer', target: caller, - qty: order.quantity + qty: order.quantity, }); - if (result.type !== "ok") { + if (result.type !== 'ok') { throw new ContractError( - `Unable to make claim with txID: ${SmartWeave.transaction.id}` + `Unable to make claim with txID: ${SmartWeave.transaction.id}`, ); } } - const acitvePair = state.pairs.find( - (pair) => pair.orders.find(({ id }) => id === orderTxID) + const acitvePair = state.pairs.find((pair) => + pair.orders.find(({ id }) => id === orderTxID), ); acitvePair.orders = acitvePair.orders.filter(({ id }) => id !== orderTxID); return { state, result: { - status: "success", - message: "Order cancelled successfully" - } + status: 'success', + message: 'Order cancelled successfully', + }, }; }; var isAddress2 = (addr) => /[a-z0-9_-]{43}/i.test(addr); @@ -489,26 +519,27 @@ function balance(state, action) { } ContractAssert( /[a-z0-9_-]{43}/i.test(action.input.target), - "Invalid Target!" + 'Invalid Target!', ); if (!state.balances[action.input.target]) { return { result: { target: action.input.target, - balance: 0 - } + balance: 0, + }, }; } return { result: { target: action.input.target, - balance: state.balances[action.input.target] - } + balance: state.balances[action.input.target], + }, }; } // src/write/transfer.js -var transfer = (state, action) => of({ state, action }).chain(validate3).map(update2); +var transfer = (state, action) => + of({ state, action }).chain(validate3).map(update2); function update2({ state, action }) { state.balances[action.caller] -= action.input.qty; state.balances[action.input.target] += action.input.qty; @@ -516,16 +547,16 @@ function update2({ state, action }) { } function validate3({ state, action }) { if (!action.caller || action.caller.length !== 43) { - return Left("Caller is not valid"); + return Left('Caller is not valid'); } - if (!action.input.qty || typeof action.input.qty !== "number") { - return Left("qty is not defined or is not a number"); + if (!action.input.qty || typeof action.input.qty !== 'number') { + return Left('qty is not defined or is not a number'); } if (!action.input.target || action.input.target.length !== 43) { - return Left("target is not valid"); + return Left('target is not valid'); } if (action.caller === action.input.target) { - return Left("target cannot be caller"); + return Left('target cannot be caller'); } if (!state.balances[action.input.target]) { state.balances[action.input.target] = 0; @@ -534,26 +565,27 @@ function validate3({ state, action }) { state.balances[action.caller] = 0; } if (state.balances[action.caller] < action.input.qty) { - return Left("not enough balance to transfer"); + return Left('not enough balance to transfer'); } return Right({ state, action }); } // src/read/validate.js function validate4(state) { - ContractAssert(state.name, "Name is required!"); - ContractAssert(state.ticker, "Ticker is required!"); - ContractAssert(state.balances, "Balances Object is required!"); - ContractAssert(state.pairs, "Pairs Array is required!"); - ContractAssert(state.claimable, "Claimable Array is required!"); - ContractAssert(state.streaks, "Streaks Object is required!"); - ContractAssert(state.lastReward > -1, "Last Reward prop is required"); - ContractAssert(state.recentRewards, "Recent Rewards prop is required"); - ContractAssert(state.U, "U is required!"); + ContractAssert(state.name, 'Name is required!'); + ContractAssert(state.ticker, 'Ticker is required!'); + ContractAssert(state.balances, 'Balances Object is required!'); + ContractAssert(state.pairs, 'Pairs Array is required!'); + ContractAssert(state.claimable, 'Claimable Array is required!'); + ContractAssert(state.streaks, 'Streaks Object is required!'); + ContractAssert(state.lastReward > -1, 'Last Reward prop is required'); + ContractAssert(state.recentRewards, 'Recent Rewards prop is required'); + ContractAssert(state.U, 'U is required!'); } // src/write/allow.js -var allow = (state, action) => of({ state, action }).chain(validate5).map(update3); +var allow = (state, action) => + of({ state, action }).chain(validate5).map(update3); function update3({ state, action }) { state.balances[action.caller] -= action.input.qty; if (!state.claimable) { @@ -563,31 +595,31 @@ function update3({ state, action }) { from: action.caller, to: action.input.target, qty: action.input.qty, - txID: SmartWeave.transaction.id + txID: SmartWeave.transaction.id, }); return { state }; } function validate5({ state, action }) { if (!Number.isInteger(action.input.qty) || action.input.qty === void 0) { - return Left("Invalid value for quantity. Must be an integer."); + return Left('Invalid value for quantity. Must be an integer.'); } if (!action?.input?.target) { - return Left("No target specified."); + return Left('No target specified.'); } if (action.input.target.length !== 43) { - return Left("Target is not valid!"); + return Left('Target is not valid!'); } if (action.input.target === SmartWeave.transaction.id) { - return Left("Cant setup claim to transfer a balance to itself"); + return Left('Cant setup claim to transfer a balance to itself'); } if (action.caller === action.input.target) { - return Left("Invalid balance transfer"); + return Left('Invalid balance transfer'); } if (!state.balances[action.caller]) { - return Left("Caller does not have a balance"); + return Left('Caller does not have a balance'); } if (state.balances[action.caller] < action.input.qty) { - return Left("Caller balance is not high enough."); + return Left('Caller balance is not high enough.'); } return Right({ state, action }); } @@ -602,20 +634,22 @@ async function buyback(state) { return state; } let zAR_U = state.pairs.find( - (p) => p.pair.includes(U2) && p.pair.includes(SmartWeave.contract.id) + (p) => p.pair.includes(U2) && p.pair.includes(SmartWeave.contract.id), ); if (!zAR_U) { state.pairs.push({ pair: [SmartWeave.contract.id, U2], orders: [], - priceData: {} + priceData: {}, }); zAR_U = state.pairs.find( - (p) => p.pair.includes(U2) && p.pair.includes(SmartWeave.contract.id) + (p) => p.pair.includes(U2) && p.pair.includes(SmartWeave.contract.id), ); } let response = null; - const orderToUpdate = await zAR_U.orders.find((o) => o.creator === SmartWeave.contract.id); + const orderToUpdate = await zAR_U.orders.find( + (o) => o.creator === SmartWeave.contract.id, + ); if (orderToUpdate) { let price = Math.floor(orderToUpdate.price * DUTCH); orderToUpdate.originalQuantity = uBalance; @@ -628,14 +662,14 @@ async function buyback(state) { input: { pair: [U2, SmartWeave.contract.id], qty: Math.floor(uBalance / price), - transaction: "INTERNAL_TRANSFER", - price - } + transaction: 'INTERNAL_TRANSFER', + price, + }, }); } if (response) { response.state.balances[SmartWeave.contract.id] = 0; - if (response.result.status === "success") { + if (response.result.status === 'success') { return response.state; } else { return state; @@ -647,7 +681,9 @@ async function buyback(state) { // node_modules/ramda/es/internal/_isPlaceholder.js function _isPlaceholder(a) { - return a != null && typeof a === "object" && a["@@functional/placeholder"] === true; + return ( + a != null && typeof a === 'object' && a['@@functional/placeholder'] === true + ); } // node_modules/ramda/es/internal/_curry1.js @@ -668,15 +704,23 @@ function _curry2(fn) { case 0: return f2; case 1: - return _isPlaceholder(a) ? f2 : _curry1(function(_b) { - return fn(a, _b); - }); + return _isPlaceholder(a) + ? f2 + : _curry1(function (_b) { + return fn(a, _b); + }); default: - return _isPlaceholder(a) && _isPlaceholder(b) ? f2 : _isPlaceholder(a) ? _curry1(function(_a) { - return fn(_a, b); - }) : _isPlaceholder(b) ? _curry1(function(_b) { - return fn(a, _b); - }) : fn(a, b); + return _isPlaceholder(a) && _isPlaceholder(b) + ? f2 + : _isPlaceholder(a) + ? _curry1(function (_a) { + return fn(_a, b); + }) + : _isPlaceholder(b) + ? _curry1(function (_b) { + return fn(a, _b); + }) + : fn(a, b); } }; } @@ -691,57 +735,59 @@ var add_default = add; function _arity(n, fn) { switch (n) { case 0: - return function() { + return function () { return fn.apply(this, arguments); }; case 1: - return function(a0) { + return function (a0) { return fn.apply(this, arguments); }; case 2: - return function(a0, a1) { + return function (a0, a1) { return fn.apply(this, arguments); }; case 3: - return function(a0, a1, a2) { + return function (a0, a1, a2) { return fn.apply(this, arguments); }; case 4: - return function(a0, a1, a2, a3) { + return function (a0, a1, a2, a3) { return fn.apply(this, arguments); }; case 5: - return function(a0, a1, a2, a3, a4) { + return function (a0, a1, a2, a3, a4) { return fn.apply(this, arguments); }; case 6: - return function(a0, a1, a2, a3, a4, a5) { + return function (a0, a1, a2, a3, a4, a5) { return fn.apply(this, arguments); }; case 7: - return function(a0, a1, a2, a3, a4, a5, a6) { + return function (a0, a1, a2, a3, a4, a5, a6) { return fn.apply(this, arguments); }; case 8: - return function(a0, a1, a2, a3, a4, a5, a6, a7) { + return function (a0, a1, a2, a3, a4, a5, a6, a7) { return fn.apply(this, arguments); }; case 9: - return function(a0, a1, a2, a3, a4, a5, a6, a7, a8) { + return function (a0, a1, a2, a3, a4, a5, a6, a7, a8) { return fn.apply(this, arguments); }; case 10: - return function(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) { + return function (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) { return fn.apply(this, arguments); }; default: - throw new Error("First argument to _arity must be a non-negative integer no greater than ten"); + throw new Error( + 'First argument to _arity must be a non-negative integer no greater than ten', + ); } } // node_modules/ramda/es/internal/_curryN.js function _curryN(length, received, fn) { - return function() { + return function () { var combined = []; var argsIdx = 0; var left = length; @@ -749,7 +795,10 @@ function _curryN(length, received, fn) { var hasPlaceholder = false; while (combinedIdx < received.length || argsIdx < arguments.length) { var result; - if (combinedIdx < received.length && (!_isPlaceholder(received[combinedIdx]) || argsIdx >= arguments.length)) { + if ( + combinedIdx < received.length && + (!_isPlaceholder(received[combinedIdx]) || argsIdx >= arguments.length) + ) { result = received[combinedIdx]; } else { result = arguments[argsIdx]; @@ -763,7 +812,9 @@ function _curryN(length, received, fn) { } combinedIdx += 1; } - return !hasPlaceholder && left <= 0 ? fn.apply(this, combined) : _arity(Math.max(0, left), _curryN(length, combined, fn)); + return !hasPlaceholder && left <= 0 + ? fn.apply(this, combined) + : _arity(Math.max(0, left), _curryN(length, combined, fn)); }; } @@ -783,48 +834,76 @@ function _curry3(fn) { case 0: return f3; case 1: - return _isPlaceholder(a) ? f3 : _curry2(function(_b, _c) { - return fn(a, _b, _c); - }); + return _isPlaceholder(a) + ? f3 + : _curry2(function (_b, _c) { + return fn(a, _b, _c); + }); case 2: - return _isPlaceholder(a) && _isPlaceholder(b) ? f3 : _isPlaceholder(a) ? _curry2(function(_a, _c) { - return fn(_a, b, _c); - }) : _isPlaceholder(b) ? _curry2(function(_b, _c) { - return fn(a, _b, _c); - }) : _curry1(function(_c) { - return fn(a, b, _c); - }); + return _isPlaceholder(a) && _isPlaceholder(b) + ? f3 + : _isPlaceholder(a) + ? _curry2(function (_a, _c) { + return fn(_a, b, _c); + }) + : _isPlaceholder(b) + ? _curry2(function (_b, _c) { + return fn(a, _b, _c); + }) + : _curry1(function (_c) { + return fn(a, b, _c); + }); default: - return _isPlaceholder(a) && _isPlaceholder(b) && _isPlaceholder(c) ? f3 : _isPlaceholder(a) && _isPlaceholder(b) ? _curry2(function(_a, _b) { - return fn(_a, _b, c); - }) : _isPlaceholder(a) && _isPlaceholder(c) ? _curry2(function(_a, _c) { - return fn(_a, b, _c); - }) : _isPlaceholder(b) && _isPlaceholder(c) ? _curry2(function(_b, _c) { - return fn(a, _b, _c); - }) : _isPlaceholder(a) ? _curry1(function(_a) { - return fn(_a, b, c); - }) : _isPlaceholder(b) ? _curry1(function(_b) { - return fn(a, _b, c); - }) : _isPlaceholder(c) ? _curry1(function(_c) { - return fn(a, b, _c); - }) : fn(a, b, c); + return _isPlaceholder(a) && _isPlaceholder(b) && _isPlaceholder(c) + ? f3 + : _isPlaceholder(a) && _isPlaceholder(b) + ? _curry2(function (_a, _b) { + return fn(_a, _b, c); + }) + : _isPlaceholder(a) && _isPlaceholder(c) + ? _curry2(function (_a, _c) { + return fn(_a, b, _c); + }) + : _isPlaceholder(b) && _isPlaceholder(c) + ? _curry2(function (_b, _c) { + return fn(a, _b, _c); + }) + : _isPlaceholder(a) + ? _curry1(function (_a) { + return fn(_a, b, c); + }) + : _isPlaceholder(b) + ? _curry1(function (_b) { + return fn(a, _b, c); + }) + : _isPlaceholder(c) + ? _curry1(function (_c) { + return fn(a, b, _c); + }) + : fn(a, b, c); } }; } // node_modules/ramda/es/internal/_isArray.js -var isArray_default = Array.isArray || function _isArray(val) { - return val != null && val.length >= 0 && Object.prototype.toString.call(val) === "[object Array]"; -}; +var isArray_default = + Array.isArray || + function _isArray(val) { + return ( + val != null && + val.length >= 0 && + Object.prototype.toString.call(val) === '[object Array]' + ); + }; // node_modules/ramda/es/internal/_isTransformer.js function _isTransformer(obj) { - return obj != null && typeof obj["@@transducer/step"] === "function"; + return obj != null && typeof obj['@@transducer/step'] === 'function'; } // node_modules/ramda/es/internal/_dispatchable.js function _dispatchable(methodNames, transducerCreator, fn) { - return function() { + return function () { if (arguments.length === 0) { return fn(); } @@ -832,13 +911,19 @@ function _dispatchable(methodNames, transducerCreator, fn) { if (!isArray_default(obj)) { var idx = 0; while (idx < methodNames.length) { - if (typeof obj[methodNames[idx]] === "function") { - return obj[methodNames[idx]].apply(obj, Array.prototype.slice.call(arguments, 0, -1)); + if (typeof obj[methodNames[idx]] === 'function') { + return obj[methodNames[idx]].apply( + obj, + Array.prototype.slice.call(arguments, 0, -1), + ); } idx += 1; } if (_isTransformer(obj)) { - var transducer = transducerCreator.apply(null, Array.prototype.slice.call(arguments, 0, -1)); + var transducer = transducerCreator.apply( + null, + Array.prototype.slice.call(arguments, 0, -1), + ); return transducer(obj); } } @@ -848,12 +933,12 @@ function _dispatchable(methodNames, transducerCreator, fn) { // node_modules/ramda/es/internal/_xfBase.js var xfBase_default = { - init: function() { - return this.xf["@@transducer/init"](); + init: function () { + return this.xf['@@transducer/init'](); + }, + result: function (result) { + return this.xf['@@transducer/result'](result); }, - result: function(result) { - return this.xf["@@transducer/result"](result); - } }; // node_modules/ramda/es/internal/_has.js @@ -863,24 +948,36 @@ function _has(prop, obj) { // node_modules/ramda/es/internal/_isArguments.js var toString = Object.prototype.toString; -var _isArguments = /* @__PURE__ */ function() { - return toString.call(arguments) === "[object Arguments]" ? function _isArguments2(x) { - return toString.call(x) === "[object Arguments]"; - } : function _isArguments2(x) { - return _has("callee", x); - }; -}(); +var _isArguments = /* @__PURE__ */ (function () { + return toString.call(arguments) === '[object Arguments]' + ? function _isArguments2(x) { + return toString.call(x) === '[object Arguments]'; + } + : function _isArguments2(x) { + return _has('callee', x); + }; +})(); var isArguments_default = _isArguments; // node_modules/ramda/es/keys.js -var hasEnumBug = !/* @__PURE__ */ { - toString: null -}.propertyIsEnumerable("toString"); -var nonEnumerableProps = ["constructor", "valueOf", "isPrototypeOf", "toString", "propertyIsEnumerable", "hasOwnProperty", "toLocaleString"]; -var hasArgsEnumBug = /* @__PURE__ */ function() { - "use strict"; - return arguments.propertyIsEnumerable("length"); -}(); +var hasEnumBug = !( + /* @__PURE__ */ { + toString: null, + }.propertyIsEnumerable('toString') +); +var nonEnumerableProps = [ + 'constructor', + 'valueOf', + 'isPrototypeOf', + 'toString', + 'propertyIsEnumerable', + 'hasOwnProperty', + 'toLocaleString', +]; +var hasArgsEnumBug = /* @__PURE__ */ (function () { + 'use strict'; + return arguments.propertyIsEnumerable('length'); +})(); var contains = function contains2(list, item) { var idx = 0; while (idx < list.length) { @@ -891,37 +988,44 @@ var contains = function contains2(list, item) { } return false; }; -var keys = typeof Object.keys === "function" && !hasArgsEnumBug ? /* @__PURE__ */ _curry1(function keys2(obj) { - return Object(obj) !== obj ? [] : Object.keys(obj); -}) : /* @__PURE__ */ _curry1(function keys3(obj) { - if (Object(obj) !== obj) { - return []; - } - var prop, nIdx; - var ks = []; - var checkArgsLength = hasArgsEnumBug && isArguments_default(obj); - for (prop in obj) { - if (_has(prop, obj) && (!checkArgsLength || prop !== "length")) { - ks[ks.length] = prop; - } - } - if (hasEnumBug) { - nIdx = nonEnumerableProps.length - 1; - while (nIdx >= 0) { - prop = nonEnumerableProps[nIdx]; - if (_has(prop, obj) && !contains(ks, prop)) { - ks[ks.length] = prop; - } - nIdx -= 1; - } - } - return ks; -}); +var keys = + typeof Object.keys === 'function' && !hasArgsEnumBug + ? /* @__PURE__ */ _curry1(function keys2(obj) { + return Object(obj) !== obj ? [] : Object.keys(obj); + }) + : /* @__PURE__ */ _curry1(function keys3(obj) { + if (Object(obj) !== obj) { + return []; + } + var prop, nIdx; + var ks = []; + var checkArgsLength = hasArgsEnumBug && isArguments_default(obj); + for (prop in obj) { + if (_has(prop, obj) && (!checkArgsLength || prop !== 'length')) { + ks[ks.length] = prop; + } + } + if (hasEnumBug) { + nIdx = nonEnumerableProps.length - 1; + while (nIdx >= 0) { + prop = nonEnumerableProps[nIdx]; + if (_has(prop, obj) && !contains(ks, prop)) { + ks[ks.length] = prop; + } + nIdx -= 1; + } + } + return ks; + }); var keys_default = keys; // node_modules/ramda/es/type.js var type = /* @__PURE__ */ _curry1(function type2(val) { - return val === null ? "Null" : val === void 0 ? "Undefined" : Object.prototype.toString.call(val).slice(8, -1); + return val === null + ? 'Null' + : val === void 0 + ? 'Undefined' + : Object.prototype.toString.call(val).slice(8, -1); }); var type_default = type; @@ -949,20 +1053,20 @@ function _arrayReduce(reducer, acc, list) { } // node_modules/ramda/es/internal/_xmap.js -var XMap = /* @__PURE__ */ function() { +var XMap = /* @__PURE__ */ (function () { function XMap2(f, xf) { this.xf = xf; this.f = f; } - XMap2.prototype["@@transducer/init"] = xfBase_default.init; - XMap2.prototype["@@transducer/result"] = xfBase_default.result; - XMap2.prototype["@@transducer/step"] = function(result, input) { - return this.xf["@@transducer/step"](result, this.f(input)); + XMap2.prototype['@@transducer/init'] = xfBase_default.init; + XMap2.prototype['@@transducer/result'] = xfBase_default.result; + XMap2.prototype['@@transducer/step'] = function (result, input) { + return this.xf['@@transducer/step'](result, this.f(input)); }; return XMap2; -}(); +})(); var _xmap = function _xmap2(f) { - return function(xf) { + return function (xf) { return new XMap(f, xf); }; }; @@ -970,32 +1074,42 @@ var xmap_default = _xmap; // node_modules/ramda/es/map.js var map = /* @__PURE__ */ _curry2( - /* @__PURE__ */ _dispatchable(["fantasy-land/map", "map"], xmap_default, function map2(fn, functor) { - switch (Object.prototype.toString.call(functor)) { - case "[object Function]": - return curryN_default(functor.length, function() { - return fn.call(this, functor.apply(this, arguments)); - }); - case "[object Object]": - return _arrayReduce(function(acc, key) { - acc[key] = fn(functor[key]); - return acc; - }, {}, keys_default(functor)); - default: - return _map(fn, functor); - } - }) + /* @__PURE__ */ _dispatchable( + ['fantasy-land/map', 'map'], + xmap_default, + function map2(fn, functor) { + switch (Object.prototype.toString.call(functor)) { + case '[object Function]': + return curryN_default(functor.length, function () { + return fn.call(this, functor.apply(this, arguments)); + }); + case '[object Object]': + return _arrayReduce( + function (acc, key) { + acc[key] = fn(functor[key]); + return acc; + }, + {}, + keys_default(functor), + ); + default: + return _map(fn, functor); + } + }, + ), ); var map_default = map; // node_modules/ramda/es/internal/_isInteger.js -var isInteger_default = Number.isInteger || function _isInteger(n) { - return n << 0 === n; -}; +var isInteger_default = + Number.isInteger || + function _isInteger(n) { + return n << 0 === n; + }; // node_modules/ramda/es/internal/_isString.js function _isString(x) { - return Object.prototype.toString.call(x) === "[object String]"; + return Object.prototype.toString.call(x) === '[object String]'; } // node_modules/ramda/es/nth.js @@ -1013,7 +1127,7 @@ var _isArrayLike = /* @__PURE__ */ _curry1(function isArrayLike(x) { if (!x) { return false; } - if (typeof x !== "object") { + if (typeof x !== 'object') { return false; } if (_isString(x)) { @@ -1030,7 +1144,8 @@ var _isArrayLike = /* @__PURE__ */ _curry1(function isArrayLike(x) { var isArrayLike_default = _isArrayLike; // node_modules/ramda/es/internal/_createReduce.js -var symIterator = typeof Symbol !== "undefined" ? Symbol.iterator : "@@iterator"; +var symIterator = + typeof Symbol !== 'undefined' ? Symbol.iterator : '@@iterator'; function _createReduce(arrayReduce, methodReduce, iterableReduce) { return function _reduce(xf, acc, list) { if (isArrayLike_default(list)) { @@ -1039,19 +1154,19 @@ function _createReduce(arrayReduce, methodReduce, iterableReduce) { if (list == null) { return acc; } - if (typeof list["fantasy-land/reduce"] === "function") { - return methodReduce(xf, acc, list, "fantasy-land/reduce"); + if (typeof list['fantasy-land/reduce'] === 'function') { + return methodReduce(xf, acc, list, 'fantasy-land/reduce'); } if (list[symIterator] != null) { return iterableReduce(xf, acc, list[symIterator]()); } - if (typeof list.next === "function") { + if (typeof list.next === 'function') { return iterableReduce(xf, acc, list); } - if (typeof list.reduce === "function") { - return methodReduce(xf, acc, list, "reduce"); + if (typeof list.reduce === 'function') { + return methodReduce(xf, acc, list, 'reduce'); } - throw new TypeError("reduce: list must be array or iterable"); + throw new TypeError('reduce: list must be array or iterable'); }; } @@ -1060,19 +1175,19 @@ function _xArrayReduce(xf, acc, list) { var idx = 0; var len = list.length; while (idx < len) { - acc = xf["@@transducer/step"](acc, list[idx]); - if (acc && acc["@@transducer/reduced"]) { - acc = acc["@@transducer/value"]; + acc = xf['@@transducer/step'](acc, list[idx]); + if (acc && acc['@@transducer/reduced']) { + acc = acc['@@transducer/value']; break; } idx += 1; } - return xf["@@transducer/result"](acc); + return xf['@@transducer/result'](acc); } // node_modules/ramda/es/bind.js var bind = /* @__PURE__ */ _curry2(function bind2(fn, thisObj) { - return _arity(fn.length, function() { + return _arity(fn.length, function () { return fn.apply(thisObj, arguments); }); }); @@ -1082,50 +1197,56 @@ var bind_default = bind; function _xIterableReduce(xf, acc, iter) { var step = iter.next(); while (!step.done) { - acc = xf["@@transducer/step"](acc, step.value); - if (acc && acc["@@transducer/reduced"]) { - acc = acc["@@transducer/value"]; + acc = xf['@@transducer/step'](acc, step.value); + if (acc && acc['@@transducer/reduced']) { + acc = acc['@@transducer/value']; break; } step = iter.next(); } - return xf["@@transducer/result"](acc); + return xf['@@transducer/result'](acc); } function _xMethodReduce(xf, acc, obj, methodName) { - return xf["@@transducer/result"](obj[methodName](bind_default(xf["@@transducer/step"], xf), acc)); + return xf['@@transducer/result']( + obj[methodName](bind_default(xf['@@transducer/step'], xf), acc), + ); } -var _xReduce = /* @__PURE__ */ _createReduce(_xArrayReduce, _xMethodReduce, _xIterableReduce); +var _xReduce = /* @__PURE__ */ _createReduce( + _xArrayReduce, + _xMethodReduce, + _xIterableReduce, +); var xReduce_default = _xReduce; // node_modules/ramda/es/internal/_xwrap.js -var XWrap = /* @__PURE__ */ function() { +var XWrap = /* @__PURE__ */ (function () { function XWrap2(fn) { this.f = fn; } - XWrap2.prototype["@@transducer/init"] = function() { - throw new Error("init not implemented on XWrap"); + XWrap2.prototype['@@transducer/init'] = function () { + throw new Error('init not implemented on XWrap'); }; - XWrap2.prototype["@@transducer/result"] = function(acc) { + XWrap2.prototype['@@transducer/result'] = function (acc) { return acc; }; - XWrap2.prototype["@@transducer/step"] = function(acc, x) { + XWrap2.prototype['@@transducer/step'] = function (acc, x) { return this.f(acc, x); }; return XWrap2; -}(); +})(); function _xwrap(fn) { return new XWrap(fn); } // node_modules/ramda/es/reduce.js -var reduce = /* @__PURE__ */ _curry3(function(xf, acc, list) { - return xReduce_default(typeof xf === "function" ? _xwrap(xf) : xf, acc, list); +var reduce = /* @__PURE__ */ _curry3(function (xf, acc, list) { + return xReduce_default(typeof xf === 'function' ? _xwrap(xf) : xf, acc, list); }); var reduce_default = reduce; // node_modules/ramda/es/always.js var always = /* @__PURE__ */ _curry1(function always2(val) { - return function() { + return function () { return val; }; }); @@ -1173,7 +1294,12 @@ var assocPath = /* @__PURE__ */ _curry3(function assocPath2(path3, val, obj) { } var idx = path3[0]; if (path3.length > 1) { - var nextObj = !isNil_default(obj) && _has(idx, obj) && typeof obj[idx] === "object" ? obj[idx] : isInteger_default(path3[1]) ? [] : {}; + var nextObj = + !isNil_default(obj) && _has(idx, obj) && typeof obj[idx] === 'object' + ? obj[idx] + : isInteger_default(path3[1]) + ? [] + : {}; val = assocPath2(Array.prototype.slice.call(path3, 1), val, nextObj); } return _assoc(idx, val, obj); @@ -1188,7 +1314,17 @@ var assoc_default = assoc; // node_modules/ramda/es/internal/_cloneRegExp.js function _cloneRegExp(pattern) { - return new RegExp(pattern.source, pattern.flags ? pattern.flags : (pattern.global ? "g" : "") + (pattern.ignoreCase ? "i" : "") + (pattern.multiline ? "m" : "") + (pattern.sticky ? "y" : "") + (pattern.unicode ? "u" : "") + (pattern.dotAll ? "s" : "")); + return new RegExp( + pattern.source, + pattern.flags + ? pattern.flags + : (pattern.global ? 'g' : '') + + (pattern.ignoreCase ? 'i' : '') + + (pattern.multiline ? 'm' : '') + + (pattern.sticky ? 'y' : '') + + (pattern.unicode ? 'u' : '') + + (pattern.dotAll ? 's' : ''), + ); } // node_modules/ramda/es/internal/_clone.js @@ -1211,25 +1347,25 @@ function _clone(value, deep, map3) { return copiedValue; }; switch (type_default(value)) { - case "Object": + case 'Object': return copy(Object.create(Object.getPrototypeOf(value))); - case "Array": + case 'Array': return copy([]); - case "Date": + case 'Date': return new Date(value.valueOf()); - case "RegExp": + case 'RegExp': return _cloneRegExp(value); - case "Int8Array": - case "Uint8Array": - case "Uint8ClampedArray": - case "Int16Array": - case "Uint16Array": - case "Int32Array": - case "Uint32Array": - case "Float32Array": - case "Float64Array": - case "BigInt64Array": - case "BigUint64Array": + case 'Int8Array': + case 'Uint8Array': + case 'Uint8ClampedArray': + case 'Int16Array': + case 'Uint16Array': + case 'Int32Array': + case 'Uint32Array': + case 'Float32Array': + case 'Float64Array': + case 'BigInt64Array': + case 'BigUint64Array': return value.slice(); default: return value; @@ -1237,14 +1373,14 @@ function _clone(value, deep, map3) { } function _isPrimitive(param) { var type3 = typeof param; - return param == null || type3 != "object" && type3 != "function"; + return param == null || (type3 != 'object' && type3 != 'function'); } -var _ObjectMap = /* @__PURE__ */ function() { +var _ObjectMap = /* @__PURE__ */ (function () { function _ObjectMap2() { this.map = {}; this.length = 0; } - _ObjectMap2.prototype.set = function(key, value) { + _ObjectMap2.prototype.set = function (key, value) { const hashedKey = this.hash(key); let bucket = this.map[hashedKey]; if (!bucket) { @@ -1253,14 +1389,14 @@ var _ObjectMap = /* @__PURE__ */ function() { bucket.push([key, value]); this.length += 1; }; - _ObjectMap2.prototype.hash = function(key) { + _ObjectMap2.prototype.hash = function (key) { let hashedKey = []; for (var value in key) { hashedKey.push(Object.prototype.toString.call(key[value])); } return hashedKey.join(); }; - _ObjectMap2.prototype.get = function(key) { + _ObjectMap2.prototype.get = function (key) { if (this.length <= 180) { for (const p in this.map) { const bucket2 = this.map[p]; @@ -1286,11 +1422,13 @@ var _ObjectMap = /* @__PURE__ */ function() { } }; return _ObjectMap2; -}(); +})(); // node_modules/ramda/es/clone.js var clone = /* @__PURE__ */ _curry1(function clone2(value) { - return value != null && typeof value.clone === "function" ? value.clone() : _clone(value, true); + return value != null && typeof value.clone === 'function' + ? value.clone() + : _clone(value, true); }); var clone_default = clone; @@ -1302,58 +1440,71 @@ var not_default = not; // node_modules/ramda/es/internal/_pipe.js function _pipe(f, g) { - return function() { + return function () { return g.call(this, f.apply(this, arguments)); }; } // node_modules/ramda/es/internal/_checkForMethod.js function _checkForMethod(methodname, fn) { - return function() { + return function () { var length = arguments.length; if (length === 0) { return fn(); } var obj = arguments[length - 1]; - return isArray_default(obj) || typeof obj[methodname] !== "function" ? fn.apply(this, arguments) : obj[methodname].apply(obj, Array.prototype.slice.call(arguments, 0, length - 1)); + return isArray_default(obj) || typeof obj[methodname] !== 'function' + ? fn.apply(this, arguments) + : obj[methodname].apply( + obj, + Array.prototype.slice.call(arguments, 0, length - 1), + ); }; } // node_modules/ramda/es/slice.js var slice = /* @__PURE__ */ _curry3( - /* @__PURE__ */ _checkForMethod("slice", function slice2(fromIndex, toIndex, list) { - return Array.prototype.slice.call(list, fromIndex, toIndex); - }) + /* @__PURE__ */ _checkForMethod( + 'slice', + function slice2(fromIndex, toIndex, list) { + return Array.prototype.slice.call(list, fromIndex, toIndex); + }, + ), ); var slice_default = slice; // node_modules/ramda/es/tail.js var tail = /* @__PURE__ */ _curry1( /* @__PURE__ */ _checkForMethod( - "tail", - /* @__PURE__ */ slice_default(1, Infinity) - ) + 'tail', + /* @__PURE__ */ slice_default(1, Infinity), + ), ); var tail_default = tail; // node_modules/ramda/es/pipe.js function pipe() { if (arguments.length === 0) { - throw new Error("pipe requires at least one argument"); + throw new Error('pipe requires at least one argument'); } - return _arity(arguments[0].length, reduce_default(_pipe, arguments[0], tail_default(arguments))); + return _arity( + arguments[0].length, + reduce_default(_pipe, arguments[0], tail_default(arguments)), + ); } // node_modules/ramda/es/reverse.js var reverse = /* @__PURE__ */ _curry1(function reverse2(list) { - return _isString(list) ? list.split("").reverse().join("") : Array.prototype.slice.call(list, 0).reverse(); + return _isString(list) + ? list.split('').reverse().join('') + : Array.prototype.slice.call(list, 0).reverse(); }); var reverse_default = reverse; // node_modules/ramda/es/compose.js function compose() { if (arguments.length === 0) { - throw new Error("compose requires at least one argument"); + throw new Error('compose requires at least one argument'); } return pipe.apply(this, reverse_default(arguments)); } @@ -1427,7 +1578,7 @@ var dissoc_default = dissoc; // node_modules/ramda/es/internal/_objectAssign.js function _objectAssign(target) { if (target == null) { - throw new TypeError("Cannot convert undefined or null to object"); + throw new TypeError('Cannot convert undefined or null to object'); } var output = Object(target); var idx = 1; @@ -1445,15 +1596,19 @@ function _objectAssign(target) { } return output; } -var objectAssign_default = typeof Object.assign === "function" ? Object.assign : _objectAssign; +var objectAssign_default = + typeof Object.assign === 'function' ? Object.assign : _objectAssign; // node_modules/ramda/es/lens.js var lens = /* @__PURE__ */ _curry2(function lens2(getter, setter) { - return function(toFunctorFn) { - return function(target) { - return map_default(function(focus) { - return setter(focus, target); - }, toFunctorFn(getter(target))); + return function (toFunctorFn) { + return function (target) { + return map_default( + function (focus) { + return setter(focus, target); + }, + toFunctorFn(getter(target)), + ); }; }; }); @@ -1461,7 +1616,7 @@ var lens_default = lens; // node_modules/ramda/es/paths.js var paths = /* @__PURE__ */ _curry2(function paths2(pathsArray, obj) { - return pathsArray.map(function(paths3) { + return pathsArray.map(function (paths3) { var val = obj; var idx = 0; var p; @@ -1492,10 +1647,14 @@ var lensPath_default = lensPath; // node_modules/ramda/es/mapObjIndexed.js var mapObjIndexed = /* @__PURE__ */ _curry2(function mapObjIndexed2(fn, obj) { - return _arrayReduce(function(acc, key) { - acc[key] = fn(obj[key], key, obj); - return acc; - }, {}, keys_default(obj)); + return _arrayReduce( + function (acc, key) { + acc[key] = fn(obj[key], key, obj); + return acc; + }, + {}, + keys_default(obj), + ); }); var mapObjIndexed_default = mapObjIndexed; @@ -1510,16 +1669,16 @@ var mergeAll = /* @__PURE__ */ _curry1(function mergeAll2(list) { var mergeAll_default = mergeAll; // node_modules/ramda/es/over.js -var Identity = function(x) { +var Identity = function (x) { return { value: x, - map: function(f) { + map: function (f) { return Identity(f(x)); - } + }, }; }; var over = /* @__PURE__ */ _curry3(function over2(lens3, f, x) { - return lens3(function(y) { + return lens3(function (y) { return Identity(f(y)); })(x).value; }); @@ -1548,7 +1707,7 @@ function allocate(balances, reward2) { var total = reduce_default( add_default, 0, - values_default(balances).filter((v) => v > 0) + values_default(balances).filter((v) => v > 0), ); const allocation = mergeAll_default( reduce_default( @@ -1558,13 +1717,13 @@ function allocate(balances, reward2) { if (balance2 < 1) { return a; } - var pct = balance2 / total * 100; + var pct = (balance2 / total) * 100; const coins = Math.round(reward2 * (pct / 100)); return [...a, { [asset]: Number(coins) }]; }, [], - Object.entries(balances) - ) + Object.entries(balances), + ), ); var remainder = reward2 - sum_default(values_default(allocation)); var iterator = keys_default(allocation).entries(); @@ -1588,12 +1747,17 @@ function reward(state, vouched) { if (keys_default(state.streaks).length < 1) { return state; } - const { reward: reward2 } = setReward(Number(SmartWeave.block.height))({ state }); + const { reward: reward2 } = setReward(Number(SmartWeave.block.height))({ + state, + }); if (reward2 === 0) { return state; } state.streaks = keys_default(state.streaks).reduce((a, k) => { - if (state.streaks[k].lastHeight > Number(SmartWeave.block.height) - DAY * 2) { + if ( + state.streaks[k].lastHeight > + Number(SmartWeave.block.height) - DAY * 2 + ) { return { ...a, [k]: state.streaks[k] }; } return a; @@ -1644,7 +1808,7 @@ function setReward(height) { HALVING_SUPPLY, CYCLE_INTERVAL, height, - ORIGIN_HEIGHT + ORIGIN_HEIGHT, ); return { state, reward: reward2 }; }; @@ -1668,16 +1832,19 @@ function getReward(supply, interval, currentHeight, originHeight) { // src/write/cancel-claim.js var cancelClaim = async (state, action) => { - ContractAssert(action.input.contract, "contract is required"); - ContractAssert(action.input.transaction, "transaction is required"); - ContractAssert(action.input.qty, "transaction is required"); - ContractAssert(action.input.contract.length === 43, "contract is not valid"); - ContractAssert(action.input.transaction.length === 43, "transaction is not valid"); - ContractAssert(Number.isInteger(action.input.qty), "qty must be integer"); + ContractAssert(action.input.contract, 'contract is required'); + ContractAssert(action.input.transaction, 'transaction is required'); + ContractAssert(action.input.qty, 'transaction is required'); + ContractAssert(action.input.contract.length === 43, 'contract is not valid'); + ContractAssert( + action.input.transaction.length === 43, + 'transaction is not valid', + ); + ContractAssert(Number.isInteger(action.input.qty), 'qty must be integer'); await SmartWeave.contracts.write(action.input.contract, { - function: "reject", + function: 'reject', tx: action.input.transaction, - qty: action.input.qty + qty: action.input.qty, }); return { state }; }; @@ -1695,13 +1862,31 @@ function contributorMint(state, action) { contributor: action.caller, height: { origin: originHeight, - current: currentHeight - } - }).chain(getContributor).map(calcBlockDiff).map(calcRewardAmount).map(allocateForTier).map(allocateForMember).map(updateBalances2).map(setLastMint4Member); + current: currentHeight, + }, + }) + .chain(getContributor) + .map(calcBlockDiff) + .map(calcRewardAmount) + .map(allocateForTier) + .map(allocateForMember) + .map(updateBalances2) + .map(setLastMint4Member); } function setLastMint4Member(ctx) { - const lastMintPath = ["contributors", "tiers", ctx.contributor.tier.name, "members", ctx.contributor.addr, "lastMint"]; - ctx.state = set_default(lensPath_default(lastMintPath), ctx.height.current, ctx.state); + const lastMintPath = [ + 'contributors', + 'tiers', + ctx.contributor.tier.name, + 'members', + ctx.contributor.addr, + 'lastMint', + ]; + ctx.state = set_default( + lensPath_default(lastMintPath), + ctx.height.current, + ctx.state, + ); return { state: ctx.state }; } function updateBalances2(ctx) { @@ -1710,52 +1895,72 @@ function updateBalances2(ctx) { state.balances[ctx.contributor.addr] = 0; } state.balances[ctx.contributor.addr] += ctx.rewardMember; - return assoc_default("state", state, ctx); + return assoc_default('state', state, ctx); } function allocateForMember(ctx) { - const members = ctx.state.contributors.tiers[ctx.contributor.tier.name].members; - const table = reduce_default((acc, [key, value]) => assoc_default(key, value.amount, acc), {}, toPairs_default(members)); + const members = + ctx.state.contributors.tiers[ctx.contributor.tier.name].members; + const table = reduce_default( + (acc, [key, value]) => assoc_default(key, value.amount, acc), + {}, + toPairs_default(members), + ); const reward2 = allocate(table, ctx.rewardTier); - return assoc_default("rewardMember", reward2[ctx.contributor.addr], ctx); + return assoc_default('rewardMember', reward2[ctx.contributor.addr], ctx); } function allocateForTier(ctx) { const { contributor, reward: reward2 } = ctx; const rewardTier = Math.floor(reward2 * (contributor.tier.percent / 100)); - return assoc_default("rewardTier", rewardTier, ctx); + return assoc_default('rewardTier', rewardTier, ctx); } function calcRewardAmount(ctx) { const { height } = ctx; const reward2 = height.diff * REWARD_UNIT_PER_HEIGHT; - return assoc_default("reward", reward2, ctx); + return assoc_default('reward', reward2, ctx); } function calcBlockDiff(ctx) { const height = ctx.height; const contributor = ctx.contributor; - const start = contributor.lastMint === 0 ? height.origin : contributor.lastMint; + const start = + contributor.lastMint === 0 ? height.origin : contributor.lastMint; const diff = height.current - start; - return assoc_default("height", { ...height, diff }, ctx); + return assoc_default('height', { ...height, diff }, ctx); } function getContributor({ state, contributor, height }) { return compose( - (c) => c ? Right({ state, contributor: c, height }) : Left("could not find"), + (c) => + c ? Right({ state, contributor: c, height }) : Left('could not find'), head_default, map_default((m) => m[contributor]), (tiers) => { - const members = reduce_default((a, [tierName, tierValue]) => { - const o = mapObjIndexed_default((d, k) => { - return { ...d, tier: { name: tierName, percent: tierValue.percent }, addr: k }; - }, tierValue.members); - return a.concat(o); - }, [], toPairs_default(tiers)); + const members = reduce_default( + (a, [tierName, tierValue]) => { + const o = mapObjIndexed_default((d, k) => { + return { + ...d, + tier: { name: tierName, percent: tierValue.percent }, + addr: k, + }; + }, tierValue.members); + return a.concat(o); + }, + [], + toPairs_default(tiers), + ); return members; }, - path_default(["contributors", "tiers"]) + path_default(['contributors', 'tiers']), )(state); } // src/write/contributor-chg.js function contributorChg(state, action) { - return of({ state, action }).chain(validate6).map(cloneMembers).map(setTarget).map(dissocCaller).map(attachMembers); + return of({ state, action }) + .chain(validate6) + .map(cloneMembers) + .map(setTarget) + .map(dissocCaller) + .map(attachMembers); } function attachMembers(ctx) { ctx.state.contributors.tiers[ctx.tier].members = ctx.members; @@ -1770,27 +1975,35 @@ function setTarget(ctx) { return ctx; } function cloneMembers(ctx) { - return { ...ctx, members: clone_default(path_default(["contributors", "tiers", ctx.tier, "members"], ctx.state)) }; + return { + ...ctx, + members: clone_default( + path_default(['contributors', 'tiers', ctx.tier, 'members'], ctx.state), + ), + }; } function validate6({ state, action }) { if (not_default(action.input.tier)) { - return Left("Tier Input is required"); + return Left('Tier Input is required'); } if (not_default(action.input.target)) { - return Left("Target Input is required"); + return Left('Target Input is required'); } return Right({ state, caller: action.caller, tier: action.input.tier, - target: action.input.target + target: action.input.target, }); } // src/write/evolve.js var EVOLVE_WINDOW = 720 * 180; function evolve(state, action) { - if (state.canEvolve && Number(SmartWeave.block.height) < state.originHeight + EVOLVE_WINDOW) { + if ( + state.canEvolve && + Number(SmartWeave.block.height) < state.originHeight + EVOLVE_WINDOW + ) { if (SmartWeave.contract.owner === action.caller) { state.evolve = action.input.value; } @@ -1800,52 +2013,54 @@ function evolve(state, action) { // src/index.js var identity = (x) => x; -var VOUCH_DAO = "_z0ch80z_daDUFqC9jHjfOL8nekJcok4ZRkE_UesYsk"; +var VOUCH_DAO = '_z0ch80z_daDUFqC9jHjfOL8nekJcok4ZRkE_UesYsk'; export async function handle(state, action) { async function CreateOrderPlusBuyback(state2, action2) { const result = await CreateOrder(state2, action2); return result; } validate4(state); - if (action.input.function === "createOrder") { - const vouched = await SmartWeave.contracts.readContractState(VOUCH_DAO).then((s) => Object.keys(s.vouched)).catch((e) => []); + if (action.input.function === 'createOrder') { + const vouched = await SmartWeave.contracts + .readContractState(VOUCH_DAO) + .then((s) => Object.keys(s.vouched)) + .catch((e) => []); state = reward(state, vouched); } - if (action.input.function === "createOrder" && !action.input.price) { + if (action.input.function === 'createOrder' && !action.input.price) { state = await buyback(state); } switch (action?.input?.function) { - case "noop": + case 'noop': return { state }; - case "addPair": + case 'addPair': return addPair(state, action).extract(); - case "createOrder": + case 'createOrder': return CreateOrderPlusBuyback(state, action); - case "cancelOrder": + case 'cancelOrder': return CancelOrder(state, action); - case "cancelClaim": + case 'cancelClaim': return cancelClaim(state, action); - case "balance": + case 'balance': return balance(state, action); - case "transfer": + case 'transfer': return transfer(state, action).fold(handleError, identity); - case "allow": + case 'allow': return allow(state, action).fold(handleError, identity); - case "claim": + case 'claim': return claim(state, action).fold(handleError, identity); - case "contributorMint": + case 'contributorMint': return contributorMint(state, action).fold(handleError, identity); - case "contributorChg": + case 'contributorChg': return contributorChg(state, action).fold(handleError, identity); - case "evolve": + case 'evolve': return evolve(state, action); default: - throw new ContractError("No Function Found"); + throw new ContractError('No Function Found'); } } function handleError(msg) { throw new ContractError(msg); } - /* eslint-enable */ diff --git a/tests/utils/ucm/state.json b/tests/utils/ucm/state.json index a7604a1..927751f 100644 --- a/tests/utils/ucm/state.json +++ b/tests/utils/ucm/state.json @@ -1,3 +1,19 @@ +/** + * Copyright (C) 2022-2024 Permanent Data Solutions, Inc. All Rights Reserved. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ { "U": "KTzTXT_ANmF84fWEKHzWURD1LWd9QaFR9yfYUwH2Lxw", "name": "Universal Content Marketplace", @@ -6,12 +22,7 @@ "creator": "HYdkNJUPvMJOLEvk4eSJr9MgGZZXxLoHszwLe-PuSMM", "streaks": {}, "balances": {}, - "settings": [ - [ - "logo", - "BPw8MuhvLQjJ328KwqnHIdzTRLBj9dGgOUv0AgTiRAg" - ] - ], + "settings": [["logo", "BPw8MuhvLQjJ328KwqnHIdzTRLBj9dGgOUv0AgTiRAg"]], "canEvolve": true, "claimable": [], "lastReward": 0, @@ -92,4 +103,4 @@ "originHeight": 1232228, "transferable": true, "recentRewards": {} -} \ No newline at end of file +} diff --git a/tools/scripts/build-ucm.js b/tools/scripts/build-ucm.js index 1a28cdc..68a2335 100644 --- a/tools/scripts/build-ucm.js +++ b/tools/scripts/build-ucm.js @@ -52,7 +52,7 @@ const ajv = new Ajv({ claimSchema, rejectSchema, constructorSchema, - allowSchema + allowSchema, ], code: { source: true, esm: true }, }); @@ -67,32 +67,35 @@ const moduleCode = standaloneCode(ajv, { validateBalance: '#/definitions/balance', validateTransferTokens: '#/definitions/transfer', validateEvolve: '#/definitions/evolve', - validateClaim: '#/definitions/claim', - validateReject: '#/definitions/reject', - validateConstructor: '#/definitions/constructor', - validateAllow: '#/definitions/allow' + validateClaim: '#/definitions/claim', + validateReject: '#/definitions/reject', + validateConstructor: '#/definitions/constructor', + validateAllow: '#/definitions/allow', }); // Now you can write the module code to file -fs.writeFileSync(path.join(__dirname, '../../src/validations-ucm.js'), moduleCode); +fs.writeFileSync( + path.join(__dirname, '../../src/validations-ucm.js'), + moduleCode, +); build({ entryPoints: contracts.map((source) => { - return path.join(__dirname,`../../src/${source}`); + return path.join(__dirname, `../../src/${source}`); }), - outdir: path.join(__dirname,'../../dist'), + outdir: path.join(__dirname, '../../dist'), minify: false, bundle: true, format: 'iife', packages: 'external', - tsconfig: path.join(__dirname,'../../tsconfig.json'), + tsconfig: path.join(__dirname, '../../tsconfig.json'), }) .catch(() => process.exit(1)) // note: SmartWeave SDK currently does not support files in IIFE bundle format, so we need to remove the "iife" part ;-) // update: it does since 0.4.31, but because viewblock.io is still incompatibile with this version, leaving as is for now. .finally(() => { const files = contracts.map((source) => { - return path.join(__dirname,`.../../dist${source}`).replace('.ts', '.js'); + return path.join(__dirname, `.../../dist${source}`).replace('.ts', '.js'); }); replace.sync({ files: files,