Skip to content

Commit

Permalink
refactor!: rename gas to gasLimit where possible
Browse files Browse the repository at this point in the history
BREAKING CHANGE: `gas` renamed to `gasLimit`
Use `gasLimit` instead of `gas` everywhere except for transaction details returned by node.
  • Loading branch information
davidyuk committed Apr 8, 2022
1 parent b4b855f commit dece758
Show file tree
Hide file tree
Showing 15 changed files with 64 additions and 59 deletions.
6 changes: 3 additions & 3 deletions docs/transaction-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ The following options are sepcific for each tx-type.
- To be used for providing `aettos` (or `AE` with respective denomination) to a contract related transaction.
- `denomination` (default: `aettos`)
- You can specify the denomination of the `amount` that will be provided to the contract related transaction.
- `gas`
- Max. amount of gas to be consumed by the transaction. Learn more on [How to estimate gas?](#how-to-estimate-gas)
- `gasLimit`
- Maximum amount of gas to be consumed by the transaction. Learn more on [How to estimate gas?](#how-to-estimate-gas)
- `gasPrice` (default: `1e9`)
- To increase chances to get your transaction included quickly you can use a higher gasPrice.

Expand Down Expand Up @@ -91,4 +91,4 @@ The following options are sepcific for each tx-type.

## How to estimate gas?
- As æpp developer, it is reasonable to estimate the gas consumption for a contract call using the dry-run feature of the node **once** and provide a specific offset (e.g. multiplied by 1.5 or 2) as default in the æpp to ensure that contract calls are mined. Depending on the logic of the contract the gas consumption of a specific contract call can vary and therefore you should monitor the gas consumption and increase the default for the respective contract call accordingly over time.
- By default, SDK estimates `gas` using dry-run endpoint. This means an extra request that makes contract iterations slower, but it is more developer friendly (support of heavy requests without adjustments, and verbose error messages).
- By default, SDK estimates `gasLimit` using dry-run endpoint. This means an extra request that makes contract iterations slower, but it is more developer friendly (support of heavy requests without adjustments, and verbose error messages).
4 changes: 2 additions & 2 deletions examples/node/paying-for-tx-contract-call-tx.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ const NEW_USER_KEYPAIR = Crypto.generateKeyPair();
// - The `entrypoint` with the name `set_latest_caller` doesn't require any params so you
// can provide an empty array
// 1. Create the `ContractCreateTx` by providing all required params.
// - You could omit `amount`, `gas` and `gasPrice` if you choose to stick to the default
// - You could omit `amount`, `gasLimit` and `gasPrice` if you choose to stick to the default
// values (see
// [transaction options](../../../transaction-options#contractcreatetx-contractcalltx))
// 1. Sign the transaction by providing `innerTx: true` as transaction option.
Expand All @@ -142,7 +142,7 @@ const NEW_USER_KEYPAIR = Crypto.generateKeyPair();
callerId: await newUserAccount.address(),
contractId: CONTRACT_ADDRESS,
amount: 0,
gas: 1000000,
gasLimit: 1000000,
gasPrice: 1500000000,
callData: calldata
})
Expand Down
10 changes: 5 additions & 5 deletions src/channel/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,7 @@ function createContract ({ code, callData, deposit, vmVersion, abiVersion }, sig
* the result of the contract call.
*
* It is worth mentioning that the gas is not consumed, because this is an off-chain
* contract call. It would be consumed if it were a on-chain one. This could happen
* contract call. It would be consumed if it were an on-chain one. This could happen
* if a call with a similar computation amount is to be forced on-chain.
*
* @param {Object} options
Expand Down Expand Up @@ -580,8 +580,8 @@ function callContract ({ amount, callData, contract, abiVersion }, sign) {
* @param {String} [options.callData] - ABI encoded compiled AEVM call data for the code
* @param {Number} [options.contract] - Address of the contract to call
* @param {Number} [options.abiVersion] - Version of the ABI
* @param {Number} [options.gasPrice=1000000000] - Gas price
* @param {Number} [options.gas=1000000] - Gas limit
* @param {Number} [options.gasPrice=1000000000]
* @param {Number} [options.gasLimit=1000000]
* @param {Function} sign - Function which verifies and signs contract force progress transaction
* @param {{ onOnChainTxL: Function }} callbacks
* @return {Promise<Object>}
Expand All @@ -600,7 +600,7 @@ function callContract ({ amount, callData, contract, abiVersion }, sign) {
* })
*/
function forceProgress (
{ amount, callData, contract, abiVersion, gas = 1000000, gasPrice = 1000000000, nonce },
{ amount, callData, contract, abiVersion, gasLimit = 1000000, gasPrice = 1000000000, nonce },
sign,
{ onOnChainTx } = {}
) {
Expand All @@ -618,7 +618,7 @@ function forceProgress (
contract_id: contract,
abi_version: abiVersion,
gas_price: gasPrice,
gas
gas: gasLimit
}
})
return {
Expand Down
6 changes: 3 additions & 3 deletions src/contract/aci.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ export default async function getContractInstance ({
const ownerId = await this.address(opt)
const { tx, contractId } = await this.contractCreateTx({
...opt,
gas: opt.gas ?? await instance._estimateGas('init', params, opt),
gasLimit: opt.gasLimit ?? await instance._estimateGas('init', params, opt),
callData: instance.calldata.encode(instance._name, 'init', params),
code: instance.bytecode,
ownerId
Expand Down Expand Up @@ -250,7 +250,7 @@ export default async function getContractInstance ({
}
const txOpt = {
...opt,
gas: opt.gas ?? GAS_MAX,
gasLimit: opt.gasLimit ?? GAS_MAX,
callData,
nonce: opt.nonce ??
(opt.top && (await this.getAccount(callerId, { hash: opt.top })).nonce + 1)
Expand All @@ -265,7 +265,7 @@ export default async function getContractInstance ({
} else {
const tx = await this.contractCallTx({
...opt,
gas: opt.gas ?? await instance._estimateGas(fn, params, opt),
gasLimit: opt.gasLimit ?? await instance._estimateGas(fn, params, opt),
callerId,
contractId,
callData
Expand Down
10 changes: 6 additions & 4 deletions src/contract/ga/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,18 @@ import { InvalidAuthDataError } from '../../utils/errors'

export const prepareGaParams = (ins) => async (authData, authFnName) => {
if (typeof authData !== 'object') throw new InvalidAuthDataError('AuthData must be an object')
if (authData.gas && BigNumber(authData.gas).gt(MAX_AUTH_FUN_GAS)) { throw new InvalidAuthDataError(`the maximum gas value for ga authFun is ${MAX_AUTH_FUN_GAS}, got ${authData.gas}`) }
const gas = authData.gas || MAX_AUTH_FUN_GAS
const gasLimit = authData.gasLimit ?? MAX_AUTH_FUN_GAS
if (new BigNumber(gasLimit).gt(MAX_AUTH_FUN_GAS)) {
throw new InvalidAuthDataError(`the maximum gasLimit value for ga authFun is ${MAX_AUTH_FUN_GAS}, got ${gasLimit}`)
}
if (authData.callData) {
if (authData.callData.split('_')[0] !== 'cb') throw new InvalidAuthDataError('Auth data must be a string with "cb" prefix.')
return { authCallData: authData.callData, gas }
return { authCallData: authData.callData, gasLimit }
}
if (!authData.source || !authData.args) throw new InvalidAuthDataError('Auth data must contain source code and arguments.')
const contract = await ins.getContractInstance({ source: authData.source })
return {
authCallData: contract.calldata.encode(contract._name, authFnName, authData.args),
gas
gasLimit
}
}
6 changes: 3 additions & 3 deletions src/contract/ga/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ async function createGeneralizedAccount (authFnName, source, args = [], options
await contract.compile()
const { tx, contractId } = await this.gaAttachTx({
...opt,
gas: opt.gas ?? await contract._estimateGas('init', args, opt),
gasLimit: opt.gasLimit ?? await contract._estimateGas('init', args, opt),
ownerId,
code: contract.bytecode,
callData: contract.calldata.encode(contract._name, 'init', args),
Expand Down Expand Up @@ -124,7 +124,7 @@ const wrapInEmptySignedTx = (tx) => buildTx({ encodedTx: tx, signatures: [] }, T
async function createMetaTx (rawTransaction, authData, authFnName, options = {}) {
if (!authData) throw new MissingParamError('authData is required')
// Check if authData is callData or if it's an object prepare a callData from source and args
const { authCallData, gas } = await prepareGaParams(this)(authData, authFnName)
const { authCallData, gasLimit } = await prepareGaParams(this)(authData, authFnName)
const opt = { ...this.Ae.defaults, ...options }
const { abiVersion } = await this.getVmVersion(TX_TYPE.contractCall)
const wrappedTx = wrapInEmptySignedTx(unpackTx(rawTransaction))
Expand All @@ -137,7 +137,7 @@ async function createMetaTx (rawTransaction, authData, authFnName, options = {})
gaId: await this.address(opt),
abiVersion,
authData: authCallData,
gas,
gasLimit,
vsn: 2
}
const { fee } = await this.prepareTxParams(TX_TYPE.gaMeta, params)
Expand Down
29 changes: 16 additions & 13 deletions src/tx/builder/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -229,23 +229,25 @@ function getOracleRelativeTtl (params, txType) {
* Calculate min fee
* @function
* @alias module:@aeternity/aepp-sdk/es/tx/builder/index
* @rtype (txType, { gas = 0, params }) => String
* @rtype (txType, { gasLimit = 0, params }) => String
* @param {String} txType - Transaction type
* @param {Options} options - Options object
* @param {String|Number} options.gas - Gas amount
* @param {String|Number} options.gasLimit
* @param {Object} options.params - Tx params
* @return {String|Number}
* @example calculateMinFee('spendTx', { gas, params })
* @example calculateMinFee('spendTx', { gasLimit, params })
*/
export function calculateMinFee (txType, { gas = 0, params, vsn }) {
export function calculateMinFee (txType, { gasLimit = 0, params, vsn }) {
const multiplier = BigNumber(1e9) // 10^9 GAS_PRICE
if (!params) return BigNumber(DEFAULT_FEE).times(multiplier).toString(10)

let actualFee = buildFee(txType, { params: { ...params, fee: 0 }, multiplier, gas, vsn })
let actualFee = buildFee(txType, { params: { ...params, fee: 0 }, multiplier, gasLimit, vsn })
let expected = BigNumber(0)

while (!actualFee.eq(expected)) {
actualFee = buildFee(txType, { params: { ...params, fee: actualFee }, multiplier, gas, vsn })
actualFee = buildFee(txType, {
params: { ...params, fee: actualFee }, multiplier, gasLimit, vsn
})
expected = actualFee
}
return expected.toString(10)
Expand All @@ -255,12 +257,11 @@ export function calculateMinFee (txType, { gas = 0, params, vsn }) {
* Calculate fee based on tx type and params
* @param txType
* @param params
* @param gas
* @param multiplier
* @param vsn
* @return {BigNumber}
*/
function buildFee (txType, { params, gas = 0, multiplier, vsn }) {
function buildFee (txType, { params, multiplier, vsn }) {
const { rlpEncoded: txWithOutFee } = buildTx({ ...params }, txType, { vsn })
const txSize = txWithOutFee.length
return TX_FEE_BASE_GAS(txType)
Expand All @@ -277,19 +278,21 @@ function buildFee (txType, { params, gas = 0, multiplier, vsn }) {
* Calculate fee
* @function
* @alias module:@aeternity/aepp-sdk/es/tx/builder
* @rtype (fee, txType, gas = 0) => String
* @rtype (fee, txType, gasLimit = 0) => String
* @param {String|Number} fee - fee
* @param {String} txType - Transaction type
* @param {Options} options - Options object
* @param {String|Number} options.gas - Gas amount
* @param {String|Number} options.gasLimit
* @param {Object} options.params - Tx params
* @return {String|Number}
* @example calculateFee(null, 'spendTx', { gas, params })
* @example calculateFee(null, 'spendTx', { gasLimit, params })
*/
export function calculateFee (fee = 0, txType, { gas = 0, params, showWarning = true, vsn } = {}) {
export function calculateFee (
fee = 0, txType, { gasLimit = 0, params, showWarning = true, vsn } = {}
) {
if (!params && showWarning) console.warn(`Can't build transaction fee, we will use DEFAULT_FEE(${DEFAULT_FEE})`)

return fee || calculateMinFee(txType, { params, gas, vsn })
return fee || calculateMinFee(txType, { params, gasLimit, vsn })
}

/**
Expand Down
8 changes: 4 additions & 4 deletions src/tx/builder/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -433,7 +433,7 @@ const GA_ATTACH_TX = [
TX_FIELD('ctVersion', FIELD_TYPES.ctVersion),
TX_FIELD('fee', FIELD_TYPES.int),
TX_FIELD('ttl', FIELD_TYPES.int),
TX_FIELD('gas', FIELD_TYPES.int),
TX_FIELD('gasLimit', FIELD_TYPES.int),
TX_FIELD('gasPrice', FIELD_TYPES.int),
TX_FIELD('callData', FIELD_TYPES.binary, 'cb')
]
Expand All @@ -444,7 +444,7 @@ const GA_META_TX_2 = [
TX_FIELD('authData', FIELD_TYPES.binary, 'cb'),
TX_FIELD('abiVersion', FIELD_TYPES.int),
TX_FIELD('fee', FIELD_TYPES.int),
TX_FIELD('gas', FIELD_TYPES.int),
TX_FIELD('gasLimit', FIELD_TYPES.int),
TX_FIELD('gasPrice', FIELD_TYPES.int),
TX_FIELD('tx', FIELD_TYPES.rlpBinary)
]
Expand All @@ -467,7 +467,7 @@ const CONTRACT_CREATE_TX = [
TX_FIELD('ttl', FIELD_TYPES.int),
TX_FIELD('deposit', Deposit),
TX_FIELD('amount', FIELD_TYPES.amount),
TX_FIELD('gas', FIELD_TYPES.int),
TX_FIELD('gasLimit', FIELD_TYPES.int),
TX_FIELD('gasPrice', FIELD_TYPES.int),
TX_FIELD('callData', FIELD_TYPES.binary, 'cb')
]
Expand All @@ -481,7 +481,7 @@ const CONTRACT_CALL_TX = [
TX_FIELD('fee', FIELD_TYPES.int),
TX_FIELD('ttl', FIELD_TYPES.int),
TX_FIELD('amount', FIELD_TYPES.amount),
TX_FIELD('gas', FIELD_TYPES.int),
TX_FIELD('gasLimit', FIELD_TYPES.int),
TX_FIELD('gasPrice', FIELD_TYPES.int),
TX_FIELD('callData', FIELD_TYPES.binary, 'cb')
]
Expand Down
4 changes: 2 additions & 2 deletions src/tx/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ const Tx = stampit(required({
* vmVersion: Number,
* deposit: Number,
* amount: Number,
* gas: Number,
* gasLimit: Number,
* gasPrice: Number,
* fee?: Number,
* ttl?: Number,
Expand All @@ -197,7 +197,7 @@ const Tx = stampit(required({
* callData: String,
* vmVersion: Number,
* amount: Number,
* gas: Number,
* gasLimit: Number,
* gasPrice: Number,
* fee?: Number,
* ttl?: Number,
Expand Down
4 changes: 2 additions & 2 deletions src/tx/tx-object.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { InvalidTxError, TypeError, UnknownTxError, InvalidSignatureError } from
const buildTransaction = (type, params, options = {}) => {
if (typeof params !== 'object') throw new TypeError('tx "params" should be an object')
if (typeof type !== 'string' || !Object.values(TX_TYPE).includes(type)) throw new UnknownTxError(`Unknown transaction type ${type}`)
const fee = calculateFee(params.fee, type, { gas: params.gas, params, vsn: params.vsn })
const fee = calculateFee(params.fee, type, { gasLimit: params.gasLimit, params, vsn: params.vsn })
const { rlpEncoded, binary, tx: encodedTx, txObject } = buildTx(
{ ...params, fee }, type, { vsn: params.vsn, ...options }
)
Expand Down Expand Up @@ -179,7 +179,7 @@ export const TxObject = stampit({
*/
calculateMinFee (props = {}) {
const params = { ...this.params, ...props }
return calculateFee(0, this.type, { gas: params.gas, params, vsn: params.vsn })
return calculateFee(0, this.type, { gasLimit: params.gasLimit, params, vsn: params.vsn })
}
}
})
Expand Down
14 changes: 7 additions & 7 deletions src/tx/tx.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ async function nameRevokeTx ({ accountId, nameId }) {
}

async function contractCreateTx ({
ownerId, code, vmVersion, abiVersion, amount, gas, gasPrice = MIN_GAS_PRICE, callData
ownerId, code, vmVersion, abiVersion, amount, gasLimit, gasPrice = MIN_GAS_PRICE, callData
}) {
// Get VM_ABI version
const ctVersion = this.getVmVersion(TX_TYPE.contractCreate, arguments[0])
Expand All @@ -192,15 +192,15 @@ async function contractCreateTx ({
nonce,
ttl,
fee: parseInt(fee),
gas: parseInt(gas),
gas: parseInt(gasLimit),
gasPrice,
vmVersion: ctVersion.vmVersion,
abiVersion: ctVersion.abiVersion
})
}

async function contractCallTx ({
callerId, contractId, abiVersion, amount, gas, gasPrice = MIN_GAS_PRICE, callData
callerId, contractId, abiVersion, amount, gasLimit, gasPrice = MIN_GAS_PRICE, callData
}) {
const ctVersion = this.getVmVersion(TX_TYPE.contractCall, arguments[0])
// Calculate fee, get absolute ttl (ttl + height), get account nonce
Expand All @@ -222,7 +222,7 @@ async function contractCallTx ({
nonce,
ttl,
fee: parseInt(fee),
gas: parseInt(gas),
gas: parseInt(gasLimit),
gasPrice,
abiVersion: ctVersion.abiVersion
})
Expand Down Expand Up @@ -466,7 +466,7 @@ async function channelSnapshotSoloTx ({ channelId, fromId, payload }) {
}

async function gaAttachTx ({
ownerId, code, vmVersion, abiVersion, authFun, gas, gasPrice = MIN_GAS_PRICE, callData
ownerId, code, vmVersion, abiVersion, authFun, gasLimit, gasPrice = MIN_GAS_PRICE, callData
}) {
// Get VM_ABI version
const ctVersion = this.getVmVersion(TX_TYPE.contractCreate, arguments[0])
Expand Down Expand Up @@ -559,7 +559,7 @@ async function getAccountNonce (accountId, nonce) {
*/
async function prepareTxParams (
txType,
{ senderId, nonce: n, ttl: t, fee: f, gas, absoluteTtl, vsn, strategy }
{ senderId, nonce: n, ttl: t, fee: f, gasLimit, absoluteTtl, vsn, strategy }
) {
n = n || (
await this.api.getAccountNextNonce(senderId, { strategy }).catch(e => ({ nextNonce: 1 }))
Expand All @@ -568,7 +568,7 @@ async function prepareTxParams (
const fee = calculateFee(
f,
txType,
{ showWarning: this.showWarning, gas, params: { ...arguments[1], nonce: n, ttl }, vsn }
{ showWarning: this.showWarning, gasLimit, params: { ...arguments[1], nonce: n, ttl }, vsn }
)
return { fee, ttl, nonce: n }
}
Expand Down
2 changes: 1 addition & 1 deletion src/tx/validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const validators = [
(tx, { txType }) => {
if (tx.fee === undefined) return []
const minFee = calculateFee(0, txType, {
gas: +tx.gas || 0, params: tx, showWarning: false, vsn: tx.VSN
gasLimit: +tx.gasLimit || 0, params: tx, showWarning: false, vsn: tx.VSN
})
if (new BigNumber(minFee).lte(tx.fee)) return []
return [{
Expand Down
4 changes: 2 additions & 2 deletions test/integration/chain.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,13 +151,13 @@ describe('Node Chain', function () {
' entrypoint foo(x : int) = x * 100'
})
await contract.deploy()
const { result: { gasUsed: gas } } = await contract.methods.foo(5)
const { result: { gasUsed: gasLimit } } = await contract.methods.foo(5)
const { nextNonce } = await aeSdk.api.getAccountNextNonce(await aeSdk.address())
spy(http, 'request')
const numbers = new Array(32).fill().map((v, idx) => idx * 2)
const results = (await Promise.all(
numbers.map((v, idx) => contract.methods
.foo(v, { nonce: nextNonce + idx, gas, combine: true }))
.foo(v, { nonce: nextNonce + idx, gasLimit, combine: true }))
)).map(r => r.decodedResult)
expect(results).to.be.eql(numbers.map(v => BigInt(v * 100)))
expect(http.request.args.length).to.be.equal(1)
Expand Down
Loading

0 comments on commit dece758

Please sign in to comment.