npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@fioprotocol/fio-sdk-lite

v1.0.0

Published

FIO SDK Lite is a lightweight library for signing transactions, decrypting FIO Requests, and signing nonces on the FIO blockchain.

Downloads

9

Readme

FIO SDK Lite

FIO SDK Lite is a lightweight library for signing transactions, decrypting FIO Requests, and signing nonces on the FIO blockchain.

For more information on FIO, visit the FIO website.

To explore the FIO Chain, API, and SDKs, check out the FIO Protocol Developer Hub.

Installation

To install the FIO SDK Lite, run:

npm install @fioprotocol/fio-sdk-lite

Type Documentation

Full type documentation is available here

Usage

Warning: In some transaction parameters, there is an actor parameter. You don't need to pass it because it is derived from the public key, which is in turn derived from the private key used to sign the transaction.

Sign Transaction

The following example demonstrates how to sign FIO blockchain transactions. It supports signing multiple transactions at once.

Action parameters actionParams:

  • action - Required. Action name of the specific action on FIO Chain, e.g. for registering FIO Handle: regaddress. For more details see FIO Chain Action API.

  • account- Required. Account name for contract matching the specific action on FIO Chain, e.g. for registering FIO Handle: fio.address. For more details see FIO Chain Action API.

  • authActor - Not required. Represents FIO Account which will execute the action. In most cases this is the hashed FIO Public Key. Is used if another actor will be used for authorization.

  • contentType - Required for newfundsreq (FIO Request) and recordobt (FIO Data) actions. 'new_funds_content' - FIO Request, or 'record_obt_data_content' - FIO Data.

  • data - Required. Body parameters for signing a transaction. See https://dev.fio.net/reference/fio-chain-actions-api

  • dataActor - Not required. Represents FIO Account which will execute the action. In most cases this is the hashed FIO Public Key. Is used if another account will execute an action.

  • id - Not required. Transaction ID that you want to sign. This is helpful for error handling.

  • payeeFioPublicKey - Required when action is: recordobt. FIO Public key of the wallet who will receive an OBT data record. This is used for encryption.

  • payerFioPublicKey - Required when action is: newfundsreq. FIO Public key of the wallet who will receive a FIO Request. This is used for encryption.

  • timeoutOffset - Not required. Time offset for transaction expiration in milliseconds. By default, this is set to 60000 milliseconds, equivalent to 1 minute.

import { signTransaction } from '@fioprotocol/fio-sdk-lite';

async function main() {
    // URL of FIO Chain API node, see: https://bpmonitor.fio.net/nodes
    const apiUrl = 'https://test.fio.eosusa.io'; // No trailing slashes

    // Transaction data, see https://dev.fio.net/reference/fio-chain-actions-api
    // actor is omitted as it will be inserted by the SDK.
    const params = {
        apiUrl,
        actionParams: [
            {
                action: 'regaddress',
                account: 'fio.address',
                data: {
                    fio_address: `testing-fio-handle-${Date.now()}@regtest`,
                    owner_fio_public_key: '',
                    tpid: '',
                    max_fee: 1500000000000, // Obtain from https://dev.fio.net/reference/get_fee
                },
            },
        ],
        privateKey: '5JSTL6nnXztYTD1buYfYSqJkNZTBdS9MDZf5nZsFW7gZd1pxZXo',
        // Get one for testing at: http://monitor.testnet.fioprotocol.io:3000/#createKey
        // And add tokens from faucet at: http://monitor.testnet.fioprotocol.io:3000/#faucet
    };

    try {
        const signedTransactions = await signTransaction(params);
        const signedTransactionsResult = JSON.parse(signedTransactions);

        const pushTransactionResult = async (signedTransactionsResult: any) => {
            const pushResult = await fetch(
                apiUrl+'/v1/chain/push_transaction',
                {
                    body: JSON.stringify(signedTransactionsResult),
                    method: 'POST',
                }
            );

            if ([400, 403, 500].includes(pushResult.status)) {
                const jsonResult = await pushResult.json();
                const errorMessage = jsonResult.message || 'Something went wrong';

                if (jsonResult.fields) {
                    const fieldErrors = jsonResult.fields.map(field => ({
                        name: field.name,
                        value: field.value,
                        error: field.error,
                    }));
                    throw new Error(`${errorMessage}: ${JSON.stringify(fieldErrors)}`);
                } else if (jsonResult.error && jsonResult.error.what) {
                    throw new Error(jsonResult.error.what);
                } else {
                    throw new Error(errorMessage);
                }
            }

            return await pushResult.json();
        };
        const results = await Promise.allSettled(
            signedTransactionsResult.successed.map(pushTransactionResult)
        );
        console.log(results);
        const processedData = results[0].status === 'fulfilled' ? results[0].value.processed : null;
        if (processedData) {
            const response = JSON.parse(processedData.action_traces[0].receipt.response);
            console.log('Processed Data Response:', JSON.stringify(response, null, 2));
        }
    } catch (error) {
        console.error("Error:", error);
    }
}

main();

Decrypt Content

Use this function to decrypt content in FIO Requests or FIO Data.

Parameters:

  • content - Required. Encrypted blob. The content field from FIO Request or FIO Data.

  • encryptionPublicKey - Required. FIO Public key of the other wallet that was used for encryption. This is returned by /get_pending_fio_requests and /get_obt_data. This is used for decryption.

  • fioContentType - Required. Set as follows: newfundsreq: new_funds_content recordobt: record_obt_data_content

  • privateKey - Required. FIO Private key.

import { decryptContent } from '@fioprotocol/fio-sdk-lite';

async function main() {
    // URL of FIO Chain API node, see: https://bpmonitor.fio.net/nodes
    const apiUrl = 'https://test.fio.eosusa.io'; // No trailing slashes
    const params = {
        fio_public_key: "FIO7MYkz3serGGGanVPnPPupE1xSm1t7t8mWJ3H7KEd2vS2ZZbXBF",
        limit: 1,
        offset: 0,
    };

    try {
        const response = await fetch(apiUrl+'/v1/chain/get_sent_fio_requests',
            {
                body: JSON.stringify(params),
                method: 'POST',
            },
        );
        const sentFioRequests = await response.json();
        const fioRequestToDecrypt = sentFioRequests.requests[0];
        const decryptedContent = decryptContent({
            content: fioRequestToDecrypt.content,
            encryptionPublicKey: fioRequestToDecrypt.payer_fio_public_key,
            fioContentType: 'new_funds_content', // new_funds_content - FIO Request, or 'record_obt_data_content' - FIO Data
            privateKey: '5JTmqev7ZsryGGkN6z4FRzd4ELQJLNZuhtQhobVVsJsBHnXxFCw',
            // Get one for testing at: http://monitor.testnet.fioprotocol.io:3000/#createKey
            // And add tokens from faucet at: http://monitor.testnet.fioprotocol.io:3000/#faucet
        });
        console.log(decryptedContent);
    } catch (error) {
        console.error("Error:", error);
    }
}

main();

Get Public Key from Private key and sign/verify nonce

Parameters getPublicKey:

  • privateKey - Required. FIO Private key.

Parameters signNonce:

  • nonce - Required. Nonce to sign.

  • privateKey - Required. FIO Private key.

Parameters verifySignature:

  • signature - Required. Signed signature string.

  • data - Required. Is a nonce value.

  • publicKey - Required. FIO Public key.

  • encoding - Not required. Is one of Buffer Encoding names: "ascii", "utf8", "utf-8", "utf16le", "utf-16le", "ucs2", "ucs-2", "base64", "base64url", "latin1", "binary", "hex". By default is automatically set as utf8.

import { signNonce, getPublicKey, verifySignature} from '@fioprotocol/fio-sdk-lite';
import { createHmac, randomBytes } from 'crypto-browserify';

async function main() {
  const privKey = '5JSTL6nnXztYTD1buYfYSqJkNZTBdS9MDZf5nZsFW7gZd1pxZXo';
  // Get one for testing at: http://monitor.testnet.fioprotocol.io:3000/#createKey
  // And add tokens from faucet at: http://monitor.testnet.fioprotocol.io:3000/#faucet
  const secret = 'nvjrf43dwmcsl';

  try {
    // Get public key from Private key
    const publicKey = getPublicKey({ privateKey: privKey });
    console.log('Public key', publicKey);

    // Generate nonce
    const stringToHash = randomBytes(8).toString('hex');
    const nonce = createHmac('sha256', secret)
      .update(stringToHash)
      .digest('hex');

    // Sign nonce
    const singedNonce = signNonce({ nonce, privateKey: privKey });
    console.log('Signed nonce', singedNonce);

    // Verify nonce
    const isSignatureVerified = verifySignature({
      signature: singedNonce,
      data: nonce,
      publicKey,
    });
    console.log(isSignatureVerified);
  } catch (error) {
    console.error('Error:', error);
  }
}

main();

Testing

Run tests using:

npm run test

Environment

Requires Node.js version 20 and higher.

Local Instalation

Build and run

npm install
npm run build

Build docs

To build docs of the project, run:

npm run docs