Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added assets/108_1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/108_2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/108_3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
198 changes: 198 additions & 0 deletions fatips/108.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
| FATIP | Title | Status | Category | Author | Created |
| ----- | -------------------------- | -------- | -------- | ------------------------------------------ | ---------- |
| 108 | Gas System | WIP | Core | Sergey Bushnyak \<sergey@kompendium.co\> | 2020-02-02 |

# Gas System

## Summary
FATIP-108 defines a FAT gas system: its basic units, dynamic gas functions, and the specifications governing their use. The gas system increases the overall health of the network by improving security; discouraging network spam; and incentivizing the deployment and rapid processing of transactions, smart contracts, and contract calls within the FAT ecosystem.

## Motivation

A well-functioning smart contract system requires contract security and processing mechanisms to ensure proper and valid contract deployment and execution. The introduction of a FAT gas system will support these needs via: discouraging network spam, incentivizing swift contract execution, and further securing the network.

Every FAT-based transaction requires network computational resources for execution and Factom Entry Credit (EC) tokens to write the execution result onto the Factom Blockchain. FATIP-108’s gas system compensates—through the provision of a fee—use of FAT-network computational resources and the cost of recording the transaction on the Factom Blockchain.

To discourage accidental or hostile infinite loops or other computational wastage in code (network spam), the proposed gas system has a progressive cost structure where network spamming becomes evermore increasingly expensive. As an additional measure in this effort, each FAT smart contract transaction will be required to set a limit to the number of computational and in-memory steps a contract’s execution logic can use.

The FATIP gas system uses two units: Factom Entry Credits (EC) are used as a unit of measure for the computational costs of operations within the FAT network and as the unit of work for securing and executing actions within the network; Factom's native token, the Factoid (FCT) is used as the unit of account for value transfers within the network gas system. The gas system uses an algorithm-based process to determine the combined dynamic quantity of FCT to both produce the needed EC to secure the transaction and also sufficiently incentivize the network for use of its computational resources in executing a transaction or contract. This system will compensate network validators to operate FAT nodes and better support the network’s ability to effectively deploy and execute a broad range of complex and dynamic smart contracts. For smart contracts and transactions that fail to fully execute, unconsumed transaction-derived EC will be retained by the tx/contract initiator. The full workflow of the proposed system is defined in the FATIP-108 Specification section below.

## Specification

When creating a smart contract on the FAT network, a user will either 1) submit the contract code and the priority parameter or 2) the sequence of calls and the priority parameter. The gas system automatically assesses the quantity of EC required for a contract’s specified chain by aggregating the estimated number of contract operations and their associated WASM opcode cost values as well as the EC required to deploy the contract and secure the tx. The total process returns an approximate cost value to the user denominated in FCT that reflects the combined costs of computation, storage, environmentals, and an incentive fee for the rapid execution and securing of the

### Gas Mechanism

The gas mechanism is tied to the metering of deterministic calls. The current WASM-based system allows the identification of specific operations through the number and complexity of opcodes created by metered WASM compilation.

The gas system combats the potential of network spamming by factoring the average use of a specific FAT chain over a period of the past five EBlocks within the gas cost determination process. Increases to a chain’s average use will lead to increases in the gas fees associated with using that specific chain, which aims to disincentivize the potential of network spamming.

### GAS Determination: FCT Estimation

FATIP-108 proposes a tiered and progressive opcode costs scheme for transactions based on computation/opcode intensity. The gas system sorts WASM opcodes by computational intensity into tiered Cost Groups (GR) one (1), two (2) and three (3), with GR3 representing those operations deemed most computationally expensive. This approach of using tiered opcode cost groups attempts to improve the predictability of the cost determinations; factor differences in the execution computation requirements across different FAT chains whose costs range based on token type, contract, and chain use; and encourage developers to optimize a contract’s size and functional efficiency.

A simplified FAT opcode unit cost table has been provided below in the FATIP-108 section [Operation Costs](#Operation Costs). A more inclusive cataloging of WASM opcodes to FAT Cost Groups will be conducted during gas system implementation and will be documented.

Gas within the FAT ecosystem is measured in EC; the lowest opcode cost group (GR1) gas cost unit is 0.005 EC, or $0.000005. The assigned gas cost values to each WASM opcode cost group are held within a special network chain called the “execution unit conversion rates” (EUCR) chain. While gas EC cost values are fixed, they can be updated by the community if changes to network use warrant their rebasing. The ability to update FAT’s gas EC cost values provides a mechanism for the community to ensure network gas costs remain competitive compared to other networks.

```
{ “date” : string,
“network” : string,
“spec_ver : string,
“signature : string,
[
{ “op_code” : string,
“ec_amount” : int32
},
{ “op_code” : string,
“ec_amount” : int32
},
]
}
```

Example JSON value to be used in the EUCR chain, which shows the date of entry, type of network (mainnet, testnet, etc), specification version for later upgrades, the signature of the signing mechanism, list of values that align the amount of EC to execution operands.

### GAS Determination: EC Estimation

Following the estimation and aggregation of computation costs, an EC estimation step derives the precise number of EC required to execute and write all required entries to the Factom Blockchain. On the Factom Blockchain, EC costs are managed by Factom’s on-chain EC exchange rate to target a peg of $0.001 per KB .

The EC estimation step concludes with: 1) the calculation of the amount of FCT required to convert to the needed amount of EC for contract deployment, execution, and entry writes; 2) the addition of a 5% safety band for summed EC; and 3) the addition of a network processing incentive fee equal to 50% of the contract’s total EC cost. FATIP-108 proposes a bottom up approach to this calculation:

1 step: evaluate source-code, generate WASM opcodes based on wasm-metering functionality.
2 step: sum EC values from opcode table to compute the estimated required ECs for execution
3 step: sum network writes operations; add total to the computed value in step 2
4 step: add 5% safety bound for summed EC, round result as some parameters might change during execution, such as variable state that require storage
5 step: add 50% of the value computed in step 3 as an FCT reward not to be converted

Pseudo code:

```
function gasEstimate(Argument contract){
var ec = evaluateAndMeter(contract)
var ecWithSafetyBound = ec + ((ec/100)*5)
var finalEC = ecWithSafetyBound + ((ecWithSafetyBound/100)*50)
return finalEC
}
```
_For example, if a contract requires 10000 opcodes for execution with 5000 GR1 operands @ 0.005 EC, 3000 GR2 operands @ 0.0075 EC, and 2000 GR3 operands @ 0.01 EC, (ignoring network writes) the total gas cost would compute to approximately $0.107 {~ 107 EC = 67 EC + 4 EC (5 % band) + 36 EC (processing incentive)._


### Contract Execution

A contract’s execution logic is triggered when a contract is submitted with a sufficient quantity of FCT. The system provides a function for the smart contract’s user/developer to find an optimal value for the execution. Contract deployers are free to submit higher values, but not more than five times the system-determined optimal value.
Contract execution:
1 step: accept FCT value along with contract source code
2 step: estimate required opcodes; total EC required based on estimation algorithm above
3 step: read EC rate chain to get current EC to FCT conversion rate
4 step: get number of ECs based on provided FCT value
5 step: compare number of required ECs to conversion number (step 4)
6 step: if conversion number less than required EC reject contract submission
7 step: if conversion number more than required EC accept
8 step: execute FCT to EC conversion based on required amount
9 step: execute contract on the node by burning required EC, writing data to the chain, and spend computational power
10 step: freeze leftover FCT in accumulator for further distribution
11 step: sum up FCT rewards per execution node until Factom block ended
12 step: release/unfreeze FCT and send FCT to the coinbase address of node that executed contract at the end of Factom block

Pseudo code:
```
function contractExecute(Argument contract, Argument fctAmount){
var valid, codes = evalContractCode(contract)
var costTable = factom.readCostTable();
var requiredEC = buildEstimateBasedOnNumberOfOperations(contract, codes, costTable)
var maxECfromFCT = fctAmount * getECRate();
if (maxECfromFCT < requiredEC) then
// not enough EC value for execution
return error
else
// continue execution, use requiredEC as gas value and leftover as
var fctToConvert = requiredFCT + (requiredFCT / 100 * 10)
var fctReward = fctAmount - fctToConvert
var ec = factom.burnToEC(fctToConvert)
exec(contract, ec) // run code on actual node
lock(fctReward) // lock reward
}
```

![img1](/assets/108_1.png)

#### Token Transactions

Token transaction costs should be based on the characteristics of a transaction. Token transactions are a contract function called by a contract user, and evaluated based on contract interface and provided arguments. Some transactions have greater costs especially if they require minting of a new token, using storage, or generating new contracts, etc.
1 step: accept function call, FCT value
2 step: sum up single operation estimates
3 step: sum up, add 10% bound
Next steps equals <4-12> of contract deployment
Any additional minting costs are based on a pricing defined in FAT-0/1 token specifications.

Pseudo code:
```
function txExecute(Argument contract, Argument fctAmount){
var valid, codes = evalContractFunction(contract)
var costTable = factom.readCostTable();
var requiredEC = buildEstimateBasedOnNumberOfOperations(contract, codes, costTable)
var maxECfromFCT = fctAmount * getECRate();

if (maxECfromFCT < requiredEC) then
// not enough EC value for execution
return error
else
// continue execution, use requiredEC as gas value and leftover as
var fctToConvert = requiredFCT + (requiredFCT / 100 * 10)
var fctReward = fctAmount - fctToConvert
var ec = factom.burnToEC(fctToConvert)
exec(contract, ec) // run code on actual node
lock(fctReward) // lock reward
}

```

![img2](/assets/108_2.png)

#### Operation Costs
WASM metering enables the precise measure of execution costs by analyzing the number of operations within a contract and the associated computation power each requires. Based on those values we can identify execution costs and estimate gas values in a distributed environment.
There are several types of operations. Given a set of operations and a corresponding set of costs for each operation, the system can deterministically estimate the computation run by summing up the costs on the execution of each operation.
For a smart contract, to a first approximation, we can assume that
size(contract) = α · n + s
where α is some constant value, n is the number of instructions (opcodes) and s is the sum of the sizes of all variable-size constants (strings, bytes) in the contract. So, the gas cost for a smart-contract consists of a number of instructions and long constants, which are performed in the execution unit (node).
As some operations require more computational power, opcodes have been batched into three groups. Using a tiered WASM opcode cost grouping scheme provides the ability to structure operations based on their processing power consumption.

##### Simple Operations (Group One - GR1)
Group One includes operations that can be identified precisely prior to execution such as arithmetic operations, and have non-branching code paths. Each WASM opcode is assigned an appropriate Intel IA-32 (x86) opcode (or a series of opcodes) internally. These opcodes have a fixed cycle count required by the CPU. FATIP-108 proposes keeping the same assignment and for the Factom community to maintain its own assigned cost values related to existing WASM opcode computational cost tables. WASM allows such cost values to be defined in JSON format.

##### Branching (Group Two - GR2)
This group includes logical operations that require branching, logic conditions (if, else, return), and loops with unidentified progress until their execution. Thus every branch leaf has its own value and based on the result of a pre-branching value, assigns a specific value.
Memory & Storage Operations (Group Three - GR3)
Group Three includes operations that require change of local and global variables during execution, and that hold memory as a finite-sized memory page which is increased during execution. If the amount of memory pages exceed an initial value, a transaction’s execution may fail with loss of already spent EC. For most operations, one memory page of size 65536 bytes is sufficient. By default the WASM ecosystem uses a linear memory progression, which will increase memory size only when it reaches the limit of the page. However, because there are cases when an execution could slightly exceed this memory page initial value limit, FATIP-108 adds a safety band to mitigate the risk of this value being exceeded.

### Operation Costs
Below are examples of typical WASM environment operations and FATIP-108 defined operation computational costs. Individual WASM opcodes can be reassigned across FATIP-108’s cost groups in the future if deemed prudent by the community.


| Operation | COST GROUP | COST PRICE, EC | Comment |
| ---------- | ------------ | ---------------- | ------------------------ |
| ADD | GR1 | 0.005 | Arithmetic operation |
| MUL | GR1 | 0.005 | |
| SUB | GR1 | 0.005 | |
| DIV | GR1 | 0.005 | |
| IF | GR2 | 0.0075 | Logical operation |
| THEN, ELSE | GR2 | 0.0075 | |
| RETURN | GR2 | 0.0075 | |
| SET | GR3 | 0.01 | Memory operation |
| UDPATE | GR3 | 0.01 | |
| JUMP | GR3 | 0.01 | Move to another place in code, loop |
| LOAD | GR3 | 0.01 | |

Additional considerations in place:
- when invoking other contracts with actions such as `call`, `delegate_call`, etc., an additional 0.04 EC is consumed.
- when creating a contract from a contract, additional 0.04 EC per call use, due to unknown nature of creation

![img1](/assets/108_2.png)

## Implementation
WASM-metering The metering counts computation time for a given program in units of gas.
WABT wasm-validation command-line tool is the best way of validating WASM binaries and to identify their correctness.

## Copyright
Copyright and related rights waived via CC0.