# New Fee Mechanism in Pirichain

We’re excited to announce a recent update that brings more dynamism to blockchain transactions. Previously, transaction fees were static at 0.1 PIRI. With this update, transaction fees are now dynamically calculated based on the blockchain’s congestion and other factors.

By the way minimum fee is increased to 1 PIRI.

**Technical Details:**

First, import the necessary libraries for cryptographic operations.

```javascript
const EC = require('elliptic').ec;
const ec = new EC('secp256k1');
const sha = require('sha256');
const req = require('request');
```

Implement the `toHexString` function to convert a byte array to a hexadecimal string.

```javascript
function toHexString(byteArray) {
    return Array.from(byteArray, function (byte) {
        return ('0' + (byte & 0xFF).toString(16)).slice(-2);
    }).join('');
}
```

Create the `getEstimatedFee` function to fetch the estimated transaction fee from the blockchain.

```javascript
async function getEstimatedFee() {
    return new Promise((resolve, reject) => {
        const requestOptionsTransaction = {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
        };
        req.post('https://core.pirichain.com/getEstimatedFee', requestOptionsTransaction, function (f, res) {
            if (!res)
            {
                resolve(1);
                return;
            }
            if (!res.body)
                console.log(res)
            else {
                console.log(res.body);
                const est=JSON.parse(res.body).estimatedBandWidthFee;
                resolve(est);
            }
        });
    })

}
```

Use the `sortObjectProperty` function to sort the transaction data before signing.

```javascript
function sortObjectProperty(o) {
    let sorted = {},
        key, a = [];

    for (key in o) {
        if (o.hasOwnProperty(key)) {
            a.push(key);
        }
    }
    a.sort();
    for (key = 0; key < a.length; key++) {
        sorted[a[key]] = o[a[key]];
    }
    return sorted;
}
```

Implement the `prepareSendTokenWithSignature` function to organize transaction data.

```javascript
async function prepareSendTokenWithSignature(from, toAddress, amount, assetID, globTime, fee) {
    let data = {
        from: from,
        to: toAddress,
        amount: amount,
        assetID: assetID,
        fee: fee,
        timeStamp: globTime,
        metaData: {}
    };

    data = sortObjectProperty(data);
    const message = JSON.stringify(data);
    return message;
}
```

Use the `sendRawTransaction` function to sign and send the transaction.

```javascript
async function sendRawTransaction(privateKey, from, to, amount, assetID = -1) {

    let pubKey = '';
    let timeStamp = new Date().getTime();
    const estimatedFee = parseFloat(await getEstimatedFee());

    let message_ = await prepareSendTokenWithSignature(from,
        to,
        amount,
        assetID,
        timeStamp,
        estimatedFee
    );

    const key = ec.keyFromPrivate(privateKey);
    pubKey = key.getPublic().encode('hex');
    let message = sha(message_);

    const resultSign = key.sign(message).toDER();
    const signatureData = toHexString(resultSign);
    const params = {
        to: to,
        amount: amount,
        assetID: -1,
        timeStamp: timeStamp,
        signaturedData: signatureData,
        publicKey: pubKey,
        address: from,
        fee: estimatedFee
    };

    console.log('message : ' + message_);
    console.log(params);
    const requestOptionsTransaction = {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(params)
    };

    req.post('https://core.pirichain.com/sendRawTransaction', requestOptionsTransaction, function (f, res) {

        if (!res.body)
            console.log(res)
        else
            console.log(res.body);
    });
}
```

Finally, use the `sendRaw` function to initiate the transaction process.

```javascript
async function sendRaw(from, privateKey, to, amount) {
    const result = await address.makingAddressInit();
    const amount = parseFloat(parseFloat(0.0001).toFixed(8));
    await sendRawTransaction(privateKey, from, to, amount, -1);
}
```

With this update, we aim to make blockchain transactions more efficient and responsive to network conditions. We believe that dynamically adjusting transaction fees will lead to a fairer and more sustainable blockchain ecosystem.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://whitepaper.pirichain.com/updates/feeupdate.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
