Skip to content

Latest commit

 

History

History
455 lines (352 loc) · 12.8 KB

File metadata and controls

455 lines (352 loc) · 12.8 KB

Docs site

For more complete docs, visit the IOTA TypeScript SDK docs

IOTA TypeScript SDK

@iota/iota-sdk is part of the IOTA Rebased SDK, designed specifically for interacting with the IOTA Rebased protocol.

This is the IOTA TypeScript SDK built on the IOTA JSON RPC API. It provides utility classes and functions for applications to sign transactions and interact with the IOTA network.

Installing

To use the SDK in your project, you can do:

$ npm install @iota/iota-sdk

You can also use your preferred package manager, such as yarn or pnpm.

Building Locally

To get started you need to install pnpm, then run the following command:

# Install all dependencies
$ pnpm install

# Run `build` for the TypeScript SDK if you're in the `sdk/typescript` project
$ pnpm run build

# Run `sdk build` for the TypeScript SDK if you're in the root of `iota` repo
$ pnpm sdk build

All pnpm commands below are intended to be run in the root of the iota repo.

Docs

You can find the TypeScript SDK Guides at IOTA Wiki and also the TypeDoc

Runnable Examples

You may want to run some of the examples we have.

Testing

To run unit tests

pnpm --filter @iota/iota-sdk test:unit

To run E2E tests against local network

pnpm --filter @iota/iota-sdk prepare:e2e

// This will run all e2e tests
pnpm --filter @iota/iota-sdk test:e2e

// Alternatively you can choose to run only one test file
npx vitest txn-builder.test.ts

Troubleshooting:

If you see errors like ECONNRESET or "socket hang up", run node -v to make sure your node version is v24.x.x.

To run E2E tests against Devnet

VITE_FAUCET_URL='https://faucet.devnet.iota.cafe:443/gas' VITE_FULLNODE_URL='https://api.devnet.iota.cafe' pnpm --filter @iota/iota-sdk exec vitest e2e

Connecting to IOTA Network

The IotaClient class provides a connection to the JSON-RPC Server and should be used for all read-only operations. The default URLs to connect with the RPC server are:

  • Local: http://127.0.0.1:9000
  • Devnet: https://api.devnet.iota.cafe
import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';

// create a client connected to devnet
const client = new IotaClient({ url: getFullnodeUrl('devnet') });

// get coins owned by an address
await client.getCoins({
    owner: '0x34abc6dfbf9ae91106ccc21b1a7839704cc9932a8ab571b7f60a2894cea219e7',
});

For local development, you can run cargo run --bin --with-faucet --force-regenesis to spin up a local network with a local validator, a fullnode, and a faucet server. Refer to this guide for more information.

import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';

// create a client connected to devnet
const client = new IotaClient({ url: getFullnodeUrl('localnet') });

// get coins owned by an address
await client.getCoins({
    owner: '0x34abc6dfbf9ae91106ccc21b1a7839704cc9932a8ab571b7f60a2894cea219e7',
});

You can also construct your own in custom connections, with the URL for your own fullnode

import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';

// create a client connected to devnet
const client = new IotaClient({
    url: 'https://api.devnet.iota.cafe',
});

// get coins owned by an address
await client.getCoins({
    owner: '0x34abc6dfbf9ae91106ccc21b1a7839704cc9932a8ab571b7f60a2894cea219e7',
});

Getting coins from the faucet

You can request iota from the faucet when running against devnet, testnet, or localnet

import { getFaucetHost, requestIotaFromFaucetV1 } from '@iota/iota-sdk/faucet';

await requestIotaFromFaucetV1({
    host: getFaucetHost('testnet'),
    recipient: '0x34abc6dfbf9ae91106ccc21b1a7839704cc9932a8ab571b7f60a2894cea219e7',
});

Writing APIs

For a primer for building transactions, refer to this guide.

Transfer Object

import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';
import { Ed25519Keypair } from '@iota/iota-sdk/keypairs/ed25519';
import { Transaction } from '@iota/iota-sdk/transactions';

// Generate a new Ed25519 Keypair
const keypair = new Ed25519Keypair();
const client = new IotaClient({
    url: getFullnodeUrl('testnet'),
});

const tx = new Transaction();
tx.transferObjects(
    ['0xe19739da1a701eadc21683c5b127e62b553e833e8a15a4f292f4f48b4afea3f2'],
    '0x1d20dcdb2bca4f508ea9613994683eb4e76e9c4ed371169677c1be02aaf0b12a',
);
const result = await client.signAndExecuteTransaction({
    signer: keypair,
    transaction: tx,
});
console.log({ result });

Transfer IOTA

To transfer 1000 NANOS to another address:

import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';
import { Ed25519Keypair } from '@iota/iota-sdk/keypairs/ed25519';
import { Transaction } from '@iota/iota-sdk/transactions';

// Generate a new Ed25519 Keypair
const keypair = new Ed25519Keypair();
const client = new IotaClient({
    url: getFullnodeUrl('testnet'),
});

const tx = new Transaction();
const [coin] = tx.splitCoins(tx.gas, [1000]);
tx.transferObjects([coin], keypair.getPublicKey().toIotaAddress());
const result = await client.signAndExecuteTransaction({
    signer: keypair,
    transaction: tx,
});
console.log({ result });

Merge coins

import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';
import { Ed25519Keypair } from '@iota/iota-sdk/keypairs/ed25519';
import { Transaction } from '@iota/iota-sdk/transactions';

// Generate a new Ed25519 Keypair
const keypair = new Ed25519Keypair();
const client = new IotaClient({
    url: getFullnodeUrl('testnet'),
});

const tx = new Transaction();
tx.mergeCoins('0xe19739da1a701eadc21683c5b127e62b553e833e8a15a4f292f4f48b4afea3f2', [
    '0x127a8975134a4824d9288722c4ee4fc824cd22502ab4ad9f6617f3ba19229c1b',
]);
const result = await client.signAndExecuteTransaction({
    signer: keypair,
    transaction: tx,
});
console.log({ result });

Move Call

import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';
import { Ed25519Keypair } from '@iota/iota-sdk/keypairs/ed25519';
import { Transaction } from '@iota/iota-sdk/transactions';

// Generate a new Ed25519 Keypair
const keypair = new Ed25519Keypair();
const client = new IotaClient({
    url: getFullnodeUrl('testnet'),
});
const packageObjectId = '0x...';
const tx = new Transaction();
tx.moveCall({
    target: `${packageObjectId}::nft::mint`,
    arguments: [tx.pure.string('Example NFT')],
});
const result = await client.signAndExecuteTransaction({
    signer: keypair,
    transaction: tx,
});
console.log({ result });

Publish Modules

To publish a package:

import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';
import { Ed25519Keypair } from '@iota/iota-sdk/keypairs/ed25519';
import { Transaction } from '@iota/iota-sdk/transactions';

const { execSync } = require('child_process');
// Generate a new Ed25519 Keypair
const keypair = new Ed25519Keypair();
const client = new IotaClient({
    url: getFullnodeUrl('testnet'),
});
const { modules, dependencies } = JSON.parse(
    execSync(`${cliPath} move build --dump-bytecode-as-base64 --path ${packagePath}`, {
        encoding: 'utf-8',
    }),
);
const tx = new Transaction();
const [upgradeCap] = tx.publish({
    modules,
    dependencies,
});
tx.transferObjects([upgradeCap], await client.getAddress());
const result = await client.signAndExecuteTransaction({
    signer: keypair,
    transaction: tx,
});
console.log({ result });

Reading APIs

Get Owned Objects

Fetch objects owned by the address 0xcc2bd176a478baea9a0de7a24cd927661cc6e860d5bacecb9a138ef20dbab231

import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';

const client = new IotaClient({
    url: getFullnodeUrl('testnet'),
});
const objects = await client.getOwnedObjects({
    owner: '0xcc2bd176a478baea9a0de7a24cd927661cc6e860d5bacecb9a138ef20dbab231',
});

Get Object

Fetch object details for the object with id 0xe19739da1a701eadc21683c5b127e62b553e833e8a15a4f292f4f48b4afea3f2

import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';

const client = new IotaClient({
    url: getFullnodeUrl('testnet'),
});
const txn = await client.getObject({
    id: '0xcc2bd176a478baea9a0de7a24cd927661cc6e860d5bacecb9a138ef20dbab231',
    // fetch the object content field
    options: { showContent: true },
});
// You can also fetch multiple objects in one batch request
const txns = await client.multiGetObjects({
    ids: [
        '0xcc2bd176a478baea9a0de7a24cd927661cc6e860d5bacecb9a138ef20dbab231',
        '0x9ad3de788483877fe348aef7f6ba3e52b9cfee5f52de0694d36b16a6b50c1429',
    ],
    // only fetch the object type
    options: { showType: true },
});

Get Transaction

Fetch transaction details from transaction digests:

import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';

const client = new IotaClient({
    url: getFullnodeUrl('testnet'),
});
const txn = await client.getTransaction({
    digest: '9XFneskU8tW7UxQf7tE5qFRfcN4FadtC2Z3HAZkgeETd',
    // only fetch the effects field
    options: {
        showEffects: true,
        showInput: false,
        showEvents: false,
        showObjectChanges: false,
        showBalanceChanges: false,
    },
});

// You can also fetch multiple transactions in one batch request
const txns = await client.multiGetTransactions({
    digests: [
        '9XFneskU8tW7UxQf7tE5qFRfcN4FadtC2Z3HAZkgeETd',
        '17mn5W1CczLwitHCO9OIUbqirNrQ0cuKdyxaNe16SAME',
    ],
    // fetch both the input transaction data as well as effects
    options: { showInput: true, showEffects: true },
});

Get Checkpoints

Get latest 100 Checkpoints in descending order and print Transaction Digests for each one of them.

client.getCheckpoints({ descendingOrder: true }).then(function (checkpointPage: CheckpointPage) {
    console.log(checkpointPage);

    checkpointPage.data.forEach((checkpoint) => {
        console.log('---------------------------------------------------------------');
        console.log(
            ' -----------   Transactions for Checkpoint:  ',
            checkpoint.sequenceNumber,
            ' -------- ',
        );
        console.log('---------------------------------------------------------------');
        checkpoint.transactions.forEach((tx) => {
            console.log(tx);
        });
        console.log('***************************************************************');
    });
});

Get Checkpoint 1994010 and print details.

client.getCheckpoint({ id: '1994010' }).then(function (checkpoint: Checkpoint) {
    console.log('Checkpoint Sequence Num ', checkpoint.sequenceNumber);
    console.log('Checkpoint timestampMs ', checkpoint.timestampMs);
    console.log('Checkpoint # of Transactions ', checkpoint.transactions.length);
});

Get Coins

Fetch coins of type 0x65b0553a591d7b13376e03a408e112c706dc0909a79080c810b93b06f922c458::usdc::USDC owned by an address:

import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';

const client = new IotaClient({
    url: getFullnodeUrl('testnet'),
});
const coins = await client.getCoins({
    owner: '0xcc2bd176a478baea9a0de7a24cd927661cc6e860d5bacecb9a138ef20dbab231',
    coinType: '0x65b0553a591d7b13376e03a408e112c706dc0909a79080c810b93b06f922c458::usdc::USDC',
});

Fetch all coin objects owned by an address:

import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';

const client = new IotaClient({
    url: getFullnodeUrl('testnet'),
});
const allCoins = await client.getAllCoins({
    owner: '0xcc2bd176a478baea9a0de7a24cd927661cc6e860d5bacecb9a138ef20dbab231',
});

Fetch the total coin balance for one coin type, owned by an address:

import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';

const client = new IotaClient({
    url: getFullnodeUrl('testnet'),
});
// If coin type is not specified, it defaults to 0x2::iota::IOTA
const coinBalance = await client.getBalance({
    owner: '0xcc2bd176a478baea9a0de7a24cd927661cc6e860d5bacecb9a138ef20dbab231',
    coinType: '0x65b0553a591d7b13376e03a408e112c706dc0909a79080c810b93b06f922c458::usdc::USDC',
});

Events API

Querying events created by transactions sent by account 0xcc2bd176a478baea9a0de7a24cd927661cc6e860d5bacecb9a138ef20dbab231

import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';

const client = new IotaClient({
    url: getFullnodeUrl('testnet'),
});
const events = client.queryEvents({
    query: { Sender: "0x34abc6dfbf9ae91106ccc21b1a7839704cc9932a8ab571b7f60a2894cea219e7" },
    limit: 2,
});