diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index b907dbc..de36198 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -471,6 +471,23 @@ export default defineConfig({ { text: 'Testnet', link: '/testnet/' } ] }, + { + // Library tutorials (phase 7): steem-js + steemgosdk usage demos. + // En-only like the Guides chapters above - the locale sidebars + // below deliberately omit this group (a locale entry would 404). + text: 'Tutorials', + items: [ + { text: 'Tutorial Overview', link: '/tutorials/' }, + { text: 'steem-js: Getting Started', link: '/tutorials/steem-js/' }, + { text: 'steem-js: Reading Chain Data', link: '/tutorials/steem-js/read-api' }, + { text: 'steem-js: Broadcasting Operations', link: '/tutorials/steem-js/broadcast' }, + { text: 'steem-js: Signed Calls & Verification', link: '/tutorials/steem-js/signed-calls' }, + { text: 'steem-js: RPC Auth Test Migration', link: '/tutorials/steem-js/rpc-auth-migration' }, + { text: 'steemgosdk (Go): Getting Started', link: '/tutorials/steemgosdk/' }, + { text: 'steemgosdk (Go): Broadcasting Operations', link: '/tutorials/steemgosdk/broadcast' }, + { text: 'steemgosdk (Go): SignedCall API', link: '/tutorials/steemgosdk/signed-call' } + ] + }, { text: 'Services', items: [ diff --git a/docs/tutorials/index.md b/docs/tutorials/index.md new file mode 100644 index 0000000..1cb6875 --- /dev/null +++ b/docs/tutorials/index.md @@ -0,0 +1,36 @@ +--- +title: Tutorials +description: Hands-on tutorials and usage examples for the official Steem client libraries - steem-js for JavaScript/TypeScript and steemgosdk for Go. +--- + +# Tutorials + +This section collects hands-on usage examples for the two official Steem client libraries. Every example was migrated from the libraries' own documentation, and the demos are runnable against a public node such as `https://api.steemit.com`. + +## The libraries + +| Library | Language | Package / module | Repository | +|---------|----------|------------------|------------| +| steem-js | JavaScript / TypeScript | npm package `@steemit/steem-js` 1.2.4 | [steemit/steem-js](https://github.com/steemit/steem-js) | +| steemgosdk | Go | Go module `github.com/steemit/steemgosdk` | [steemit/steemgosdk](https://github.com/steemit/steemgosdk) | + +Both libraries talk to the same JSON-RPC API that the generated [API Reference](/api/) documents, method by method. Use the tutorials to learn the client-side patterns; use the API Reference for the on-the-wire details of every method. + +## steem-js pages + +- [Getting started](/tutorials/steem-js/) - installation, browser usage, configuration (`config.set`, `api.setUrl`, `setOptions`, multiple API instances), JSON-RPC overview, API routing, end-to-end usage examples, TypeScript support and error handling. +- [Reading chain data](/tutorials/steem-js/read-api.html) - every read helper: tags, blog and discussions, blocks, global properties, accounts, market, votes, content, witnesses, plus the login/follow helpers and the offline authentication, formatter and utils utilities. +- [Broadcasting operations](/tutorials/steem-js/broadcast.html) - the full `steem.broadcast` operation catalogue, promise/callback patterns, multisig and binary transaction serialization. +- [Signed calls and signature verification](/tutorials/steem-js/signed-calls.html) - authenticated `signedCall` requests and the signature verification toolkit, with the complete example guides. +- [RPC auth test migration](/tutorials/steem-js/rpc-auth-migration.html) - how the `rpc-auth` test suite was migrated into steem-js. + +## steemgosdk pages + +- [Getting started](/tutorials/steemgosdk/) - client setup, chain-reading API examples, key-generation auth examples and Steem URI signing examples. +- [Broadcasting operations](/tutorials/steemgosdk/broadcast.html) - votes, transfers, comments, comment options with beneficiaries, multi-operation transactions and custom_json broadcasts, plus complete end-to-end examples. +- [SignedCall API](/tutorials/steemgosdk/signed-call.html) - authenticated JSON-RPC calls from Go, interoperable with steem-js signed calls. + +## Notes + +- The tutorials are English-only for now, mirroring the Guides section. +- Examples reference well-known test keys from the libraries' own documentation; never use them in production - generate your own keys as shown in the auth examples. diff --git a/docs/tutorials/steem-js/broadcast.md b/docs/tutorials/steem-js/broadcast.md new file mode 100644 index 0000000..9796efd --- /dev/null +++ b/docs/tutorials/steem-js/broadcast.md @@ -0,0 +1,399 @@ +--- +title: steem-js - Broadcasting Operations +description: The full steem-js broadcast catalogue - promise and callback patterns, every broadcast operation, multisig and binary transaction serialization. +--- + +# steem-js: Broadcasting Operations + +The `steem.broadcast` namespace causes permanent changes on the blockchain: votes, transfers, posts, witness operations and more. This page carries the complete broadcast examples from the [steem-js](https://github.com/steemit/steem-js) documentation; reading chain data is covered in [Reading chain data](/tutorials/steem-js/read-api.html). + +> On-the-wire details of every operation are documented in the generated [broadcast operations reference](/api/broadcast_ops/). + +## Broadcast API + +## Broadcast API + +### Broadcast Block + +Broadcast a new block on the Steem blockchain. + +```javascript +steem.api.broadcastBlockAsync(blockObject).then(function(data) { + console.log(data); +}); +``` + +### Broadcast Transaction Synchronous + +```javascript +steem.api.broadcastTransactionSynchronousAsync(trx).then(function(result) { + console.log(result); +}); +``` + +## Broadcast Operations + +## Broadcast Operations + +The `steem.broadcast` methods cause permanent changes on the blockchain. + +### Promise Support + +All broadcast methods support both callback and Promise patterns. You can use either approach: + +#### Promise Pattern (Recommended) + +```javascript +// Using Promises directly +steem.broadcast.voteAsync(wif, voter, author, permlink, weight) + .then(result => console.log(result)) + .catch(error => console.error(error)); + +// Using async/await +async function castVote() { + try { + const result = await steem.broadcast.voteAsync(wif, voter, author, permlink, weight); + console.log(result); + } catch (error) { + console.error(error); + } +} +``` + +#### Callback Pattern (Legacy) + +```javascript +steem.broadcast.vote(wif, voter, author, permlink, weight, function(err, result) { + if (err) { + console.error(err); + } else { + console.log(result); + } +}); +``` + +### Account Create + +```javascript +steem.broadcast.accountCreateAsync(wif, fee, creator, newAccountName, owner, active, posting, memoKey, jsonMetadata).then(function(result) { + console.log(result); +}); +``` + +### Account Create With Delegation + +```javascript +steem.broadcast.accountCreateWithDelegationAsync(wif, fee, delegation, creator, newAccountName, owner, active, posting, memoKey, jsonMetadata, extensions).then(function(result) { + console.log(result); +}); +``` + +### Delegate Vesting Shares + +Delegates STEEM POWER, denominated in VESTS, from a `delegator` to the `delegatee`. Requires the `delegator`'s private WIF key. Set the delegation to 0 to undelegate. + +```javascript +steem.broadcast.delegateVestingSharesAsync(wif, delegator, delegatee, vesting_shares).then(function(result) { + console.log(result); +}); +``` + +### Account Update + +```javascript +steem.broadcast.accountUpdateAsync(wif, account, owner, active, posting, memoKey, jsonMetadata).then(function(result) { + console.log(result); +}); +``` + +### Account Witness Proxy + +```javascript +steem.broadcast.accountWitnessProxyAsync(wif, account, proxy).then(function(result) { + console.log(result); +}); +``` + +### Account Witness Vote + +```javascript +steem.broadcast.accountWitnessVoteAsync(wif, account, witness, approve).then(function(result) { + console.log(result); +}); +``` + +### Change Recovery Account + +```javascript +steem.broadcast.changeRecoveryAccountAsync(wif, accountToRecover, newRecoveryAccount, extensions).then(function(result) { + console.log(result); +}); +``` + +### Comment + +```javascript +steem.broadcast.commentAsync(wif, parentAuthor, parentPermlink, author, permlink, title, body, jsonMetadata).then(function(result) { + console.log(result); +}); +``` + +### Comment Options + +```javascript +steem.broadcast.commentOptionsAsync(wif, author, permlink, maxAcceptedPayout, percentSteemDollars, allowVotes, allowCurationRewards, extensions).then(function(result) { + console.log(result); +}); +``` + +The `extensions` parameter supports the beneficiaries extension (tag 0). Pass an array of `[tag, value]`, e.g. `[[0, { beneficiaries: [{ account: 'foo', weight: 1000 }, { account: 'bar', weight: 5000 }] }]]`. Beneficiaries are automatically sorted by account name before serialization to comply with the Steem protocol. + +### Convert + +```javascript +steem.broadcast.convertAsync(wif, owner, requestid, amount).then(function(result) { + console.log(result); +}); +``` + +### Custom + +```javascript +steem.broadcast.customAsync(wif, requiredAuths, id, data).then(function(result) { + console.log(result); +}); +``` + +### Custom Json + +```javascript +steem.broadcast.customJsonAsync(wif, requiredAuths, requiredPostingAuths, id, json).then(function(result) { + console.log(result); +}); +``` + +### Delete Comment + +```javascript +steem.broadcast.deleteCommentAsync(wif, author, permlink).then(function(result) { + console.log(result); +}); +``` + +### Escrow Operations + +```javascript +// Escrow Dispute +steem.broadcast.escrowDisputeAsync(wif, from, to, agent, who, escrowId); + +// Escrow Release +steem.broadcast.escrowReleaseAsync(wif, from, to, agent, who, receiver, escrowId, sbdAmount, steemAmount); + +// Escrow Transfer +steem.broadcast.escrowTransferAsync(wif, from, to, agent, escrowId, sbdAmount, steemAmount, fee, ratificationDeadline, escrowExpiration, jsonMeta); + +// Escrow Approve +steem.broadcast.escrowApproveAsync(wif, from, to, agent, who, escrowId, approve); +``` + +### Get Escrow + +```javascript +steem.api.getEscrowAsync(from, escrowId).then(function(data) { + console.log(data); +}); +``` + +### Feed Publish + +```javascript +steem.broadcast.feedPublishAsync(wif, publisher, exchangeRate).then(function(result) { + console.log(result); +}); +``` + +### Limit Order Operations + +```javascript +// Limit Order Cancel +steem.broadcast.limitOrderCancelAsync(wif, owner, orderid); + +// Limit Order Create +steem.broadcast.limitOrderCreateAsync(wif, owner, orderid, amountToSell, minToReceive, fillOrKill, expiration); + +// Limit Order Create2 +steem.broadcast.limitOrderCreate2Async(wif, owner, orderid, amountToSell, exchangeRate, fillOrKill, expiration); +``` + +**Limit Order Parameter Description:** + +| Parameter | Description | Data Type | Notes | +|---|---|---|---| +| wif | Active private key | String | | +| owner | Account name | String | No leading @ symbol | +| orderid | User defined ordernumber | Integer | Used to cancel orders | +| amountToSell | Amount to sell | String | "X.XXX ASSET" must have 3 decimal places. e.g. "25.100 SBD" | +| minToReceive | Amount desired | String | "X.XXX ASSET" must have 3 decimal places. e.g. "20.120 STEEM" | +| fillOrKill | Fill order from current order book or kill the order | Boolean | `false` places the order into the Order Book until either cancelled, filled, or the expiration time is reached | +| expiration | Time when order expires | Integer | Unit milliseconds. Zero is UNIX epoch | + +### Account Recovery + +```javascript +// Recover Account +steem.broadcast.recoverAccountAsync(wif, accountToRecover, newOwnerAuthority, recentOwnerAuthority, extensions); + +// Request Account Recovery +steem.broadcast.requestAccountRecoveryAsync(wif, recoveryAccount, accountToRecover, newOwnerAuthority, extensions); +``` + +### Transfer Operations + +```javascript +// Transfer +steem.broadcast.transferAsync(wif, from, to, amount, memo); + +// Transfer To Vesting +steem.broadcast.transferToVestingAsync(wif, from, to, amount); + +// Transfer To Savings +steem.broadcast.transferToSavingsAsync(wif, from, to, amount, memo); + +// Transfer From Savings +steem.broadcast.transferFromSavingsAsync(wif, from, requestId, to, amount, memo); + +// Cancel Transfer From Savings +steem.broadcast.cancelTransferFromSavingsAsync(wif, from, requestId); +``` + +**Transfer Parameter Description:** + +| Parameter | Description | Data Type | Notes | +|---|---|---|---| +| wif | Active private key for the `from` account | String | | +| from | Account name to take asset from | String | No leading @ symbol | +| to | Account name to place asset into | String | No leading @ symbol | +| amount | Amount of asset to transfer | String | "X.XXX ASSET" must have 3 decimal places. e.g. "5.150 SBD" | + +### Vote + +```javascript +steem.broadcast.voteAsync(wif, voter, author, permlink, weight).then(function(result) { + console.log(result); +}); +``` + +### Withdraw Vesting + +```javascript +steem.broadcast.withdrawVestingAsync(wif, account, vestingShares).then(function(result) { + console.log(result); +}); +``` + +### Witness Update + +```javascript +steem.broadcast.witnessUpdateAsync(wif, owner, url, blockSigningKey, props, fee).then(function(result) { + console.log(result); +}); +``` + +### Set Withdraw Vesting Route + +```javascript +steem.broadcast.setWithdrawVestingRouteAsync(wif, fromAccount, toAccount, percent, autoVest).then(function(result) { + console.log(result); +}); +``` + +### Get Withdraw Routes + +Gets withdraw routes (Steem Power withdraws). + +```javascript +steem.api.getWithdrawRoutesAsync(account, withdrawRouteType).then(function(data) { + console.log(data); +}); +``` + +### Claim Reward Balance + +Claims pending rewards, be they Steem, SBD or Vests. + +```javascript +steem.broadcast.claimRewardBalanceAsync(wif, account, reward_steem, reward_sbd, reward_vests).then(function(data) { + console.log(data); +}); +``` + +**Parameter Description:** + +| Parameter | Data Type | Description | +|---------|--------|-----------| +| wif | string | Use steem.auth.toWif(user, pass, type) | +| account | string | A Steem username | +| reward_steem | string | Balance like "0.000 STEEM" | +| reward_sbd | string | Balance like "0.000 SBD" | +| reward_vests | string | Balance like "0.000006 VESTS" | + +### Multisig + +You can use multisignature to broadcast an operation. + +```javascript +steem.broadcast.sendAsync({ + extensions: [], + operations: [ + ['vote', { + voter: 'guest123', + author: 'fabien', + permlink: 'test', + weight: 1000 + }] + ] +}, [privPostingWif1, privPostingWif2]).then(result => { + console.log(result); +}); +``` + +### Transaction serialization (binary) + +Broadcast and signing use a **binary transaction format** compatible with the Steem protocol (FC-style). The serializer lives in `src/auth/serializer/transaction.ts` and is used internally by `steem.auth.signTransaction` and `steem.broadcast.sendAsync`. + +**Usage** + +- **For signing / digest**: `steem.auth.serializeTransaction(trx)` — returns the `Buffer` that is hashed for the signature. This is the public API for the binary serializer; `steem.auth.transaction.toBuffer(trx)` is the equivalent internal entry point. + +```javascript +// The public serializer (preferred for app code): +const buf = steem.auth.serializeTransaction(trx); // Buffer +``` +- **Transaction shape**: `trx` must include `ref_block_num`, `ref_block_prefix`, `expiration`, `operations` (array of `[opType, opData]`), and optionally `extensions` and `signatures`. + +**Serializer coverage** + +All Steem operation types used in `operations` are supported (op type indices 0–54), including: + +- **Content & social**: vote, comment, delete_comment, comment_options, custom_json +- **Accounts & authority**: account_create, account_update, account_update2, account_create_with_delegation, create_claimed_account, request_account_recovery, recover_account, change_recovery_account, reset_account, set_reset_account, decline_voting_rights +- **Transfers & vesting**: transfer, transfer_to_vesting, withdraw_vesting, set_withdraw_vesting_route, transfer_to_savings, transfer_from_savings, cancel_transfer_from_savings, delegate_vesting_shares +- **Market & convert**: limit_order_create, limit_order_create2, limit_order_cancel, feed_publish, convert, fill_order +- **Escrow**: escrow_transfer, escrow_dispute, escrow_release, escrow_approve +- **Rewards & system**: claim_reward_balance, claim_reward_balance2, comment_reward, liquidity_reward, interest, fill_vesting_withdraw, fill_convert_request, fill_transfer_from_savings +- **Witness & custom**: pow, pow2, witness_update, witness_set_properties, account_witness_vote, account_witness_proxy, custom, custom_binary + +Field order and encoding (assets, authorities, time, extensions) follow the same layout as the C++ FC_REFLECT / [steemutil](https://github.com/steemit/steemutil) protocol. Cross-language fixtures under `test/fixtures/serializer/` are used to keep the JS output aligned with steemutil’s encoder where applicable. + +**Compatibility notes** + +- Use **STEEM / SBD / VESTS** asset strings (e.g. `"1.000 STEEM"`) for amount fields. +- Authorities: `owner` / `active` / `posting` use `weight_threshold`, `account_auths`, and `key_auths` (array of `[key, weight]`); public keys as STM… strings. +- Optional fields (e.g. `owner` in account_update) are encoded with a presence byte where the protocol requires it. +- Serializer support **does not imply** a high-level `steem.broadcast.*` wrapper, JSON normalization, or string-only metadata handling for every operation listed above. + + +## Where to go next + +- End-to-end vote / transfer / publish snippets: [Getting started - Usage Examples](/tutorials/steem-js/index.html#usage-examples). +- Signing and verifying transactions by hand: [Signed calls and signature verification](/tutorials/steem-js/signed-calls.html). diff --git a/docs/tutorials/steem-js/index.md b/docs/tutorials/steem-js/index.md new file mode 100644 index 0000000..86bfbab --- /dev/null +++ b/docs/tutorials/steem-js/index.md @@ -0,0 +1,527 @@ +--- +title: steem-js - Getting Started +description: Install and configure the @steemit/steem-js library - browser usage, config.set, api.setUrl, setOptions, multiple API instances, JSON-RPC routing and end-to-end usage examples. +--- + +# steem-js: Getting Started + +[steem-js](https://github.com/steemit/steem-js) is the official JavaScript/TypeScript library for the Steem blockchain (npm package `@steemit/steem-js`, currently at version 1.2.4). This tutorial walks through installation, configuration and everyday usage patterns, migrated from the library's own documentation. + +> **v1.0.16+:** Most `steem.api` read helpers call **`condenser_api`** on the node; see [API routing](#api-routing) for namespaces, removed methods, and modern `database_api` `list_*` / `find_*` usage. + +In this guide: + +- [Installation](#installation) and [Browser Usage](#browser-usage) +- [Configuration](#configuration) - `steem.config.set()`, `steem.api.setUrl()`, `steem.api.setOptions()` and multiple API instances +- [JSON-RPC](#json-rpc) overview and [API routing](#api-routing) +- [Usage Examples](#usage-examples), [TypeScript Support](#typescript-support), [Error Handling](#error-handling) and [Security Notes](#security-notes) + +Read-only API helpers are covered in [Reading chain data](/tutorials/steem-js/read-api.html); broadcasting lives in [Broadcasting operations](/tutorials/steem-js/broadcast.html); authenticated calls are described in [Signed calls and signature verification](/tutorials/steem-js/signed-calls.html). + +## Installation + +## Installation + +### Requirements + +- **Node.js**: >= 20.19.0 (required for Node.js usage) +- Modern browsers with ES6+ support (for browser usage) + +### npm / pnpm / yarn + +```bash +npm install @steemit/steem-js +# or +pnpm install @steemit/steem-js +# or +yarn add @steemit/steem-js +``` + +### Browser (CDN) + +```html + + + + + +``` + +--- + +## Browser Usage + +```html + + +``` + + +## Configuration + +## Configuration + +Default configuration works with Steem network. You can also configure it for other compatible networks. + +### Global Configuration with `steem.config.set()` + +The `steem.config.set()` method is the recommended way to configure the library. It manages both global configuration and automatically synchronizes the API singleton instance. + +#### Basic Usage + +```javascript +// Set multiple configuration options at once +steem.config.set({ + nodes: ['https://api.steemit.com'], + address_prefix: 'STM', + chain_id: '0000000000000000000000000000000000000000000000000000000000000000' +}); + +// Or set individually (key-value pair) +steem.config.set('address_prefix', 'STM'); +steem.config.set('chain_id', '0000000000000000000000000000000000000000000000000000000000000000'); +``` + +#### Configuration Options + +| Option | Type | Description | Default | +|--------|------|-------------|---------| +| `nodes` | `string[]` | Array of API node URLs. The first node is used as the primary endpoint. | `['https://api.steemit.com']` | +| `address_prefix` | `string` | Address prefix for the blockchain (e.g., 'STM' for Steem, 'TST' for testnet). | `'STM'` | +| `chain_id` | `string` | Chain ID for the blockchain network. | `'0000000000000000000000000000000000000000000000000000000000000000'` | +| `debug` | `boolean` | Enable debug logging. | `false` | +| `debug_warnings` | `boolean` | Enable debug warnings. | `false` | + +#### How `steem.config.set()` Works + +When you call `steem.config.set({ nodes: [...] })`: + +1. **Saves configuration globally**: The configuration values are stored in the global config instance, accessible via `steem.config.get()`. + +2. **Automatically updates API singleton**: The first node from the `nodes` array is extracted and used to update the `steem.api` singleton instance's URL. This ensures that all API calls using `steem.api` will use the configured endpoint. + +3. **Synchronizes state**: Both the global config and the API instance are kept in sync. + +**Example:** + +```javascript +// Configure the library +steem.config.set({ + nodes: ['https://api.steemit.com'], + address_prefix: 'STM' +}); + +// The steem.api singleton now uses 'https://api.steemit.com' as its endpoint +// All subsequent API calls will use this endpoint +steem.api.getAccountsAsync(['ety001']).then(accounts => { + console.log(accounts); +}); +``` + +#### Get Configuration + +```javascript +// Get a single configuration value +const chainId = steem.config.get('chain_id'); +const nodes = steem.config.get('nodes'); +const addressPrefix = steem.config.getString('address_prefix'); + +// Get all configuration +const allConfig = steem.config.all(); +console.log(allConfig); +// Output: { nodes: [...], address_prefix: 'STM', chain_id: '...', ... } + +// Type-safe getters +const isDebug = steem.config.getBoolean('debug'); +const maxRetries = steem.config.getNumber('max_retries'); +``` + +### Direct API Configuration + +If you need to change the API endpoint without updating the global configuration, you can use the API instance methods directly. + +#### `steem.api.setUrl(url: string)` + +Changes the API endpoint URL directly without updating the global config. This is useful when you want to temporarily switch endpoints or test different nodes. + +```javascript +// Change API endpoint directly +steem.api.setUrl('https://api.steemit.com'); + +// This only affects the steem.api singleton instance +// The global config.nodes remains unchanged +``` + +**When to use:** +- Testing different API endpoints temporarily +- Switching endpoints without updating global config +- Quick endpoint changes for debugging + +#### `steem.api.setOptions(options: ApiOptions)` + +Provides more control over API instance configuration. This method allows you to set multiple options at once, including transport type, logger, and other advanced settings. + +```javascript +// Set multiple API options +steem.api.setOptions({ + url: 'https://api.steemit.com', + transport: 'http', + logger: { + log: (...args) => console.log('[API]', ...args) + } +}); +``` + +**Available Options:** + +| Option | Type | Description | +|--------|------|-------------| +| `url` | `string` | API endpoint URL (must be HTTP/HTTPS) | +| `transport` | `string` | Transport type ('http' is the only supported value) | +| `logger` | `object` | Logger object with a `log` method | +| `useTestNet` | `boolean` | Enable testnet mode (sets address_prefix to 'TST') | +| `fetchMethod` | `function` | Custom fetch implementation for HTTP requests | + +**Example with logger:** + +```javascript +steem.api.setOptions({ + url: 'https://api.steemit.com', + logger: { + log: (level, ...args) => { + if (level === 'error') { + console.error('[Steem API]', ...args); + } else { + console.log('[Steem API]', level, ...args); + } + } + } +}); +``` + +#### Differences: `steem.config.set()` vs `steem.api.setUrl()` + +| Method | Updates Global Config | Updates API Singleton | Use Case | +|--------|----------------------|---------------------|----------| +| `steem.config.set({ nodes: [...] })` | ✅ Yes | ✅ Yes (automatically) | Recommended for normal use. Sets both config and API endpoint. | +| `steem.api.setUrl(url)` | ❌ No | ✅ Yes | Quick endpoint change without affecting config. | +| `steem.api.setOptions(options)` | ❌ No | ✅ Yes | Advanced configuration with transport, logger, etc. | + +**Best Practice:** + +- **Use `steem.config.set()`** for initial setup and when you want to keep config and API in sync. +- **Use `steem.api.setUrl()`** for temporary endpoint changes or testing. +- **Use `steem.api.setOptions()`** when you need advanced configuration like custom loggers. + +### Multiple API Instances + +By default, `steem.api` is a singleton instance that's shared across your application. However, you can create multiple independent API instances using the `Api` class constructor. This is useful when you need to: + +- Connect to multiple different API endpoints simultaneously +- Isolate API calls for different purposes +- Test different configurations without affecting the global instance + +#### Creating Multiple Instances + +```javascript +// ESM import (Node.js or modern browsers) +import { Api } from '@steemit/steem-js'; + +// CommonJS (Node.js) +const { Api } = require('@steemit/steem-js'); + +// UMD (Browser) +// After loading the UMD script, Api is available on the steem object +const Api = steem.Api; + +// Create independent API instances +const api1 = new Api({ url: 'https://api.steemit.com' }); +const api2 = new Api({ url: 'https://api.steemit.com' }); + +// Each instance operates independently +api1.getAccountsAsync(['ety001']).then(accounts => { + console.log('From instance 1:', accounts); +}); + +api2.getAccountsAsync(['ety001']).then(accounts => { + console.log('From instance 2:', accounts); +``` +}); + +#### Complete Example: Multiple Instances with Different Configurations + +```javascript +import { Api } from '@steemit/steem-js'; + +// Create API instances for different purposes +const api1 = new Api({ + url: 'https://api.steemit.com', + logger: { + log: (...args) => console.log('[API Instance 1]', ...args) + } +}); + +const api2 = new Api({ + url: 'https://api.steemit.com', + logger: { + log: (...args) => console.log('[API Instance 2]', ...args) + } +}); + +// Use them independently +async function getAccounts() { + try { + // Query with first instance + const accounts1 = await api1.getAccountsAsync(['ety001']); + console.log('From instance 1:', accounts1[0]); + + // Query with second instance + const accounts2 = await api2.getAccountsAsync(['ety001']); + console.log('From instance 2:', accounts2[0]); + } catch (error) { + console.error('Error:', error); + } +} + +getAccounts(); +``` + +#### Example: Using Multiple Instances + +```javascript +import { Api } from '@steemit/steem-js'; + +// Create multiple instances (all using the same endpoint) +const api1 = new Api({ url: 'https://api.steemit.com' }); +const api2 = new Api({ url: 'https://api.steemit.com' }); + +// Use different instances for different requests +async function getAccount(username) { + try { + const accounts = await api1.getAccountsAsync([username]); + return accounts[0]; + } catch (error) { + console.warn('First instance failed, trying second...', error); + // Fallback to second instance + const accounts = await api2.getAccountsAsync([username]); + return accounts[0]; + } +} + +// Usage +getAccount('ety001').then(account => { + console.log('Account:', account); +}); +``` + +#### Important Notes about Multiple Instances + +1. **Independent Configuration**: Each `Api` instance has its own configuration and doesn't affect the global `steem.config` or the `steem.api` singleton. + +2. **No Automatic Sync**: Changes to `steem.config.set()` will NOT affect instances created with `new Api()`. You need to call `setOptions()` or `setUrl()` on each instance individually. + +3. **Memory Considerations**: Each instance maintains its own transport connection and state. Creating many instances may increase memory usage. + +4. **Broadcast Module**: The `steem.broadcast` module uses the `steem.api` singleton by default. If you want to use a custom API instance with broadcast, you'll need to pass it explicitly or modify the broadcast module's API reference. + +**Example: Using Custom API Instance with Broadcast** + +```javascript +import { Api } from '@steemit/steem-js'; +import { broadcast } from '@steemit/steem-js'; + +// Create a custom API instance +const customApi = new Api({ url: 'https://api.steemit.com' }); + +// Note: The broadcast module uses steem.api singleton by default +// To use a custom instance, you would need to modify the broadcast module +// or create a wrapper that uses your custom API instance +``` + + +## JSON-RPC + +## JSON-RPC + +Activate JSON-RPC transport: + +```javascript +steem.config.set({ nodes: ['https://api.steemit.com'] }); +``` + +Authenticated RPC deserves its own chapter: `steem.api.signedCall` (and its Promise flavour `signedCallAsync`) sign requests with your private key, and the library ships a full signature-verification toolkit. Both topics - including the complete example guides - live on the [Signed calls and signature verification](/tutorials/steem-js/signed-calls.html) page. + +## API routing + +## API routing + +Steem nodes expose multiple JSON-RPC plugin namespaces. steem-js maps each `steem.api.*` helper to a namespace in `src/api/methods.ts`. + +### How requests are sent + +| Style | Example | Wire format (HTTP) | +|-------|---------|-------------------| +| Generated helper | `steem.api.getAccountsAsync(['ned'])` | JSON-RPC `call` with `['condenser_api', 'get_accounts', [['ned']]]` | +| Explicit namespace | `steem.api.call('condenser_api.get_accounts', [['ned']])` | JSON-RPC method `condenser_api.get_accounts` | + +As of **v1.0.16**, legacy read helpers (`get_accounts`, `get_content`, discussions, witnesses, …) use **`condenser_api`**, matching current [steem](https://github.com/steemit/steem) full nodes. Methods that remain on the modern **`database_api`** plugin include `get_config`, `get_dynamic_global_properties`, `get_transaction_hex`, `get_required_signatures`, `get_potential_signatures`, `verify_authority`, `verify_account_authority`, `get_order_book`, `get_witness_schedule`, `get_active_witnesses`, `get_feed_history`, and `find_change_recovery_account_requests`. + +### Modern `database_api` (`list_*` / `find_*`) + +The node's native `database_api` plugin uses different method names and object-shaped parameters (e.g. `database_api.find_accounts` with `{ accounts: ['user'] }`). Those are **not** exposed as camelCase helpers; call them with: + +```javascript +await steem.api.callAsync('database_api.find_accounts', [{ accounts: ['initminer'] }]); +``` + +### Removed helpers (v1.0.16) + +These `steem.api.*` methods were removed from the library because they are not implemented on current Steem nodes: + +- WebSocket subscriptions: `setSubscribeCallback`, `setPendingTransactionCallback`, `setBlockAppliedCallback`, `cancelAllSubscriptions` +- Categories: `getTrendingCategories`, `getBestCategories`, `getActiveCategories`, `getRecentCategories` +- Discussions: `getDiscussionsByTrending30`, `getDiscussionsByPayout` +- Account: `getAccountNotifications`, `getAccountReputation`, `getAccountBandwidth`, `getAccountBandwidthByType`, `getAccountBandwidthByTypeAndTime` +- Market / mining: `getLiquidityQueue`, `getMinerQueue` +- Escrow: `getEscrowByFrom`, `getEscrowByTo`, `getEscrowByAgent` +- Proposed transactions: `getProposedTransactions`, `getProposedTransaction`, and related `getProposedTransactionApprovals*` variants + +Use `getEscrow` / `condenser_api` or `database_api.list_escrows` / `find_escrows` where applicable. + +## Usage Examples + +## Usage Examples + +### Basic Usage + +```javascript +import { steem } from '@steemit/steem-js'; + +// Configure API endpoint +steem.config.set({ + nodes: ['https://api.steemit.com'], + address_prefix: 'STM', + chain_id: '0000000000000000000000000000000000000000000000000000000000000000' +}); + +// Get account information +const account = await steem.api.getAccountsAsync(['ned']); +console.log(account); + +// Generate keys +const keys = steem.auth.generateKeys('username', 'password', ['owner', 'active', 'posting', 'memo']); +console.log(keys); +``` + +### Voting Example + +```javascript +// Vote on a post +const postingWif = steem.auth.toWif('username', 'password', 'posting'); +await steem.broadcast.voteAsync( + postingWif, + 'voter', + 'author', + 'permlink', + 10000 // weight +); +``` + +### Transfer Example + +```javascript +// Transfer STEEM +const activeWif = steem.auth.toWif('username', 'password', 'active'); +await steem.broadcast.transferAsync( + activeWif, + 'from', + 'to', + '1.000 STEEM', + 'memo' +); +``` + +### Publishing Post Example + +```javascript +// Publish new post +const postingWif = steem.auth.toWif('username', 'password', 'posting'); +await steem.broadcast.commentAsync( + postingWif, + '', // parentAuthor (empty string means main post) + 'general', // parentPermlink (category) + 'author', + 'my-post-permlink', + 'My Post Title', + 'This is the body of my post.', + JSON.stringify({ + tags: ['general', 'blog'], + app: 'my-app/1.0' + }) +); +``` + +--- + +## Error Handling + +All async methods will throw errors and should be handled appropriately: + +```javascript +try { + const account = await steem.api.getAccountsAsync(['nonexistent']); + console.log(account); +} catch (error) { + console.error('Error fetching account:', error.message); +} + +// Or using Promise catch +steem.api.getAccountsAsync(['nonexistent']) + .then(account => console.log(account)) + .catch(error => console.error('Error:', error.message)); +``` + +--- + +## Security Notes + +- Private keys are never logged or exposed +- Uses cryptographically secure random number generation +- All cryptographic operations use proper implementations +- Always verify transaction parameters in production +- Never hardcode private keys in client-side code + + +## TypeScript Support + +## TypeScript Support + +Steem.js fully supports TypeScript with complete type definitions: + +```typescript +import { steem, Account, DynamicGlobalProperties } from '@steemit/steem-js'; + +// Type-safe API calls +const accounts: Account[] = await steem.api.getAccountsAsync(['ned']); +const props: DynamicGlobalProperties = await steem.api.getDynamicGlobalPropertiesAsync(); + +// Typed configuration +steem.config.set({ + nodes: ['https://api.steemit.com'], + address_prefix: 'STM' as const, + chain_id: '0000000000000000000000000000000000000000000000000000000000000000' +}); +``` + + +## Where to go next + +- [Reading chain data](/tutorials/steem-js/read-api.html) - the full read API catalogue with runnable examples. +- [Broadcasting operations](/tutorials/steem-js/broadcast.html) - every broadcast operation the library supports. +- [Signed calls and signature verification](/tutorials/steem-js/signed-calls.html) - authenticated requests and signature checks. diff --git a/docs/tutorials/steem-js/read-api.md b/docs/tutorials/steem-js/read-api.md new file mode 100644 index 0000000..80fc8bf --- /dev/null +++ b/docs/tutorials/steem-js/read-api.md @@ -0,0 +1,1280 @@ +--- +title: steem-js - Reading Chain Data +description: Full steem-js read API walkthrough - tags, blog, discussions, blocks, global properties, accounts, market, votes, content, witnesses, login, follow, authentication, formatter and utils. +--- + +# steem-js: Reading Chain Data + +This page collects the read-side examples for `steem.api`, migrated from the [steem-js](https://github.com/steemit/steem-js) documentation. Setup, configuration and usage examples live in the [getting-started tutorial](/tutorials/steem-js/index.html); broadcasting is covered in [Broadcasting operations](/tutorials/steem-js/broadcast.html). + +> Every helper below wraps a JSON-RPC method that is documented in the generated [API Reference](/api/) - for example `getAccountsAsync` corresponds to [condenser_api.get_accounts](/api/condenser_api/get_accounts.html) and `getContentAsync` to [condenser_api.get_content](/api/condenser_api/get_content.html). The demos here show the steem-js client-side patterns. + +## Read API methods + +## Read API methods + +The sections below document `steem.api` helpers for reading chain state. Unless noted, calls are routed to **`condenser_api`** on the node. + +### Tags + +#### Get Trending Tags + +Returns a list of the currently trending tags in descending order by value. + +```javascript +steem.api.getTrendingTagsAsync(afterTag, limit).then(function(result) { + console.log(result); +}); +``` + +**Parameter Description:** + +| Parameter | Description | Data Type | Notes | +|---|---|---|---| +| afterTag | The name of the last tag to begin from | String | Use the empty string `''` to start the list. Subsequent calls can use the last tag name | +| limit | The maximum number of tags to return | Integer | | + +**Call Example:** + +```javascript +steem.api.getTrendingTagsAsync('', 2).then(function(result) { + console.log(result); +}); +``` + +**Return Example:** + +```javascript +[ + { name: '', total_payouts: '37610793.383 SBD', net_votes: 4211122, top_posts: 411832, comments: 1344461, trending: '5549490701' }, + { name: 'life', total_payouts: '8722947.658 SBD', net_votes: 1498401, top_posts: 127103, comments: 54049, trending: '570954588' } +] +``` + +**Using the Result:** + +```javascript +// Extract tag names from the result into an array +const tagNames = result.map(function(item) { return item.name; }); +console.log(tagNames); + +// Get the last tag for subsequent calls +const lastKnownTag = result[result.length - 1].name; + +// Use the last known tag to get the next group of tags +steem.api.getTrendingTagsAsync(lastKnownTag, 2).then(function(result) { + console.log(result); +}); +``` + +#### Get Blog + +Gets the last `limit` number of posts of `account` before the post with index `entryId`. + +```javascript +steem.api.getBlogAsync(account, entryId, limit).then(function(data) { + console.log(data); +}); +``` + +**Parameter Description:** + +| Parameter | Data Type | Description | +|---------|--------|-----------| +| account | string | A Steem username | +| entryId | number | A positive number - the index from which to start counting (zero-based index) | +| limit | number | A positive number - the max count of posts to be returned | + +**Call Example:** + +```javascript +steem.api.getBlogAsync("username", 10, 3).then(function(data) { + console.log(data); +}); + +// In this case we get [3] posts, the newest of which is the one with index [10] +// (that's the 11th post, because post indexes are zero-based) +// This means the results will be posts [10, 9 and 8] +``` + +#### Get Blog Authors + +Gets a list of all people who wrote in someone's blog, along with how many times they wrote in that blog. + +```javascript +steem.api.getBlogAuthorsAsync(blogAccount).then(function(data) { + console.log(data); +}); +``` + +**Return Example:** + +```javascript +[ + ['username1', 1], + ['username2', 1], + ['username3', 3], + ['username4', 2], + ['username5', 1] +] +``` + +#### Get Blog Entries + +Gets the last `limit` number of posts of `account` before the post with index `entryId`. Very similar to getBlog but with much simpler result objects. + +```javascript +steem.api.getBlogEntriesAsync(account, entryId, limit).then(function(data) { + console.log(data); +}); +``` + +**Return Example:** + +```javascript +[ + { author: 'username', permlink: 'post-permlink-10', blog: 'username', reblog_on: '1970-01-01T00:00:00', entry_id: 10 }, + { author: 'username', permlink: 'post-permlink-9', blog: 'username', reblog_on: '1970-01-01T00:00:00', entry_id: 9 }, + { author: 'username', permlink: 'post-permlink-8', blog: 'username', reblog_on: '1970-01-01T00:00:00', entry_id: 8 } +] +``` + +#### Get Discussions By Trending + +Gets the Steem posts as they would be shown in the trending tab of steemit.com. + +```javascript +steem.api.getDiscussionsByTrendingAsync(query).then(function(data) { + console.log(data); +}); +``` + +**Call Example:** + +```javascript +const query = { limit: 3, tag: "steem" }; +steem.api.getDiscussionsByTrendingAsync(query).then(function(data) { + console.log(data); +}); + +// NOTE! The default limit is 0. Not setting a limit will get you an empty result. +``` + +#### Other Discussion Query Methods + +```javascript +// By created time +steem.api.getDiscussionsByCreatedAsync(query); + +// By activity +steem.api.getDiscussionsByActiveAsync(query); + +// By cashout time +steem.api.getDiscussionsByCashoutAsync(query); + +// By votes +steem.api.getDiscussionsByVotesAsync(query); + +// By children +steem.api.getDiscussionsByChildrenAsync(query); + +// By hot +steem.api.getDiscussionsByHotAsync(query); + +// By feed +steem.api.getDiscussionsByFeedAsync(query); + +// By blog +steem.api.getDiscussionsByBlogAsync(query); + +// By comments +steem.api.getDiscussionsByCommentsAsync(query); +``` + +#### Get Discussions By Promoted + +Gets the recent posts ordered by how much was spent to promote them. + +```javascript +steem.api.getDiscussionsByPromotedAsync(query).then(function(data) { + console.log(data); +}); +``` + +**Call Example:** + +```javascript +const query = { limit: 3, tag: "steem" }; +steem.api.getDiscussionsByPromotedAsync(query).then(function(data) { + console.log(data); +}); +``` + +### Blocks and Transactions + +#### Get Block Header + +```javascript +steem.api.getBlockHeaderAsync(blockNum).then(function(result) { + console.log(result); +}); +``` + +#### Get Block + +```javascript +steem.api.getBlockAsync(blockNum).then(function(result) { + console.log(result); +}); +``` + +#### Get Ops In Block + +Gets all operations in a given block. + +```javascript +steem.api.getOpsInBlockAsync(blockNum, onlyVirtual).then(function(data) { + console.log(data); +}); +``` + +**Parameter Description:** + +| Parameter | Data Type | Description | +|---------|--------|-----------| +| blockNum | number | A positive number | +| onlyVirtual | boolean | 'false' to get all operations. 'true' to only get virtual operations | + +**Call Example:** + +```javascript +steem.api.getOpsInBlockAsync(10000001, false).then(function(data) { + console.log(data); +}); +``` + +#### Get State + +Gets a lot of information about the state of `path`. + +```javascript +steem.api.getStateAsync(path).then(function(data) { + console.log(data); +}); +``` + +**Call Example:** + +```javascript +// Valid call examples: +steem.api.getStateAsync("/@username"); +steem.api.getStateAsync("/@username/permlink-of-post"); +steem.api.getStateAsync("/@username/comments"); +steem.api.getStateAsync("/@username/recent-replies"); +steem.api.getStateAsync("/trending"); +steem.api.getStateAsync("/trending/collorchallenge"); +``` + +### Global Properties + +`getConfig`, `getDynamicGlobalProperties`, `getFeedHistory`, and `getWitnessSchedule` use **`database_api`** on the node. `getChainProperties`, `getHardforkVersion`, and `getNextScheduledHardfork` use **`condenser_api`**. + +#### Get Config + +```javascript +steem.api.getConfigAsync().then(function(result) { + console.log(result); +}); +``` + +#### Get Dynamic Global Properties + +```javascript +steem.api.getDynamicGlobalPropertiesAsync().then(function(result) { + console.log(result); +}); +``` + +#### Get Chain Properties + +```javascript +steem.api.getChainPropertiesAsync().then(function(result) { + console.log(result); +}); +``` + +#### Get Feed Entries + +Gets the posts in the feed of a user. The feed displays posts of followed users, as well as what they resteemed. + +```javascript +steem.api.getFeedEntriesAsync(account, entryId, limit).then(function(data) { + console.log(data); +}); +``` + +**Parameter Description:** + +| Parameter | Data Type | Description | +|---------|--------|-----------| +| account | string | A Steem username | +| entryId | number | The post ID from which to start counting. Write '0' to start from newest post | +| limit | number | A positive number | + +**Return Example:** + +```javascript +[ + { author: 'otherusername', permlink: 'permlink', reblog_by: ['resteembot'], reblog_on: '2018-02-11T18:42:54', entry_id: 10260 }, + { author: 'otherusername', permlink: 'permlink', reblog_by: [], reblog_on: '2018-02-11T18:39:24', entry_id: 10259 } +] +``` + +#### Get Feed History + +```javascript +steem.api.getFeedHistoryAsync().then(function(result) { + console.log(result); +}); +``` + +#### Get Current Median History Price + +```javascript +steem.api.getCurrentMedianHistoryPriceAsync().then(function(result) { + console.log(result); +}); +``` + +#### Get Ticker + +Gets the latest summarized data from the Steem market. + +```javascript +steem.api.getTickerAsync().then(function(data) { + console.log(data); +}); +``` + +**Return Example:** + +```javascript +{ + latest: '0.89732142857142860', + lowest_ask: '0.89684014869888484', + highest_bid: '0.89600000000000002', + percent_change: '-14.56712923228768730', + steem_volume: '7397.697 STEEM', + sbd_volume: '6662.316 SBD' +} +``` + +#### Get Trade History + +Gets the trade history for a given period between a `start` date and an `end` date. + +```javascript +steem.api.getTradeHistoryAsync(start, end, limit).then(function(data) { + console.log(data); +}); +``` + +**Parameter Description:** + +| Parameter | Data Type | Description | +|---------|--------|-----------| +| start | string | Datetime string in the format "2018-01-01T00:00:00" | +| end | string | Datetime string in the format "2018-01-01T00:00:00" | +| limit | number | A positive number | + +**Call Example:** + +```javascript +const start = "2018-01-01T00:00:00"; +const end = "2018-01-02T00:00:00"; + +steem.api.getTradeHistoryAsync(start, end, 5).then(function(data) { + console.log(data); +}); +``` + +#### Get Version + +Gets the version of the Steem blockchain you are connected to. + +```javascript +steem.api.getVersionAsync().then(function(data) { + console.log(data); +}); +``` + +**Return Example:** + +```javascript +{ + blockchain_version: '0.19.2', + steem_revision: '07be64314ce9d277eb7da921b459c993c2e2412c', + fc_revision: '8dd1fd1ec0906509eb722fa7c8d280d59bcca23d' +} +``` + +#### Get Volume + +Gets the Steem and Steem Dollar volumes. + +```javascript +steem.api.getVolumeAsync().then(function(data) { + console.log(data); +}); +``` + +**Return Example:** + +```javascript +{ + steem_volume: '8101.888 STEEM', + sbd_volume: '7287.268 SBD' +} +``` + +#### Get Hardfork Version + +Gets the current hardfork version of the STEEM blockchain. + +```javascript +steem.api.getHardforkVersionAsync().then(function(result) { + console.log(result); // '0.19.0' +}); +``` + +#### Get Next Scheduled Hardfork + +```javascript +steem.api.getNextScheduledHardforkAsync().then(function(result) { + console.log(result); +}); +``` + +#### Get Reward Fund + +```javascript +steem.api.getRewardFundAsync(name).then(function(result) { + console.log(result); +}); +``` + +#### Get Vesting Delegations + +Returns a list of delegations made from one `account`. Denominated in VESTS. + +```javascript +steem.api.getVestingDelegationsAsync(account, from, limit).then(function(result) { + console.log(result); +}); +``` + +**Parameter Description:** + +| Parameter | Description | Data Type | Notes | +|---|---|---|---| +| account | Account who is making the delegations | String | | +| from | The name of the last account to begin from | String | Use the empty string `''` to start the list. Subsequent calls can use the last delegatee's account name | +| limit | The maximum number of delegation records to return | Integer | | + +**Call Example:** + +```javascript +steem.api.getVestingDelegationsAsync('ned', '', 2).then(function(result) { + console.log(result); +}); +``` + +**Return Example:** + +```javascript +[ + { id: 498422, delegator: 'ned', delegatee: 'spaminator', vesting_shares: '409517519.233783 VESTS', min_delegation_time: '2018-01-16T19:30:36' }, + { id: 181809, delegator: 'ned', delegatee: 'surpassinggoogle', vesting_shares: '1029059275.000000 VESTS', min_delegation_time: '2017-08-08T15:25:15' } +] +``` + +### Keys + +#### Get Key References + +```javascript +steem.api.getKeyReferencesAsync(key).then(function(result) { + console.log(result); +}); +``` + +### Accounts + +#### Get Accounts + +Gets multiple accounts by their names. + +```javascript +steem.api.getAccountsAsync(names).then(function(result) { + console.log(result); +}); +``` + +**Parameter Description:** + +| Parameter | Data Type | Description | +|---------|--------|-----------| +| names | array | Array of account names (strings) | + +**Call Example:** + +```javascript +steem.api.getAccountsAsync(['ned', 'dan']).then(function(accounts) { + console.log(accounts); +}); +``` + +**Note:** To get a single account, pass an array with one name: `getAccountsAsync(['username'])` and access the first element of the result. + +#### Get Account References + +```javascript +steem.api.getAccountReferencesAsync(accountId).then(function(result) { + console.log(result); +}); +``` + +#### Lookup Account Names + +```javascript +steem.api.lookupAccountNamesAsync(accountNames).then(function(result) { + console.log(result); +}); +``` + +#### Lookup Accounts + +```javascript +steem.api.lookupAccountsAsync(lowerBoundName, limit).then(function(result) { + console.log(result); +}); +``` + +#### Get Account Count + +```javascript +steem.api.getAccountCountAsync().then(function(result) { + console.log(result); +}); +``` + +#### Get Conversion Requests + +```javascript +steem.api.getConversionRequestsAsync(accountName).then(function(result) { + console.log(result); +}); +``` + +#### Get Account History + +```javascript +steem.api.getAccountHistoryAsync(account, from, limit).then(function(result) { + console.log(result); +}); +``` + +**Signed Version (for private account data):** + +```javascript +// For accessing private or authenticated account data +const privateKey = steem.auth.toWif('username', 'password', 'active'); + +steem.api.signedCall( + 'condenser_api.get_account_history', + ['username', -1, 100], + 'username', + privateKey, + function(err, result) { + if (err) { + console.error('Error:', err); + } else { + console.log('Private account history:', result); + } + } +); +``` + +#### Get Owner History + +```javascript +steem.api.getOwnerHistoryAsync(account).then(function(result) { + console.log(result); +}); +``` + +#### Get Recovery Request + +```javascript +steem.api.getRecoveryRequestAsync(account).then(function(result) { + console.log(result); +}); +``` + +#### Get Account Reputations + +Gets the reputation points of `limit` accounts with names most similar to `lowerBoundName`. + +```javascript +steem.api.getAccountReputationsAsync(lowerBoundName, limit).then(function(data) { + console.log(data); +}); +``` + +**Return Example:** + +```javascript +[ + { account: 'username', reputation: '26727073581' }, + { account: 'username-taken', reputation: 0 } +] +``` + +### Market + +#### Get Order Book + +```javascript +steem.api.getOrderBookAsync(limit).then(function(result) { + console.log(result); +}); +``` + +#### Get Market Order Book + +Takes the top-most `limit` entries in the market order book for both buy and sell orders. + +```javascript +steem.api.getMarketOrderBookAsync(limit).then(function(data) { + console.log(data); +}); +``` + +**Return Example:** + +```javascript +{ + bids: [ + { price: '0.91116173120728938', steem: 2195, sbd: 2000 }, + { price: '0.91089965397923878', steem: 1156, sbd: 1053 } + ], + asks: [ + { price: '0.91145625249700357', steem: 9053, sbd: 8251 }, + { price: '0.91159226975214813', steem: 16184, sbd: 14753 } + ] +} +``` + +#### Get Open Orders + +```javascript +steem.api.getOpenOrdersAsync(owner).then(function(result) { + console.log(result); +}); +``` + +`getOrderBook` uses **`database_api`** on the node; `getMarketOrderBook` uses **`market_history_api`**. + +#### Get Market History Buckets + +```javascript +steem.api.getMarketHistoryBucketsAsync().then(function(data) { + console.log(data); // [15, 60, 300, 3600, 86400] +}); +``` + +### Authority / Validation + +#### Get Transaction Hex + +```javascript +steem.api.getTransactionHexAsync(trx).then(function(result) { + console.log(result); +}); +``` + +#### Get Transaction + +```javascript +steem.api.getTransactionAsync(trxId).then(function(result) { + console.log(result); +}); +``` + +#### Get Required Signatures + +```javascript +steem.api.getRequiredSignaturesAsync(trx, availableKeys).then(function(result) { + console.log(result); +}); +``` + +#### Get Potential Signatures + +```javascript +steem.api.getPotentialSignaturesAsync(trx).then(function(result) { + console.log(result); +}); +``` + +#### Verify Authority + +Uses **`database_api`** on the node. + +```javascript +steem.api.verifyAuthorityAsync(trx).then(function(result) { + console.log(result); +}); +``` + +#### Verify Account Authority + +Uses **`database_api`** on the node. + +```javascript +steem.api.verifyAccountAuthorityAsync(nameOrId, signers).then(function(result) { + console.log(result); +}); +``` + +#### Get Tags Used By Author + +Gets tags used by a Steem user. Most users have no tags yet, but some do. + +```javascript +steem.api.getTagsUsedByAuthorAsync(author).then(function(data) { + console.log(data); +}); +``` + +**Call Example:** + +```javascript +steem.api.getTagsUsedByAuthorAsync("good-karma").then(function(data) { + console.log(data); // [['challenge', 0]] +}); +``` + +### Votes + +#### Get Active Votes + +```javascript +steem.api.getActiveVotesAsync(author, permlink).then(function(result) { + console.log(result); +}); +``` + +#### Get Account Votes + +```javascript +steem.api.getAccountVotesAsync(voter).then(function(result) { + console.log(result); +}); +``` + +### Content + +#### Get Content + +```javascript +steem.api.getContentAsync(author, permlink).then(function(result) { + console.log(result); +}); +``` + +#### Get Content Replies + +```javascript +steem.api.getContentRepliesAsync(author, permlink).then(function(result) { + console.log(result); +}); +``` + +#### Get Discussions By Author Before Date + +```javascript +steem.api.getDiscussionsByAuthorBeforeDateAsync(author, startPermlink, beforeDate, limit).then(function(result) { + console.log(result); +}); +``` + +#### Get Reblogged By + +Gives a list of the users that reblogged (resteemed) a given post. + +```javascript +steem.api.getRebloggedByAsync(author, permlink).then(function(data) { + console.log(data); +}); +``` + +**Return Example:** + +```javascript +['author', 'user1', 'user2', 'user3', 'user4'] +``` + +#### Get Replies By Last Update + +```javascript +steem.api.getRepliesByLastUpdateAsync(startAuthor, startPermlink, limit).then(function(result) { + console.log(result); +}); +``` + +### Witnesses + +#### Get Witnesses + +```javascript +steem.api.getWitnessesAsync(witnessIds).then(function(result) { + console.log(result); +}); +``` + +#### Get Witness By Account + +Returns information about a witness with the given `accountName`. + +```javascript +steem.api.getWitnessByAccountAsync(accountName).then(function(result) { + console.log(result); +}); +``` + +#### Get Witnesses By Vote + +```javascript +steem.api.getWitnessesByVoteAsync(from, limit).then(function(result) { + console.log(result); +}); +``` + +#### Lookup Witness Accounts + +```javascript +steem.api.lookupWitnessAccountsAsync(lowerBoundName, limit).then(function(result) { + console.log(result); +}); +``` + +#### Get Witness Count + +```javascript +steem.api.getWitnessCountAsync().then(function(result) { + console.log(result); +}); +``` + +#### Get Active Witnesses + +```javascript +steem.api.getActiveWitnessesAsync().then(function(result) { + console.log(result); +}); +``` + +#### Get Witness Schedule + +Gets some general information about the witnesses. + +```javascript +steem.api.getWitnessScheduleAsync().then(function(data) { + console.log(data); +}); +``` + +**Return Example:** + +```javascript +{ + id: 0, + current_virtual_time: '292589412128104496649868821', + next_shuffle_block_num: 19756485, + current_shuffled_witnesses: '31797..................00000000', + num_scheduled_witnesses: 21, + top19_weight: 1, + timeshare_weight: 5, + miner_weight: 1, + witness_pay_normalization_factor: 25, + median_props: { + account_creation_fee: '0.100 STEEM', + maximum_block_size: 65536, + sbd_interest_rate: 0 + }, + majority_version: '0.19.2', + max_voted_witnesses: 20, + max_miner_witnesses: 0, + max_runner_witnesses: 1, + hardfork_required_witnesses: 17 +} +``` + +## Login API + +## Login API + +### Login + +⚠️ **It's not safe** to use this method with your username and password. This method always returns `true` and is only used internally with empty values to enable broadcast. + +```javascript +steem.api.loginAsync('', '').then(function(result) { + console.log(result); +}); +``` + +### Get Api By Name + +```javascript +steem.api.getApiByNameAsync(apiName).then(function(result) { + console.log(result); +}); +``` + +--- + +## Follow API + +The follower API queries information about follow relationships between accounts. The API is read-only and does not create changes on the blockchain. + +### Get Followers + +Returns an alphabetical ordered array of the accounts that are following a particular account. + +```javascript +steem.api.getFollowersAsync(following, startFollower, followType, limit).then(function(result) { + console.log(result); +}); +``` + +**Parameter Description:** + +| Parameter | Description | Data Type | Notes | +|---|---|---|---| +| following | The followers of which account | String | No leading @ symbol | +| startFollower | Start the list from which follower? | String | No leading @ symbol. Use the empty string `''` to start the list. Subsequent calls can use the name of the last follower | +| followType | ?? | ?? | Set to 0 or 'blog' - either works | +| limit | The maximum number of followers to return | Integer | | + +**Call Example:** + +```javascript +steem.api.getFollowersAsync('ned', '', 'blog', 2).then(function(result) { + console.log(result); +}); +``` + +**Return Example:** + +```javascript +[ + { follower: 'a-0-0', following: 'ned', what: ['blog'] }, + { follower: 'a-0-0-0-1abokina', following: 'ned', what: ['blog'] } +] +``` + +### Get Following + +Returns an alphabetical ordered Array of the accounts that are followed by a particular account. + +```javascript +steem.api.getFollowingAsync(follower, startFollowing, followType, limit).then(function(result) { + console.log(result); +}); +``` + +**Return Example:** + +```javascript +[ + { follower: 'dan', following: 'dantheman', what: ['blog'] }, + { follower: 'dan', following: 'krnel', what: ['blog'] } +] +``` + +### Get Follow Count + +```javascript +steem.api.getFollowCountAsync(account).then(function(result) { + console.log(result); +}); +``` + +**Return Example:** + +```javascript +{ account: 'ned', follower_count: 16790, following_count: 913 } +``` + +## Authentication + +## Authentication + +### Verify + +```javascript +steem.auth.verify(name, password, auths); +``` + +### Generate Keys + +```javascript +steem.auth.generateKeys(name, password, roles); +``` + +### Get Private Keys + +```javascript +steem.auth.getPrivateKeys(name, password, roles); +``` + +### Is Wif + +```javascript +steem.auth.isWif(privWif); +``` + +### To Wif + +```javascript +steem.auth.toWif(name, password, role); +``` + +### Wif Is Valid + +```javascript +steem.auth.wifIsValid(privWif, pubWif); +``` + +### Wif To Public + +```javascript +steem.auth.wifToPublic(privWif); +``` + +### Sign Transaction + +Signs a transaction with the provided private keys. The signature is computed +over the digest `sha256(chain_id ‖ serializeTransaction(normalizedTrx))`, where +`chain_id` comes from the configured chain (default all-zero for mainnet). + +- **`trx`** — transaction object: `ref_block_num`, `ref_block_prefix`, + `expiration`, `operations` (array of `[opType, opData]`), and `extensions`. +- **`keys`** — array of WIF private keys used to sign. +- Returns a transaction object with a `signatures` array appended. + +```javascript +const wif = '5JLw5dgQAx6rhZEgNN5C2ds1V47RweGshynFSWFbaMohsYsBvE8'; +const tx = { + ref_block_num: 123, + ref_block_prefix: 456789, + expiration: '2026-07-10T00:00:00', + operations: [['transfer', { + from: 'alice', to: 'bob', amount: '1.000 STEEM', memo: '' + }]], + extensions: [], +}; + +const signedTx = steem.auth.signTransaction(tx, [wif]); +console.log(signedTx.signatures); // ['1f23...'] (hex signatures) +``` + +> **Note:** the `signatures` field is **not** part of the signed digest. Signing +> serializes the transaction *before* attaching signatures, so the digest covers +> only the unsigned transaction body. + +### Verify Transaction + +Verifies that a signed transaction's signatures were produced by the given +public key. The digest is reconstructed exactly as `signTransaction` computes +it: `sha256(chain_id ‖ serializeTransaction(normalizedTrx))`. Returns `true` if +any signature is valid for `publicKey`, otherwise `false`. + +- **`transaction`** — a signed transaction object (must contain a `signatures` + array). The `signatures` field is stripped before digest calculation, so it + does not matter how many signatures are present. +- **`publicKey`** — the `STM…` public key to verify against. +- Returns `boolean`. + +```javascript +const publicKey = steem.auth.wifToPublic(wif); + +// Round-trip: a correctly-signed tx verifies against its signing key +const isValid = steem.auth.verifyTransaction(signedTx, publicKey); +console.log(isValid); // true + +// A different public key is rejected +const wrongPub = steem.auth.wifToPublic('5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3'); +console.log(steem.auth.verifyTransaction(signedTx, wrongPub)); // false +``` + +> **Security use case:** a relay/wallet server can call `verifyTransaction` on a +> client-submitted transaction to prove — *before* forwarding it to the chain — +> that it was signed by a key belonging to the claimed account. This closes a +> defense-in-depth gap where the server previously could only check transaction +> shape, not cryptographic authenticity. + +### Serialize Transaction + +Serializes a transaction to its **binary** form (FC-style), returning a `Buffer`. +This is the same serializer used internally by `signTransaction`, so the output +matches the Steem node's transaction wire format byte-for-byte. Downstream apps +can use it to reconstruct the signing digest themselves. + +- **`trx`** — transaction object (same shape as `signTransaction`'s `trx`). +- Returns `Buffer`. + +```javascript +import { sha256 } from '@noble/hashes/sha2'; + +// Build the exact digest signTransaction signs over: +const buf = steem.auth.serializeTransaction(tx); // Buffer +const chainId = Buffer.alloc(32, 0); // mainnet chain_id (all-zero) +const digest = Buffer.from(sha256(Buffer.concat([chainId, buf]))); +console.log(digest.toString('hex')); // 32-byte digest +``` + +## Formatter + +## Formatter + +### Amount + +Formats number and currency to the valid way for sending (for example - it trims the number's floating point remainder to 3 digits only). + +```javascript +steem.formatter.amount(_amount, asset); +``` + +**Parameter Description:** + +| Parameter | Data Type | Description | +|---------|--------|-----------| +| _amount | number | A positive number | +| asset | string | The name of a Steem asset (steem, sbd) | + +**Call Example:** + +```javascript +steem.formatter.amount(53.442346, "STEEM"); // "53.442 STEEM" +``` + +### Vesting Steem + +Converts the vests of `account` into the number of Steem they represent. + +```javascript +steem.formatter.vestingSteem(account, gprops); +``` + +**Call Example:** + +```javascript +steem.api.getAccountsAsync(["username"]).then(function(accounts) { + steem.api.getStateAsync("/@username").then(function(state) { + const vestingSteem = steem.formatter.vestingSteem(accounts[0], state.props); + console.log(vestingSteem); // 7.42431235 + }); +}); +``` + +### Number With Commas + +Formats a big number, by adding a comma on every 3 digits. Attention - only works on strings. No numbers can be passed directly. + +```javascript +steem.formatter.numberWithCommas(x); +``` + +**Call Example:** + +```javascript +steem.formatter.numberWithCommas("53304432342.432"); // "53,304,432,342.432" +``` + +### Estimate Account Value + +Gets the estimated dollar value of the assets of `account`. + +```javascript +steem.formatter.estimateAccountValue(account).then(function(data) { + console.log(data); // 32.25 +}); +``` + +### Create Suggested Password + +```javascript +const password = steem.formatter.createSuggestedPassword(); +console.log(password); // 'GAz3GYFvvQvgm7t2fQmwMDuXEzDqTzn9' +``` + +### Comment Permlink + +```javascript +const parentAuthor = 'ned'; +const parentPermlink = 'a-selfie'; +const commentPermlink = steem.formatter.commentPermlink(parentAuthor, parentPermlink); +console.log(commentPermlink); // 're-ned-a-selfie-20170621t080403765z' +``` + +### Reputation + +```javascript +const reputation = steem.formatter.reputation(3512485230915); +console.log(reputation); // 56 +``` + +### Vest To Steem + +```javascript +const steemPower = steem.formatter.vestToSteem(vestingShares, totalVestingShares, totalVestingFundSteem); +console.log(steemPower); +``` + + +## Utils + +## Utils + +### Validate Username + +```javascript +const isValidUsername = steem.utils.validateAccountName('test1234'); +console.log(isValidUsername); // null + +const isValidUsername2 = steem.utils.validateAccountName('a1'); +console.log(isValidUsername2); // 'Account name should be longer.' +``` + +### Camel Case + +Formats a string with '_' characters to follow the CamelCase notation instead. + +```javascript +steem.utils.camelCase(str); +``` + +**Call Example:** + +```javascript +steem.utils.camelCase("example_string"); // "exampleString" +``` + +## Where to go next + +- To modify chain state, see [Broadcasting operations](/tutorials/steem-js/broadcast.html). +- For authenticated reads and signature verification, see [Signed calls and signature verification](/tutorials/steem-js/signed-calls.html). +- For installation and configuration, return to the [getting-started tutorial](/tutorials/steem-js/index.html). diff --git a/docs/tutorials/steem-js/rpc-auth-migration.md b/docs/tutorials/steem-js/rpc-auth-migration.md new file mode 100644 index 0000000..ae38adc --- /dev/null +++ b/docs/tutorials/steem-js/rpc-auth-migration.md @@ -0,0 +1,216 @@ +# RPC Auth Test Migration + +## Overview + +This document describes the migration of tests from the `@steemit/rpc-auth` package to `steem-js` v1.0.11. + +## Migration Details + +### Source +- **Original Package**: `@steemit/rpc-auth` v1.1.1 +- **Source Location**: the local `rpc-auth` repository checkout +- **Original Test File**: `test/index.ts` +- **Test Framework**: Mocha + +### Destination +- **Target Package**: `@steemit/steem-js` v1.0.11 +- **Target Location**: the local `steem-js` repository checkout +- **New Test File**: `test/rpc-auth.test.ts` +- **Test Framework**: Vitest + +## Changes Made + +### 1. Test Framework Migration + +**From Mocha:** +```typescript +import 'mocha' +import * as assert from 'assert' + +describe('rpc auth', function() { + it('signs and validates', async function() { + assert.equal(...) + }) +}) +``` + +**To Vitest:** +```typescript +import { describe, it, expect } from 'vitest' + +describe('RPC Auth', () => { + it('should sign and validate a request', async () => { + expect(...).toBe(...) + }) +}) +``` + +### 2. Dependency Updates + +**Removed:** +- `dsteem` (old steem-js library) +- `node-fetch` (for testnet account creation) +- Mocha-specific utilities + +**Replaced with:** +- `steem-js` own API (`steem.auth`, `steem.api`) +- Native `crypto.randomBytes` +- Vitest assertions + +### 3. Test Account Handling + +**Original:** +- Created testnet accounts dynamically +- Used `dsteem.Client.testnet()` +- Required network access + +**New:** +- Uses environment variables or test keys +- No dynamic account creation +- Can run without network (most tests) + +### 4. Verification Function + +**Original:** +```typescript +const dsteemVerify: VerifyMessage = async (message, signatures, account) => { + const opts = { hash: message, signatures, required_posting: [account] } + const rv = await client.database.call('verify_signatures', [opts]) + if (rv.valid !== true) throw new Error('Signature invalid') +} +``` + +**New:** +```typescript +const createVerifyFunction = () => { + return async (message: Buffer, signatures: string[], account: string) => { + const accounts = await api.getAccountsAsync([account]) + const postingKeys = accounts[0].posting?.key_auths?.map(k => k[0]) || [] + // Verify using steem-js Signature and PublicKey classes + } +} +``` + +## Test Coverage + +### Migrated Tests + +✅ **sign and validate** - Basic signing and validation workflow +✅ **invalid requests** - Comprehensive error handling tests: + - Invalid JSON RPC request + - Missing signed payload + - Invalid request params + - Missing account + - Invalid encoded params + - Invalid nonce (multiple cases) + - Invalid timestamp + - Expired signature + - Verification failure + +✅ **signing errors** - Error handling when signing: + - Missing params + - Empty keys array + +✅ **signature format** - Signature structure validation: + - Valid signature format + - Unique nonces + - Valid timestamps + +✅ **multiple signatures** - Support for multiple keys + +### Skipped Tests + +⏭️ **invalid signatures (integration test)** - Requires: + - Real testnet account + - Network access + - Can be enabled with `STEEM_USERNAME` and `STEEM_PASSWORD` env vars + +## Test Results + +``` +✓ test/rpc-auth.test.ts (19 tests | 1 skipped) + ✓ RPC Auth > sign and validate > should sign and validate a request + ✓ RPC Auth > invalid requests > should handle invalid JSON RPC request + ✓ RPC Auth > invalid requests > should handle missing signed payload + ✓ RPC Auth > invalid requests > should handle invalid request params + ✓ RPC Auth > invalid requests > should handle missing account + ✓ RPC Auth > invalid requests > should handle invalid encoded params + ✓ RPC Auth > invalid requests > should handle invalid nonce (not a string) + ✓ RPC Auth > invalid requests > should handle invalid nonce (wrong length) + ✓ RPC Auth > invalid requests > should handle invalid nonce (wrong format) + ✓ RPC Auth > invalid requests > should handle invalid timestamp + ✓ RPC Auth > invalid requests > should handle expired signature + ✓ RPC Auth > invalid requests > should handle verification failure + ✓ RPC Auth > signing errors > should handle invalid requests when signing + ✓ RPC Auth > signing errors > should handle empty keys array + ✓ RPC Auth > signature format > should generate valid signature format + ✓ RPC Auth > signature format > should generate unique nonces for each request + ✓ RPC Auth > signature format > should generate valid timestamps + ✓ RPC Auth > multiple signatures > should support multiple keys + ↓ RPC Auth > invalid signatures > should handle invalid signatures (integration test) +``` + +## Key Differences + +### Error Message Format + +**Original rpc-auth:** +``` +ValidationError: Verification failed (Nope) +``` + +**steem-js v1.0.11:** +``` +Error: Verification failed: Nope +``` + +The error format changed from `(message)` to `: message`, which is reflected in the tests. + +### API Changes + +1. **PrivateKey handling**: + - Original: `PrivateKey.from(key)` or `PrivateKey.fromString(key)` + - New: `PrivateKey.fromWif(key)` + +2. **Signature creation**: + - Original: `key.sign(message.buffer)` then `hexify()` + - New: `Signature.signBufferSha256(message, privateKey)` then `.toHex()` + +3. **No ValidationError class**: + - Original: Custom `ValidationError` class + - New: Standard `Error` with formatted messages + +## Running the Tests + +```bash +# Run all rpc-auth tests +pnpm test -- rpc-auth.test.ts + +# Run with coverage +pnpm test:coverage -- rpc-auth.test.ts + +# Run specific test +pnpm test -- rpc-auth.test.ts -t "should sign and validate" +``` + +## Integration Test Setup + +To run the skipped integration test, set environment variables: + +```bash +export STEEM_USERNAME="your-testnet-account" +export STEEM_PASSWORD="your-password" +pnpm test -- rpc-auth.test.ts +``` + +## Notes + +- All core functionality tests have been successfully migrated +- The test suite maintains the same coverage as the original +- Integration tests are skipped by default but can be enabled +- Tests are compatible with vitest and modern TypeScript +- No external dependencies required for most tests + +--- + + migrated from the steem-js repository documentation; the verification utilities it exercises are demonstrated in [Signed calls and signature verification](/tutorials/steem-js/signed-calls.html). diff --git a/docs/tutorials/steem-js/signed-calls.md b/docs/tutorials/steem-js/signed-calls.md new file mode 100644 index 0000000..5671727 --- /dev/null +++ b/docs/tutorials/steem-js/signed-calls.md @@ -0,0 +1,1352 @@ +--- +title: steem-js - Signed Calls and Signature Verification +description: Authenticated steem-js RPC with signedCall/signedCallAsync and the signature verification toolkit - full example guides for signed RPC requests, message signatures and transaction verification. +--- + +# steem-js: Signed Calls and Signature Verification + +Some data and operations require proving account ownership. steem-js ships two cooperating toolkits: `steem.api.signedCall` for authenticated JSON-RPC requests, and `signatureVerification` for checking signatures on the receiving side. This page merges the library's signed-call and signature-verification example guides; the read helpers they use are documented in [Reading chain data](/tutorials/steem-js/read-api.html). + +## Signed RPC Calls + +## Signed RPC Calls + +For secure RPC calls that require authentication, use `signedCall`. This method signs the request with your private key to prove ownership of the account. + +#### signedCall + +Makes a signed JSON-RPC call to the Steem blockchain. The request is cryptographically signed to authenticate the caller. This is the callback-based version. For Promise-based usage, see `signedCallAsync` below. + +```javascript +steem.api.signedCall(method, params, account, privateKey, callback); +``` + +**Parameter Description:** + +| Parameter | Data Type | Description | +|---------|--------|-----------| +| method | string | Full RPC method name (e.g. `condenser_api.get_account_history`) | +| params | array | Parameters for the RPC method | +| account | string | The account name making the request | +| privateKey | string | Private key (WIF format) for signing | +| callback | function | Callback function(err, result) | + +**Requirements:** +- Uses HTTP transport for all API calls +- Requires a valid private key in WIF format +- The account must match the private key + +**Call Example:** + +```javascript +// Configure for HTTP transport +steem.config.set({ + nodes: ['https://api.steemit.com'], + transport: 'http' +}); + +// Make a signed call +const privateKey = '5JLw5dgQAx6rhZEgNN5C2ds1V47RweGshynFSWFbaMohsYsBvE8'; +const account = 'username'; + +// Using callback style +steem.api.signedCall( + 'condenser_api.get_account_history', + [account, -1, 10], + account, + privateKey, + function(err, result) { + if (err) { + console.error('Signed call failed:', err); + } else { + console.log('Account history:', result); + } + } +); +``` + +#### signedCallAsync + +Promise-based version of `signedCall` for use with async/await syntax. + +```javascript +steem.api.signedCallAsync(method, params, account, privateKey); +``` + +**Returns:** Promise that resolves with the result or rejects with an error. + +**Promise Example:** + +```javascript +// Using signedCallAsync with async/await +try { + const result = await steem.api.signedCallAsync( + 'condenser_api.get_account_history', + ['username', -1, 10], + 'username', + privateKey + ); + console.log('Result:', result); +} catch (error) { + console.error('Error:', error); +} +``` + +**Security Notes:** +- The request includes a timestamp and nonce to prevent replay attacks +- Signatures expire after 60 seconds +- Private keys are never transmitted, only the signature +- Each request is uniquely signed with cryptographic proof + +**Use Cases:** +- Accessing private account data +- Making authenticated API calls +- Proving account ownership +- Secure communication with Steem nodes + +## Signature Verification + +For verifying signed requests and messages, Steem.js provides comprehensive verification utilities: + +```javascript +import { signatureVerification } from '@steemit/steem-js/api'; + +// Verify a signed RPC request +const getAccountKeys = signatureVerification.createApiVerificationFunction(steem.api); +const result = await signatureVerification.verifySignedRequest(signedRequest, getAccountKeys); + +if (result.valid) { + console.log('✅ Signature verified for account:', result.account); + console.log('Decoded parameters:', result.params); +} else { + console.log('❌ Verification failed:', result.error); +} + +// Verify a simple message signature +const message = 'Hello, Steem!'; +const signature = steem.auth.sign(message, privateKey); +const publicKey = steem.auth.wifToPublic(privateKey); +const isValid = signatureVerification.verifyMessageSignature(message, signature, publicKey); +``` + +**Verification Features:** +- **Signed Request Validation**: Verify complete signed RPC requests +- **Message Signature Verification**: Verify individual message signatures +- **Batch Verification**: Verify multiple requests simultaneously +- **Expiration Checking**: Automatic signature expiration validation +- **Format Validation**: Validate signature and key formats +- **Account Key Extraction**: Extract public keys from account data + +**The remainder of this page collects comprehensive signedCall and signature verification examples.** + +--- + +## signedCall Examples + +The subsections below are the complete signedCall examples from the library documentation. + +This document provides comprehensive examples for using `signedCall` in Steem.js for authenticated API requests. + +## Overview + +`signedCall` is used for making authenticated JSON-RPC calls to the Steem blockchain. It cryptographically signs requests to prove account ownership and access private or restricted data. + +Pass the full RPC method name (e.g. `condenser_api.get_account_history`). Legacy read methods use the **`condenser_api`** namespace on current nodes; see [API routing](/tutorials/steem-js/index.html#api-routing) in the getting-started tutorial. + +## Basic Setup + +```javascript +import { steem } from '@steemit/steem-js'; + +// Configure for HTTP transport (required for signedCall) +steem.config.set({ + nodes: ['https://api.steemit.com'], + transport: 'http' +}); +``` + +## Authentication Methods + +### Using Username and Password + +```javascript +// Generate private key from username/password +const username = 'your-username'; +const password = 'your-password'; +const activeKey = steem.auth.toWif(username, password, 'active'); +const postingKey = steem.auth.toWif(username, password, 'posting'); +``` + +### Using Existing Private Key + +```javascript +// Use existing WIF private key +const privateKey = '5JLw5dgQAx6rhZEgNN5C2ds1V47RweGshynFSWFbaMohsYsBvE8'; +const account = 'username'; +``` + +## Basic SignedCall Examples + +### 1. Get Account History (Authenticated) + +```javascript +function getAccountHistorySigned(account, privateKey) { + return new Promise((resolve, reject) => { + steem.api.signedCall( + 'condenser_api.get_account_history', + [account, -1, 100], + account, + privateKey, + (err, result) => { + if (err) reject(err); + else resolve(result); + } + ); + }); +} + +// Usage +const account = 'username'; +const privateKey = steem.auth.toWif(account, 'password', 'active'); + +getAccountHistorySigned(account, privateKey) + .then(history => { + console.log('Account history:', history); + }) + .catch(error => { + console.error('Error:', error); + }); +``` + +### 2. Get Private Account Information + +```javascript +async function getPrivateAccountInfo(account, privateKey) { + try { + // Get detailed account information with private data + const result = await new Promise((resolve, reject) => { + steem.api.signedCall( + 'condenser_api.get_accounts', + [[account]], + account, + privateKey, + (err, result) => { + if (err) reject(err); + else resolve(result); + } + ); + }); + + return result[0]; // Return first account + } catch (error) { + throw new Error(`Failed to get account info: ${error.message}`); + } +} + +// Usage +getPrivateAccountInfo('username', privateKey) + .then(accountInfo => { + console.log('Private account data:', { + name: accountInfo.name, + balance: accountInfo.balance, + sbd_balance: accountInfo.sbd_balance, + vesting_shares: accountInfo.vesting_shares + }); + }); +``` + +### 3. Access Witness Information (Authenticated) + +```javascript +function getWitnessInfoSigned(witnessAccount, privateKey) { + return new Promise((resolve, reject) => { + steem.api.signedCall( + 'condenser_api.get_witness_by_account', + [witnessAccount], + witnessAccount, + privateKey, + (err, result) => { + if (err) reject(err); + else resolve(result); + } + ); + }); +} + +// Usage +getWitnessInfoSigned('witness-account', privateKey) + .then(witnessInfo => { + console.log('Witness information:', witnessInfo); + }); +``` + +## Advanced Examples + +### 4. Batch Signed Requests + +```javascript +class SignedApiClient { + constructor(account, privateKey) { + this.account = account; + this.privateKey = privateKey; + } + + async call(method, params) { + return new Promise((resolve, reject) => { + steem.api.signedCall( + method, + params, + this.account, + this.privateKey, + (err, result) => { + if (err) reject(err); + else resolve(result); + } + ); + }); + } + + async getAccountHistory(limit = 100) { + return this.call('condenser_api.get_account_history', [this.account, -1, limit]); + } + + async getFollowers(limit = 100) { + return this.call('condenser_api.get_followers', [this.account, '', 'blog', limit]); + } + + async getFollowing(limit = 100) { + return this.call('condenser_api.get_following', [this.account, '', 'blog', limit]); + } +} + +// Usage +const client = new SignedApiClient('username', privateKey); + +async function getUserData() { + try { + const [history, followers, following] = await Promise.all([ + client.getAccountHistory(50), + client.getFollowers(100), + client.getFollowing(100) + ]); + + console.log('User data loaded:', { + historyCount: history.length, + followersCount: followers.length, + followingCount: following.length + }); + } catch (error) { + console.error('Failed to load user data:', error); + } +} + +getUserData(); +``` + +### 5. Error Handling and Retry Logic + +```javascript +class RobustSignedClient { + constructor(account, privateKey, maxRetries = 3) { + this.account = account; + this.privateKey = privateKey; + this.maxRetries = maxRetries; + } + + async callWithRetry(method, params, retryCount = 0) { + try { + return await this.makeSignedCall(method, params); + } catch (error) { + if (retryCount < this.maxRetries && this.isRetryableError(error)) { + console.log(`Retrying ${method}, attempt ${retryCount + 1}/${this.maxRetries}`); + await this.delay(1000 * (retryCount + 1)); // Exponential backoff + return this.callWithRetry(method, params, retryCount + 1); + } + throw error; + } + } + + makeSignedCall(method, params) { + return new Promise((resolve, reject) => { + steem.api.signedCall(method, params, this.account, this.privateKey, (err, result) => { + if (err) reject(err); + else resolve(result); + }); + }); + } + + isRetryableError(error) { + const retryableErrors = [ + 'network error', + 'timeout', + 'connection refused', + 'signature expired' + ]; + + return retryableErrors.some(errorType => + error.message.toLowerCase().includes(errorType) + ); + } + + delay(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); + } +} + +// Usage +const robustClient = new RobustSignedClient('username', privateKey); + +robustClient.callWithRetry('condenser_api.get_account_history', ['username', -1, 100]) + .then(result => console.log('Success:', result)) + .catch(error => console.error('Final error:', error)); +``` + +### 6. Validation and Security + +```javascript +class SecureSignedClient { + constructor(account, privateKey) { + this.account = account; + this.privateKey = privateKey; + this.validateCredentials(); + } + + validateCredentials() { + // Validate account name + if (!this.account || typeof this.account !== 'string') { + throw new Error('Invalid account name'); + } + + // Validate private key format + if (!steem.auth.isWif(this.privateKey)) { + throw new Error('Invalid private key format'); + } + + // Verify key matches account (optional, requires additional API call) + const publicKey = steem.auth.wifToPublic(this.privateKey); + console.log(`Using public key: ${publicKey} for account: ${this.account}`); + } + + async secureCall(method, params) { + // Additional security checks + // Prefer condenser_api.* for legacy reads; database_api.* for config/validation and list/find APIs. + if (!method.startsWith('condenser_api.') && !method.startsWith('database_api.')) { + throw new Error('Only condenser_api and database_api methods are allowed'); + } + + // Rate limiting (simple implementation) + if (this.lastCallTime && Date.now() - this.lastCallTime < 1000) { + throw new Error('Rate limit: Wait at least 1 second between calls'); + } + + this.lastCallTime = Date.now(); + + return new Promise((resolve, reject) => { + steem.api.signedCall(method, params, this.account, this.privateKey, (err, result) => { + if (err) { + console.error(`Signed call failed for ${method}:`, err.message); + reject(err); + } else { + console.log(`Signed call successful for ${method}`); + resolve(result); + } + }); + }); + } +} + +// Usage +const secureClient = new SecureSignedClient('username', privateKey); + +secureClient.secureCall('condenser_api.get_accounts', [['username']]) + .then(result => console.log('Secure result:', result)) + .catch(error => console.error('Secure error:', error)); +``` + +## Common Use Cases + +### Account Management + +```javascript +// Get comprehensive account data +async function getFullAccountData(account, privateKey) { + const client = new SignedApiClient(account, privateKey); + + const [ + accountInfo, + history, + followers, + following + ] = await Promise.all([ + client.call('condenser_api.get_accounts', [[account]]), + client.call('condenser_api.get_account_history', [account, -1, 100]), + client.call('condenser_api.get_followers', [account, '', 'blog', 1000]), + client.call('condenser_api.get_following', [account, '', 'blog', 1000]) + ]); + + return { + account: accountInfo[0], + recentActivity: history, + followers: followers, + following: following + }; +} +``` + +### Content Analysis + +```javascript +// Analyze user's content and voting patterns +async function analyzeUserActivity(account, privateKey) { + const client = new SignedApiClient(account, privateKey); + + const history = await client.call('condenser_api.get_account_history', [account, -1, 1000]); + + const analysis = { + posts: 0, + comments: 0, + votes: 0, + transfers: 0, + other: 0 + }; + + history.forEach(([, operation]) => { + const opType = operation.op[0]; + switch (opType) { + case 'comment': + if (operation.op[1].parent_author === '') { + analysis.posts++; + } else { + analysis.comments++; + } + break; + case 'vote': + analysis.votes++; + break; + case 'transfer': + analysis.transfers++; + break; + default: + analysis.other++; + } + }); + + return analysis; +} +``` + +## Error Handling + +### Common Errors and Solutions + +```javascript +function handleSignedCallError(error) { + switch (true) { + case error.message.includes('RPC methods can only be called when using http transport'): + console.error('Solution: Configure HTTP transport instead of WebSocket'); + console.log('steem.config.set({ transport: "http" });'); + break; + + case error.message.includes('Signature expired'): + console.error('Solution: Request expired, retry with fresh signature'); + break; + + case error.message.includes('Invalid private key'): + console.error('Solution: Check private key format (should be WIF)'); + break; + + case error.message.includes('Account not found'): + console.error('Solution: Verify account name is correct'); + break; + + default: + console.error('Unknown error:', error.message); + } +} + +// Usage in error handling +steem.api.signedCall(method, params, account, privateKey, (err, result) => { + if (err) { + handleSignedCallError(err); + return; + } + + console.log('Success:', result); +}); +``` + +### Using signedCallAsync (Promise-based) + +For modern async/await code, use `signedCallAsync`: + +```javascript +try { + const result = await steem.api.signedCallAsync( + 'conveyor.is_email_registered', + [{ email: 'user@example.com' }], + 'your-account', + 'your-private-key-wif' + ); + + console.log('Success:', result); +} catch (error) { + console.error('Error:', error); +} +``` + +This is equivalent to the callback version but uses Promises, making it easier to use with async/await syntax. + +## Best Practices + +1. **Always use HTTPS endpoints** for signed calls +2. **Validate private keys** before making calls +3. **Implement retry logic** for network errors +4. **Use rate limiting** to avoid overwhelming the API +5. **Handle signature expiration** gracefully +6. **Never log private keys** in production +7. **Use environment variables** for sensitive data +8. **Implement proper error handling** for all scenarios + +## SignedCall Security Considerations + +- Private keys are never transmitted over the network +- Each request includes a unique nonce and timestamp +- Signatures expire after 60 seconds to prevent replay attacks +- Always verify the endpoint is using HTTPS +- Store private keys securely (never in plain text) +- Consider using hardware wallets for production applications + +## Testing + +```javascript +// Test signedCall functionality +describe('SignedCall Tests', () => { + const testAccount = 'test-account'; + const testPrivateKey = '5JLw5dgQAx6rhZEgNN5C2ds1V47RweGshynFSWFbaMohsYsBvE8'; + + it('should make successful signed call', (done) => { + steem.api.signedCall( + 'condenser_api.get_accounts', + [[testAccount]], + testAccount, + testPrivateKey, + (err, result) => { + expect(err).toBeNull(); + expect(result).toBeDefined(); + expect(Array.isArray(result)).toBe(true); + done(); + } + ); + }); + + it('should handle invalid private key', (done) => { + steem.api.signedCall( + 'condenser_api.get_accounts', + [[testAccount]], + testAccount, + 'invalid-key', + (err, result) => { + expect(err).toBeDefined(); + expect(err.message).toContain('Invalid private key'); + done(); + } + ); + }); +}); +``` + +This comprehensive guide should help you implement `signedCall` effectively in your Steem.js applications. + +--- + +## Signature Verification Examples + +This document provides comprehensive examples for verifying signatures in Steem.js, including signed RPC requests and general message signatures. + +## Verification Overview + +Signature verification is crucial for: +- Validating the authenticity of signed RPC requests +- Ensuring messages haven't been tampered with +- Verifying account ownership +- Implementing secure authentication systems + +## Basic Setup + +```javascript +import { steem } from '@steemit/steem-js'; +import { signatureVerification } from '@steemit/steem-js/api'; + +// Configure API +steem.config.set({ + nodes: ['https://api.steemit.com'], + transport: 'http' +}); +``` + +## 1. Verifying Signed RPC Requests + +### Basic Verification + +```javascript +async function verifySignedRpcRequest(signedRequest) { + try { + // Create account key fetcher + const getAccountKeys = signatureVerification.createApiVerificationFunction(steem.api); + + // Verify the signed request + const result = await signatureVerification.verifySignedRequest(signedRequest, getAccountKeys); + + if (result.valid) { + console.log('✅ Signature verified successfully'); + console.log('Account:', result.account); + console.log('Timestamp:', result.timestamp); + console.log('Decoded params:', result.params); + return true; + } else { + console.log('❌ Signature verification failed:', result.error); + return false; + } + } catch (error) { + console.error('Verification error:', error); + return false; + } +} + +// Example usage +const signedRequest = { + jsonrpc: '2.0', + method: 'condenser_api.get_accounts', + id: 1, + params: { + __signed: { + account: 'username', + nonce: '1234567890abcdef', + params: 'WyJ1c2VybmFtZSJd', // base64 encoded ["username"] + signatures: ['304502210...'], // hex signature + timestamp: '2025-01-01T12:00:00.000Z' + } + } +}; + +verifySignedRpcRequest(signedRequest); +``` + +### Complete Sign and Verify Workflow + +```javascript +async function completeSignAndVerifyWorkflow() { + const account = 'username'; + const password = 'password'; + const privateKey = steem.auth.toWif(account, password, 'active'); + + try { + // Step 1: Create and sign a request + const request = { + method: 'condenser_api.get_accounts', + params: [[account]], + id: 1 + }; + + const signedRequest = steem.api.signRequest(request, account, [privateKey]); + console.log('✅ Request signed successfully'); + + // Step 2: Verify the signed request + const getAccountKeys = signatureVerification.createApiVerificationFunction(steem.api); + const verificationResult = await signatureVerification.verifySignedRequest( + signedRequest, + getAccountKeys + ); + + if (verificationResult.valid) { + console.log('✅ Signature verification successful'); + console.log('Verified account:', verificationResult.account); + console.log('Original params:', verificationResult.params); + } else { + console.log('❌ Verification failed:', verificationResult.error); + } + + return verificationResult; + } catch (error) { + console.error('Workflow error:', error); + return { valid: false, error: error.message }; + } +} + +completeSignAndVerifyWorkflow(); +``` + +## 2. Message Signature Verification + +### Simple Message Verification + +```javascript +function verifySimpleMessage() { + const message = 'Hello, Steem blockchain!'; + const privateKey = '5JLw5dgQAx6rhZEgNN5C2ds1V47RweGshynFSWFbaMohsYsBvE8'; + const publicKey = steem.auth.wifToPublic(privateKey); + + // Sign the message + const signature = steem.auth.sign(message, privateKey); + console.log('Message signed:', signature); + + // Verify the signature + const isValid = signatureVerification.verifyMessageSignature(message, signature, publicKey); + console.log('Signature valid:', isValid); + + return isValid; +} + +verifySimpleMessage(); +``` + +### Multiple Signatures Verification + +```javascript +function verifyMultipleSignatures() { + const message = 'Multi-signature test message'; + + // Create multiple key pairs + const keys = [ + { private: '5JLw5dgQAx6rhZEgNN5C2ds1V47RweGshynFSWFbaMohsYsBvE8' }, + { private: '5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3' } + ].map(k => ({ + ...k, + public: steem.auth.wifToPublic(k.private) + })); + + // Sign with multiple keys + const signatures = keys.map(key => steem.auth.sign(message, key.private)); + const publicKeys = keys.map(key => key.public); + + console.log('Signatures created:', signatures.length); + + // Verify multiple signatures + const result = signatureVerification.verifyMultipleSignatures( + message, + signatures, + publicKeys + ); + + console.log('Verification result:', { + verified: result.verified, + validSignatures: result.validSignatures, + totalChecked: result.details.length + }); + + // Show detailed results + result.details.forEach((detail, index) => { + console.log(`Signature ${index + 1}:`, detail.valid ? '✅' : '❌'); + }); + + return result; +} + +verifyMultipleSignatures(); +``` + +## 3. Batch Verification + +### Verify Multiple Signed Requests + +```javascript +async function batchVerifyRequests() { + const account = 'username'; + const privateKey = steem.auth.toWif(account, 'password', 'active'); + + // Create multiple signed requests + const requests = [ + { method: 'condenser_api.get_accounts', params: [[account]], id: 1 }, + { method: 'condenser_api.get_account_history', params: [account, -1, 10], id: 2 }, + { method: 'condenser_api.get_followers', params: [account, '', 'blog', 10], id: 3 } + ]; + + const signedRequests = requests.map(req => + steem.api.signRequest(req, account, [privateKey]) + ); + + console.log(`Created ${signedRequests.length} signed requests`); + + // Batch verify all requests + const getAccountKeys = signatureVerification.createApiVerificationFunction(steem.api); + const results = await signatureVerification.batchVerifySignedRequests( + signedRequests, + getAccountKeys + ); + + console.log('Batch verification results:'); + results.forEach((result, index) => { + console.log(`Request ${index + 1}:`, result.valid ? '✅' : '❌', result.error || 'Valid'); + }); + + const validCount = results.filter(r => r.valid).length; + console.log(`${validCount}/${results.length} requests verified successfully`); + + return results; +} + +batchVerifyRequests(); +``` + +## 4. Advanced Verification Scenarios + +### Custom Account Key Provider + +```javascript +class CustomAccountKeyProvider { + constructor() { + this.keyCache = new Map(); + } + + async getAccountKeys(account) { + // Check cache first + if (this.keyCache.has(account)) { + console.log(`Using cached keys for ${account}`); + return this.keyCache.get(account); + } + + try { + // Fetch from API + const accountData = await new Promise((resolve, reject) => { + steem.api.call('condenser_api.get_accounts', [[account]], (err, result) => { + if (err) reject(err); + else resolve(result[0]); + }); + }); + + const keys = signatureVerification.extractAccountKeys(accountData); + + // Cache the keys + this.keyCache.set(account, keys); + console.log(`Fetched and cached keys for ${account}`); + + return keys; + } catch (error) { + throw new Error(`Failed to get keys for ${account}: ${error.message}`); + } + } +} + +async function useCustomKeyProvider() { + const keyProvider = new CustomAccountKeyProvider(); + const account = 'username'; + + // Create a signed request + const request = steem.api.signRequest( + { method: 'condenser_api.get_accounts', params: [[account]], id: 1 }, + account, + [steem.auth.toWif(account, 'password', 'active')] + ); + + // Verify using custom provider + const result = await signatureVerification.verifySignedRequest( + request, + (acc) => keyProvider.getAccountKeys(acc) + ); + + console.log('Custom verification result:', result.valid ? '✅' : '❌'); + return result; +} + +useCustomKeyProvider(); +``` + +### Signature Expiration Checking + +```javascript +function checkSignatureExpiration() { + const timestamps = [ + new Date().toISOString(), // Current time + new Date(Date.now() - 30000).toISOString(), // 30 seconds ago + new Date(Date.now() - 120000).toISOString(), // 2 minutes ago (expired) + 'invalid-timestamp' + ]; + + console.log('Checking signature expiration:'); + timestamps.forEach((timestamp, index) => { + const isExpired = signatureVerification.isSignatureExpired(timestamp); + console.log(`Timestamp ${index + 1}: ${isExpired ? '❌ Expired' : '✅ Valid'}`); + console.log(` Value: ${timestamp}`); + }); + + // Custom expiration time (5 minutes) + const customExpiry = signatureVerification.isSignatureExpired( + new Date(Date.now() - 360000).toISOString(), // 6 minutes ago + 300000 // 5 minutes in ms + ); + + console.log(`Custom expiry check: ${customExpiry ? '❌ Expired' : '✅ Valid'}`); +} + +checkSignatureExpiration(); +``` + +### Format Validation + +```javascript +function validateFormats() { + const testSignatures = [ + '304502210...', // Valid hex signature + 'invalid-signature', // Invalid format + '', // Empty + '123' // Too short + ]; + + const testPublicKeys = [ + 'STM6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV', // Valid Steem public key + 'invalid-public-key', // Invalid format + '', // Empty + 'STM123' // Invalid checksum + ]; + + console.log('Signature format validation:'); + testSignatures.forEach((sig, index) => { + const isValid = signatureVerification.isValidSignatureFormat(sig); + console.log(`Signature ${index + 1}: ${isValid ? '✅' : '❌'} - ${sig.substring(0, 20)}...`); + }); + + console.log('\nPublic key format validation:'); + testPublicKeys.forEach((key, index) => { + const isValid = signatureVerification.isValidPublicKeyFormat(key); + console.log(`Key ${index + 1}: ${isValid ? '✅' : '❌'} - ${key.substring(0, 20)}...`); + }); +} + +validateFormats(); +``` + +## 5. Real-World Use Cases + +### Secure API Gateway + +```javascript +class SecureApiGateway { + constructor(api) { + this.api = api; + this.getAccountKeys = signatureVerification.createApiVerificationFunction(api); + } + + async processSignedRequest(signedRequest) { + try { + // Step 1: Verify the signature + const verification = await signatureVerification.verifySignedRequest( + signedRequest, + this.getAccountKeys + ); + + if (!verification.valid) { + return { + success: false, + error: 'Invalid signature', + details: verification.error + }; + } + + // Step 2: Check if signature is not expired + if (signatureVerification.isSignatureExpired(verification.timestamp)) { + return { + success: false, + error: 'Signature expired' + }; + } + + // Step 3: Execute the original request + const result = await new Promise((resolve, reject) => { + this.api.call(signedRequest.method, verification.params, (err, result) => { + if (err) reject(err); + else resolve(result); + }); + }); + + return { + success: true, + account: verification.account, + result: result + }; + + } catch (error) { + return { + success: false, + error: 'Processing failed', + details: error.message + }; + } + } +} + +// Usage +async function useSecureGateway() { + const gateway = new SecureApiGateway(steem.api); + + // Create a signed request + const signedRequest = steem.api.signRequest( + { method: 'condenser_api.get_accounts', params: [['username']], id: 1 }, + 'username', + [steem.auth.toWif('username', 'password', 'active')] + ); + + // Process through secure gateway + const result = await gateway.processSignedRequest(signedRequest); + + if (result.success) { + console.log('✅ Secure request processed successfully'); + console.log('Account:', result.account); + console.log('Result:', result.result); + } else { + console.log('❌ Secure request failed:', result.error); + } + + return result; +} + +useSecureGateway(); +``` + +### Message Authentication System + +```javascript +class MessageAuthSystem { + constructor() { + this.trustedKeys = new Set(); + } + + addTrustedKey(publicKey) { + if (signatureVerification.isValidPublicKeyFormat(publicKey)) { + this.trustedKeys.add(publicKey); + console.log(`✅ Added trusted key: ${publicKey.substring(0, 20)}...`); + } else { + console.log(`❌ Invalid key format: ${publicKey}`); + } + } + + verifyMessage(message, signature, publicKey) { + // Check if key is trusted + if (!this.trustedKeys.has(publicKey)) { + return { + valid: false, + error: 'Untrusted public key' + }; + } + + // Verify signature + const isValid = signatureVerification.verifyMessageSignature(message, signature, publicKey); + + return { + valid: isValid, + publicKey: publicKey, + message: message, + error: isValid ? null : 'Invalid signature' + }; + } + + batchVerifyMessages(messages) { + return messages.map(msg => this.verifyMessage(msg.message, msg.signature, msg.publicKey)); + } +} + +// Usage +function useMessageAuthSystem() { + const authSystem = new MessageAuthSystem(); + + // Add trusted keys + const trustedKey = steem.auth.wifToPublic('5JLw5dgQAx6rhZEgNN5C2ds1V47RweGshynFSWFbaMohsYsBvE8'); + authSystem.addTrustedKey(trustedKey); + + // Create and verify messages + const message = 'Authenticated message'; + const signature = steem.auth.sign(message, '5JLw5dgQAx6rhZEgNN5C2ds1V47RweGshynFSWFbaMohsYsBvE8'); + + const result = authSystem.verifyMessage(message, signature, trustedKey); + + console.log('Message authentication result:', result.valid ? '✅' : '❌'); + if (!result.valid) { + console.log('Error:', result.error); + } + + return result; +} + +useMessageAuthSystem(); +``` + +## 6. Transaction Signature Verification + +`steem.auth.verifyTransaction(signedTx, publicKey)` verifies that a transaction's +signatures were produced by the given public key. Unlike the message/RPC-request +verification above, this operates at the **transaction** level: it reconstructs +the exact digest `sha256(chain_id ‖ serializeTransaction(trx))` that +`signTransaction` signs over, then checks each signature against it. + +> **Why this matters:** a relay or wallet server can prove a client-submitted +> transaction was signed by the claimed account's key *before* forwarding it to +> the chain — closing a defense-in-depth gap that transaction-shape validation +> alone cannot cover. + +### Basic Sign-and-Verify Round-Trip + +```javascript +import { steem } from '@steemit/steem-js'; + +const wif = '5JLw5dgQAx6rhZEgNN5C2ds1V47RweGshynFSWFbaMohsYsBvE8'; +const publicKey = steem.auth.wifToPublic(wif); + +const tx = { + ref_block_num: 123, + ref_block_prefix: 456789, + expiration: '2026-07-10T00:00:00', + operations: [['transfer', { + from: 'alice', to: 'bob', amount: '1.000 STEEM', memo: '' + }]], + extensions: [], +}; + +// Client signs the transaction locally +const signedTx = steem.auth.signTransaction(tx, [wif]); + +// Server (or same process) verifies it against the public key +const isValid = steem.auth.verifyTransaction(signedTx, publicKey); +console.log(isValid ? '✅ Valid signature' : '❌ Invalid signature'); +// => ✅ Valid signature +``` + +### Server-Side Verification (Relay Service) + +This is the primary security use case: a wallet/relay server receives a +signed transaction from a client and must independently confirm the signer +before broadcasting. + +```javascript +import { steem } from '@steemit/steem-js'; + +/** + * Verify a client-submitted transaction before relaying it to the chain. + * + * @param {object} signedTx - Transaction signed by the client (has .signatures) + * @param {string} publicKey - The STM... public key the server expects the + * account to sign with (e.g. fetched from get_accounts). + * @returns {boolean} true if the signature is cryptographically valid. + */ +function verifyClientTransaction(signedTx, publicKey) { + if (!signedTx || !Array.isArray(signedTx.signatures) || signedTx.signatures.length === 0) { + console.error('❌ Transaction has no signatures'); + return false; + } + + const isValid = steem.auth.verifyTransaction(signedTx, publicKey); + if (!isValid) { + console.error('❌ Signature does not match the claimed public key'); + return false; + } + + console.log('✅ Transaction signed by the claimed key — safe to relay'); + return true; +} + +// Usage in a relay route: +// const account = await steem.api.getAccountsAsync([username]); +// const expectedPubKey = account[0].active.key_auths[0][0]; +// if (!verifyClientTransaction(clientSignedTx, expectedPubKey)) { +// return res.status(403).json({ error: 'Invalid signature' }); +// } +// await steem.broadcast.sendAsync(clientSignedTx); +``` + +### Rejected Cases + +```javascript +// 1. Wrong public key +const wrongPub = steem.auth.wifToPublic('5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3'); +console.log(steem.auth.verifyTransaction(signedTx, wrongPub)); // false + +// 2. Tampered transaction (operation changed after signing) +const tampered = JSON.parse(JSON.stringify(signedTx)); +tampered.operations[0][1].amount = '999.000 STEEM'; +console.log(steem.auth.verifyTransaction(tampered, publicKey)); // false + +// 3. Missing signatures entirely +const unsigned = { ...tx }; +console.log(steem.auth.verifyTransaction(unsigned, publicKey)); // false +``` + +### Building the Digest Manually with serializeTransaction + +For advanced use cases (e.g. verifying with a custom crypto stack), the binary +serializer is exported as `steem.auth.serializeTransaction(trx)` so you can +reconstruct the signing digest yourself: + +```javascript +import { steem } from '@steemit/steem-js'; +import { sha256 } from '@noble/hashes/sha2'; + +// The digest signTransaction signs over: +const buf = steem.auth.serializeTransaction(tx); // Buffer (binary transaction) +const chainId = Buffer.alloc(32, 0); // mainnet chain_id (all-zero) +const digest = Buffer.from(sha256(Buffer.concat([chainId, buf]))); +console.log('Signing digest:', digest.toString('hex')); // 32-byte hex +``` + +> **Note:** `serializeTransaction` does **not** include the `signatures` field in +> its output when the input lacks one — matching `signTransaction`, which +> serializes the transaction body *before* attaching signatures. + +### Common Verification Errors + +```javascript +function handleVerificationErrors() { + const commonErrors = [ + { + name: 'Invalid signature format', + test: () => signatureVerification.isValidSignatureFormat('invalid') + }, + { + name: 'Invalid public key format', + test: () => signatureVerification.isValidPublicKeyFormat('invalid') + }, + { + name: 'Expired signature', + test: () => !signatureVerification.isSignatureExpired( + new Date(Date.now() - 120000).toISOString() + ) + } + ]; + + console.log('Common verification error checks:'); + commonErrors.forEach(error => { + try { + const result = error.test(); + console.log(`${error.name}: ${result ? '✅ Pass' : '❌ Fail'}`); + } catch (e) { + console.log(`${error.name}: ❌ Exception - ${e.message}`); + } + }); +} + +handleVerificationErrors(); +``` + +## Verification Best Practices + +1. **Always validate input formats** before verification +2. **Check signature expiration** to prevent replay attacks +3. **Use trusted key sources** for verification +4. **Implement proper error handling** for all scenarios +5. **Cache account keys** to improve performance +6. **Log verification attempts** for security auditing +7. **Use batch verification** for multiple requests +8. **Implement rate limiting** to prevent abuse + +## Verification Security Considerations + +- Signatures expire after 60 seconds by default +- Always verify against the correct account's public keys +- Use HTTPS endpoints to prevent man-in-the-middle attacks +- Validate all input parameters before processing +- Implement proper logging for security auditing +- Consider implementing additional authentication layers for sensitive operations + +This comprehensive guide covers all aspects of signature verification in Steem.js, from basic message verification to complex authentication systems. + +## Where to go next + +- [Reading chain data](/tutorials/steem-js/read-api.html) for the read helpers used inside signed requests. +- [RPC auth test migration](/tutorials/steem-js/rpc-auth-migration.html) for how this machinery is exercised in the test suite. diff --git a/docs/tutorials/steemgosdk/broadcast.md b/docs/tutorials/steemgosdk/broadcast.md new file mode 100644 index 0000000..03571db --- /dev/null +++ b/docs/tutorials/steemgosdk/broadcast.md @@ -0,0 +1,747 @@ +--- +title: steemgosdk - Broadcasting Operations +description: Broadcast every Steem operation from Go - votes, transfers, encrypted memos, comments, beneficiaries, multi-operation transactions, custom_json and complete examples. +--- + +# steemgosdk: Broadcasting Operations + +The `Broadcast` instance of the [Steem Go SDK](https://github.com/steemit/steemgosdk) automatically handles transaction preparation (ref_block_num, ref_block_prefix, expiration) and signing - you only provide operations and private keys. This page carries the complete broadcast examples from the SDK documentation; client setup and key generation live in [Getting started](/tutorials/steemgosdk/index.html). + +> **⚠️ Security Warning**: The private keys used in the examples below (`5JRaypasxMx1L97ZUX7YuC5Psb5EAbF821kkAGtBj7xCJFQcbLg`) are **test/example keys only**. They are publicly known and should **NEVER** be used in production. Always generate your own private keys from your account name and password using the `auth.ToWif()` or `auth.GetPrivateKeys()` methods. + +> On-the-wire details of every operation are documented in the generated [broadcast operations reference](/api/broadcast_ops/). + +## Broadcast Examples + +## Broadcast Examples + +### Vote on a Post + +```go +package main + +import ( + "fmt" + "time" + "github.com/steemit/steemgosdk" + "github.com/steemit/steemutil/protocol" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + broadcast := client.GetBroadcast() + + // Create a vote operation + voteOp := &protocol.VoteOperation{ + Voter: "your-account-name", + Author: "steemit", + Permlink: "firstpost", + Weight: 10000, // 100% vote weight (10000 = 100%) + } + + // Your posting private key in WIF format + // WARNING: This is a test/example key. NEVER use it in production! + // Generate your own key using: auth.ToWif(accountName, password, "posting") + postingWif := "5JRaypasxMx1L97ZUX7YuC5Psb5EAbF821kkAGtBj7xCJFQcbLg" + + // Broadcast the vote + result, err := broadcast.SendWith(voteOp, postingWif) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + fmt.Printf("Transaction broadcasted: %s\n", string(result)) +} +``` + +### Transfer STEEM or SBD + +```go +package main + +import ( + "fmt" + "time" + "github.com/steemit/steemgosdk" + "github.com/steemit/steemutil/protocol" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + broadcast := client.GetBroadcast() + + // Create a transfer operation + transferOp := &protocol.TransferOperation{ + From: "your-account-name", + To: "recipient-account", + Amount: "1.000 STEEM", + Memo: "Hello from Steem Go SDK!", + } + + // Your active private key in WIF format + // WARNING: This is a test/example key. NEVER use it in production! + activeWif := "5JRaypasxMx1L97ZUX7YuC5Psb5EAbF821kkAGtBj7xCJFQcbLg" + + // Broadcast the transfer + result, err := broadcast.SendWith(transferOp, activeWif) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + fmt.Printf("Transfer broadcasted: %s\n", string(result)) +} +``` + +### Transfer with Encrypted Memo + +```go +package main + +import ( + "fmt" + "time" + "github.com/steemit/steemgosdk" + "github.com/steemit/steemutil/protocol" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + broadcast := client.GetBroadcast() + auth := client.GetAuth() + + // Recipient's memo public key + recipientMemoKey := "STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA" + + // Your memo private key + // WARNING: This is a test/example key. NEVER use it in production! + yourMemoWif := "5JRaypasxMx1L97ZUX7YuC5Psb5EAbF821kkAGtBj7xCJFQcbLg" + + // Encrypt the memo (memos starting with '#' are encrypted) + encryptedMemo, err := auth.EncodeMemo(yourMemoWif, recipientMemoKey, "#Secret message") + if err != nil { + fmt.Printf("Error encrypting memo: %v\n", err) + return + } + + // Create transfer with encrypted memo + transferOp := &protocol.TransferOperation{ + From: "your-account-name", + To: "recipient-account", + Amount: "1.000 STEEM", + Memo: encryptedMemo, + } + + // Your active private key + // WARNING: This is a test/example key. NEVER use it in production! + activeWif := "5JRaypasxMx1L97ZUX7YuC5Psb5EAbF821kkAGtBj7xCJFQcbLg" + + // Broadcast the transfer + result, err := broadcast.SendWith(transferOp, activeWif) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + fmt.Printf("Transfer with encrypted memo broadcasted: %s\n", string(result)) +} +``` + +### Create a Comment + +```go +package main + +import ( + "fmt" + "time" + "github.com/steemit/steemgosdk" + "github.com/steemit/steemutil/protocol" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + broadcast := client.GetBroadcast() + + // Create a comment operation + commentOp := &protocol.CommentOperation{ + ParentAuthor: "steemit", + ParentPermlink: "firstpost", + Author: "your-account-name", + Permlink: "my-comment-permlink", + Title: "My Comment Title", + Body: "This is the body of my comment.", + JsonMetadata: `{"tags":["steem"],"app":"steemgosdk/1.0"}`, + } + + // Your posting private key + // WARNING: This is a test/example key. NEVER use it in production! + postingWif := "5JRaypasxMx1L97ZUX7YuC5Psb5EAbF821kkAGtBj7xCJFQcbLg" + + // Broadcast the comment + result, err := broadcast.SendWith(commentOp, postingWif) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + fmt.Printf("Comment broadcasted: %s\n", string(result)) +} +``` + +### Post with Comment Options (Beneficiaries) + +Use `CommentOptionsOperation` to set beneficiaries who will receive a portion of the post rewards: + +```go +package main + +import ( + "encoding/json" + "fmt" + "time" + "github.com/steemit/steemgosdk" + "github.com/steemit/steemutil/protocol" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + broadcast := client.GetBroadcast() + + author := "your-account-name" + permlink := "my-post-with-beneficiaries" + tags := []string{"test", "steem"} + + jsonMeta, _ := json.Marshal(map[string]interface{}{ + "tags": tags, + "app": "steemgosdk/1.0", + }) + + // Create comment operation + commentOp := &protocol.CommentOperation{ + ParentAuthor: "", + ParentPermlink: tags[0], + Author: author, + Permlink: permlink, + Title: "Post with Beneficiaries", + Body: "This post has beneficiaries set.", + JsonMetadata: string(jsonMeta), + } + + // Define beneficiaries (weight is in basis points: 3000 = 30%) + // Note: steemutil v0.0.19+ automatically sorts beneficiaries alphabetically + beneficiaries := []protocol.Beneficiary{ + {Account: "alice", Weight: 2000}, // 20% + {Account: "bob", Weight: 1000}, // 10% + } + + // Create comment options with beneficiaries extension + optionsOp := &protocol.CommentOptionsOperation{ + Author: author, + Permlink: permlink, + MaxAcceptedPayout: "1000000.000 SBD", + PercentSteemDollars: 10000, + AllowVotes: true, + AllowCurationRewards: true, + Extensions: protocol.CommentOptionsExtensions{ + protocol.NewBeneficiariesExtension(beneficiaries), + }, + } + + // Broadcast both operations in one transaction + // WARNING: This is a test/example key. NEVER use it in production! + postingWif := "5JRaypasxMx1L97ZUX7YuC5Psb5EAbF821kkAGtBj7xCJFQcbLg" + + result, err := broadcast.Send([]protocol.Operation{commentOp, optionsOp}, map[string]string{ + "posting": postingWif, + }) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + fmt.Printf("Post with beneficiaries broadcasted: %s\n", string(result)) +} +``` + +### Post with Comment Options (No Beneficiaries) + +You can also use `CommentOptionsOperation` without setting beneficiaries: + +```go +package main + +import ( + "encoding/json" + "fmt" + "time" + "github.com/steemit/steemgosdk" + "github.com/steemit/steemutil/protocol" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + broadcast := client.GetBroadcast() + + author := "your-account-name" + permlink := "my-post-with-options" + tags := []string{"test", "steem"} + + jsonMeta, _ := json.Marshal(map[string]interface{}{ + "tags": tags, + "app": "steemgosdk/1.0", + }) + + commentOp := &protocol.CommentOperation{ + ParentAuthor: "", + ParentPermlink: tags[0], + Author: author, + Permlink: permlink, + Title: "Post with Options", + Body: "This post has comment options but no beneficiaries.", + JsonMetadata: string(jsonMeta), + } + + // Comment options with empty extensions (no beneficiaries) + optionsOp := &protocol.CommentOptionsOperation{ + Author: author, + Permlink: permlink, + MaxAcceptedPayout: "1000000.000 SBD", + PercentSteemDollars: 10000, + AllowVotes: true, + AllowCurationRewards: true, + Extensions: protocol.CommentOptionsExtensions{}, // Empty extensions + } + + // WARNING: This is a test/example key. NEVER use it in production! + postingWif := "5JRaypasxMx1L97ZUX7YuC5Psb5EAbF821kkAGtBj7xCJFQcbLg" + + result, err := broadcast.Send([]protocol.Operation{commentOp, optionsOp}, map[string]string{ + "posting": postingWif, + }) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + fmt.Printf("Post with options broadcasted: %s\n", string(result)) +} +``` + +### Multiple Operations in One Transaction + +```go +package main + +import ( + "fmt" + "time" + "github.com/steemit/steemgosdk" + "github.com/steemit/steemutil/protocol" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + broadcast := client.GetBroadcast() + + // Create multiple operations + voteOp := &protocol.VoteOperation{ + Voter: "your-account-name", + Author: "steemit", + Permlink: "firstpost", + Weight: 10000, + } + + commentOp := &protocol.CommentOperation{ + ParentAuthor: "steemit", + ParentPermlink: "firstpost", + Author: "your-account-name", + Permlink: "my-comment-permlink", + Title: "My Comment", + Body: "Great post!", + JsonMetadata: "{}", + } + + // Prepare private keys (posting key for both operations) + // WARNING: This is a test/example key. NEVER use it in production! + privKeys := map[string]string{ + "posting": "5JRaypasxMx1L97ZUX7YuC5Psb5EAbF821kkAGtBj7xCJFQcbLg", + } + + // Broadcast multiple operations in one transaction + result, err := broadcast.Send([]protocol.Operation{voteOp, commentOp}, privKeys) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + fmt.Printf("Transaction with multiple operations broadcasted: %s\n", string(result)) +} +``` + +## Complete Examples + +## Complete Examples + +### Complete Transfer Example + +```go +package main + +import ( + "fmt" + "time" + "github.com/steemit/steemgosdk" + "github.com/steemit/steemutil/protocol" +) + +func main() { + // Initialize client + url := "https://api.steemit.com" + client := steemgosdk.GetClient(url) + + // Get instances + api := client.GetAPI() + broadcast := client.GetBroadcast() + auth := client.GetAuth() + + // 1. Check account balance (optional) + result, err := api.Call("condenser_api", "get_accounts", []interface{}{ + []interface{}{"your-account-name"}, + }) + if err != nil { + fmt.Printf("Error getting account: %v\n", err) + return + } + fmt.Println("Account retrieved successfully") + fmt.Printf("Account data: %v\n", result.Result) + + // 2. Prepare transfer operation + transferOp := &protocol.TransferOperation{ + From: "your-account-name", + To: "recipient-account", + Amount: "1.000 STEEM", + Memo: "Transfer from Steem Go SDK", + } + + // 3. Get private key (in production, store securely) + // WARNING: This is a test/example key. NEVER use it in production! + activeWif := "5JRaypasxMx1L97ZUX7YuC5Psb5EAbF821kkAGtBj7xCJFQcbLg" + + // Or generate from account name and password + // keys, _ := auth.GetPrivateKeys("your-account-name", "your-password", []string{"active"}) + // activeWif := keys["active"] + + // 4. Broadcast transaction + result, err := broadcast.SendWith(transferOp, activeWif) + if err != nil { + fmt.Printf("Error broadcasting: %v\n", err) + return + } + + fmt.Printf("Transfer successful! Result: %s\n", string(result)) +} +``` + +### Complete Vote and Comment Example + +```go +package main + +import ( + "fmt" + "time" + "github.com/steemit/steemgosdk" + "github.com/steemit/steemutil/protocol" +) + +func main() { + // Initialize + client := steemgosdk.GetClient("https://api.steemit.com") + broadcast := client.GetBroadcast() + auth := client.GetAuth() + + // Get posting key + accountName := "your-account-name" + password := "your-password" + keys, err := auth.GetPrivateKeys(accountName, password, []string{"posting"}) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + postingWif := keys["posting"] + + // 1. Vote on a post + voteOp := &protocol.VoteOperation{ + Voter: accountName, + Author: "steemit", + Permlink: "firstpost", + Weight: 10000, // 100% + } + + result, err := broadcast.SendWith(voteOp, postingWif) + if err != nil { + fmt.Printf("Error voting: %v\n", err) + return + } + fmt.Printf("Vote broadcasted: %s\n", string(result)) + + // 2. Comment on the same post + commentOp := &protocol.CommentOperation{ + ParentAuthor: "steemit", + ParentPermlink: "firstpost", + Author: accountName, + Permlink: "my-comment-" + fmt.Sprintf("%d", time.Now().Unix()), + Title: "", + Body: "Great post! Thanks for sharing.", + JsonMetadata: `{"tags":["steem"],"app":"steemgosdk/1.0"}`, + } + + result, err = broadcast.SendWith(commentOp, postingWif) + if err != nil { + fmt.Printf("Error commenting: %v\n", err) + return + } + fmt.Printf("Comment broadcasted: %s\n", string(result)) +} +``` + +## CustomJson Examples + +## CustomJson Examples + +### Basic CustomJson Operation + +```go +package main + +import ( + "encoding/json" + "fmt" + "github.com/steemit/steemgosdk" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + broadcast := client.GetBroadcast() + + // Create a follow operation using custom_json + followData := []interface{}{ + "follow", + map[string]interface{}{ + "follower": "your-account-name", + "following": "steemit", + "what": []string{"blog"}, + }, + } + + jsonStr, _ := json.Marshal(followData) + + // Broadcast custom_json operation + // Parameters: requiredAuths, requiredPostingAuths, id, json, privKeyWif + result, err := broadcast.CustomJson( + []string{}, // required_auths (empty for posting auth) + []string{"your-account-name"}, // required_posting_auths + "follow", // id + string(jsonStr), // json + "your-posting-private-key", // posting WIF + ) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + fmt.Printf("CustomJson operation broadcasted: %s\n", string(result)) +} +``` + +### Notify Operation (setLastRead) + +```go +package main + +import ( + "encoding/json" + "fmt" + "time" + "github.com/steemit/steemgosdk" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + broadcast := client.GetBroadcast() + + // Create a notify operation to set last read date + notifyData := []interface{}{ + "setLastRead", + map[string]interface{}{ + "date": time.Now().UTC().Format(time.RFC3339), + }, + } + + jsonStr, _ := json.Marshal(notifyData) + + // Broadcast custom_json operation + result, err := broadcast.CustomJson( + []string{}, // required_auths (empty) + []string{"your-account-name"}, // required_posting_auths + "notify", // id + string(jsonStr), // json + "your-posting-private-key", // posting WIF + ) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + fmt.Printf("Notify operation broadcasted: %s\n", string(result)) +} +``` + +### CustomJson with Active Authority + +```go +package main + +import ( + "encoding/json" + "fmt" + "github.com/steemit/steemgosdk" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + broadcast := client.GetBroadcast() + + // Create custom operation data + customData := map[string]interface{}{ + "action": "custom_action", + "data": "some custom data", + } + + jsonStr, _ := json.Marshal(customData) + + // Broadcast custom_json operation with active authority + // When requiredAuths is not empty, active key is required + result, err := broadcast.CustomJson( + []string{"your-account-name"}, // required_auths (requires active key) + []string{}, // required_posting_auths (empty) + "custom_id", // id + string(jsonStr), // json + "your-active-private-key", // active WIF + ) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + fmt.Printf("CustomJson with active auth broadcasted: %s\n", string(result)) +} +``` + +### Using CustomJSONOperation Directly + +```go +package main + +import ( + "encoding/json" + "fmt" + "github.com/steemit/steemgosdk" + "github.com/steemit/steemutil/protocol" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + broadcast := client.GetBroadcast() + + // Create CustomJSONOperation directly + followData := []interface{}{ + "follow", + map[string]interface{}{ + "follower": "your-account-name", + "following": "steemit", + "what": []string{"blog"}, + }, + } + + jsonStr, _ := json.Marshal(followData) + + op := &protocol.CustomJSONOperation{ + RequiredAuths: []string{}, + RequiredPostingAuths: []string{"your-account-name"}, + ID: "follow", + JSON: string(jsonStr), + } + + // Use SendWith to broadcast + privKeys := map[string]string{ + "posting": "your-posting-private-key", + } + + result, err := broadcast.Send([]protocol.Operation{op}, privKeys) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + fmt.Printf("CustomJSONOperation broadcasted: %s\n", string(result)) +} +``` + +### Witness Price Feed (feed_publish) + +```go +package main + +import ( + "fmt" + "log" + + "github.com/steemit/steemgosdk" + "github.com/steemit/steemgosdk/broadcast" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + bc := client.GetBroadcast() + + rate := broadcast.ExchangeRate{ + Base: "0.500 SBD", + Quote: "1.000 STEEM", + } + + // Use the witness account active key (WIF). Block signing keys cannot sign feed_publish. + result, err := bc.FeedPublish("your-witness-account", rate, "your-active-private-key") + if err != nil { + log.Fatal(err) + } + + fmt.Printf("feed_publish result: %s\n", string(result)) +} +``` + +## Notes + +## Notes + +- **Security**: Never hardcode private keys or passwords in production code. Use environment variables or secure key management systems. +- **Test Private Keys**: The private key `5JRaypasxMx1L97ZUX7YuC5Psb5EAbF821kkAGtBj7xCJFQcbLg` used in examples is a **test/example key only**. It is publicly known and should **NEVER** be used in production. Always use your own private keys generated from your account name and password. +- **Error Handling**: Always check errors returned by SDK methods. +- **CustomJson Authority**: + - If `requiredAuths` is not empty, you need to provide an **active** private key + - If only `requiredPostingAuths` is set, you need to provide a **posting** private key + - The `CustomJson()` method automatically determines which key type to use based on the provided auths +- **Network**: The examples use `https://api.steemit.com` as the default node. You can use any Steem node URL. +- **WIF Format**: Private keys should be in Wallet Import Format (WIF), starting with '5'. +- **Public Keys**: Public keys should be in Steem format, starting with 'STM'. +- **Memo Encryption**: Memos starting with '#' are automatically encrypted. Plain text memos are sent as-is. +- **API Methods**: The SDK provides convenient methods like `GetBlock()`, `GetBlocks()`, `GetDynamicGlobalProperties()`, and `GetTransactionHex()` in the `API` instance. Use these instead of generic `Call()` when possible for better type safety and simpler code. +- **Broadcast**: The `Broadcast` instance automatically handles transaction preparation (ref_block_num, ref_block_prefix, expiration) and signing. You only need to provide operations and private keys. The Broadcast instance internally creates an API instance for fetching dynamic global properties. + + +## Where to go next + +- [Getting started](/tutorials/steemgosdk/index.html) - client setup, auth/keys and Steem URI examples. +- [SignedCall API](/tutorials/steemgosdk/signed-call.html) - authenticated reads from Go. diff --git a/docs/tutorials/steemgosdk/index.md b/docs/tutorials/steemgosdk/index.md new file mode 100644 index 0000000..eb3476e --- /dev/null +++ b/docs/tutorials/steemgosdk/index.md @@ -0,0 +1,594 @@ +--- +title: steemgosdk - Getting Started +description: Set up the Steem Go SDK - client initialization, chain-reading API examples, key-generation auth examples and Steem URI signing examples. +--- + +# steemgosdk: Getting Started + +[steemgosdk](https://github.com/steemit/steemgosdk) is the official Go library for the Steem blockchain (Go module `github.com/steemit/steemgosdk`, targeting Go 1.18+). Install it with `go get github.com/steemit/steemgosdk`, then follow the examples below, migrated from the SDK's own documentation. + +> Every helper below talks to the same JSON-RPC methods documented in the generated [API Reference](/api/) - for example `GetAccounts` corresponds to [condenser_api.get_accounts](/api/condenser_api/get_accounts.html). + +## Basic Setup + +## Basic Setup + +### Initialize Client + +```go +package main + +import ( + "fmt" + "github.com/steemit/steemgosdk" +) + +func main() { + // Create a client pointing to a Steem node + url := "https://api.steemit.com" + client := steemgosdk.GetClient(url) + + // Set account name and WIFs if needed + client.AccountName = "your-account-name" + + fmt.Println("Client initialized:", client.Url) +} +``` + +### Get API, Broadcast, and Auth Instances + +```go +// Get API instance for making RPC calls +api := client.GetAPI() + +// Get Broadcast instance for signing and broadcasting transactions +broadcast := client.GetBroadcast() + +// Get Auth instance for authentication and key management +auth := client.GetAuth() +``` + +## API Examples + +## API Examples + +### Get Block Information + +```go +package main + +import ( + "fmt" + "github.com/steemit/steemgosdk" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + api := client.GetAPI() + + // Get block by number + block, err := api.GetBlock(1) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + fmt.Printf("Block ID: %s\n", block.BlockID) + fmt.Printf("Previous: %s\n", block.Previous) + fmt.Printf("Timestamp: %s\n", block.Timestamp) +} +``` + +### Get Multiple Blocks + +```go +package main + +import ( + "fmt" + "github.com/steemit/steemgosdk" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + api := client.GetAPI() + + // Get blocks in range [from, to) + blocks, err := api.GetBlocks(10000000, 10000010) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + fmt.Printf("Retrieved %d blocks\n", len(blocks)) + for _, wrapBlock := range blocks { + fmt.Printf("Block %d: %s\n", wrapBlock.BlockNum, wrapBlock.Block.BlockID) + } +} +``` + +### Get Account Information + +```go +package main + +import ( + "encoding/json" + "fmt" + "github.com/steemit/steemgosdk" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + api := client.GetAPI() + + // Get account information + result, err := api.Call("condenser_api", "get_accounts", []interface{}{ + []interface{}{"steemit"}, + }) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + // Print raw result + resultJSON, _ := json.MarshalIndent(result.Result, "", " ") + fmt.Println(string(resultJSON)) +} +``` + +### Get Account Information with Reputation Calculation + +```go +package main + +import ( + "fmt" + "github.com/steemit/steemgosdk" + "github.com/steemit/steemutil/protocol" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + api := client.GetAPI() + + // Get account information + accounts, err := api.GetAccounts([]string{"steemit"}) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + if len(accounts) > 0 { + account := accounts[0] + rawRep := account.Reputation + + // Convert raw reputation to log10 format + repLog10 := protocol.RepLog10(rawRep) + + fmt.Printf("Account: %s\n", account.Name) + fmt.Printf("Raw Reputation: %d\n", rawRep) + fmt.Printf("Reputation Score (log10): %d\n", repLog10) + } +} +``` + +### Get Dynamic Global Properties + +```go +package main + +import ( + "fmt" + "github.com/steemit/steemgosdk" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + api := client.GetAPI() + + dgp, err := api.GetDynamicGlobalProperties() + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + fmt.Printf("Head Block Number: %d\n", dgp.HeadBlockNumber) + fmt.Printf("Head Block ID: %s\n", dgp.HeadBlockId) + fmt.Printf("Time: %s\n", dgp.Time) +} +``` + +### Get Content (Post/Comment) + +```go +package main + +import ( + "encoding/json" + "fmt" + "github.com/steemit/steemgosdk" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + api := client.GetAPI() + + // Get a specific post/comment + result, err := api.Call("condenser_api", "get_content", []interface{}{ + "steemit", + "firstpost", + }) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + resultJSON, _ := json.MarshalIndent(result.Result, "", " ") + fmt.Println(string(resultJSON)) +} +``` + +### Get Transaction Hex + +```go +package main + +import ( + "encoding/hex" + "fmt" + "time" + "github.com/steemit/steemgosdk" + "github.com/steemit/steemutil/protocol" + "github.com/steemit/steemutil/transaction" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + api := client.GetAPI() + + // Get dynamic global properties + dgp, err := api.GetDynamicGlobalProperties() + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + // Create a transaction + refBlockPrefix, _ := transaction.RefBlockPrefix(dgp.HeadBlockId) + expiration := time.Now().Add(600 * time.Second) + tx := transaction.NewSignedTransaction(&transaction.Transaction{ + RefBlockNum: transaction.RefBlockNum(dgp.HeadBlockNumber), + RefBlockPrefix: refBlockPrefix, + Expiration: &protocol.Time{Time: &expiration}, + }) + + // Add an operation + voteOp := &protocol.VoteOperation{ + Voter: "your-account-name", + Author: "steemit", + Permlink: "firstpost", + Weight: 10000, + } + tx.PushOperation(voteOp) + + // Get transaction hex + txHex, err := api.GetTransactionHex(tx) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + // Serialize transaction locally for comparison + txBytes, _ := tx.Serialize() + localHex := hex.EncodeToString(txBytes) + + fmt.Printf("Transaction hex from API: %v\n", txHex) + fmt.Printf("Local transaction hex: %s00\n", localHex) +} +``` + +## Auth Examples + +## Auth Examples + +### Generate Keys from Account Name and Password + +```go +package main + +import ( + "fmt" + "github.com/steemit/steemgosdk" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + auth := client.GetAuth() + + accountName := "your-account-name" + password := "your-password" + roles := []string{"owner", "active", "posting", "memo"} + + // Generate public keys + pubKeys, err := auth.GenerateKeys(accountName, password, roles) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + fmt.Printf("Owner key: %s\n", pubKeys["owner"]) + fmt.Printf("Active key: %s\n", pubKeys["active"]) + fmt.Printf("Posting key: %s\n", pubKeys["posting"]) + fmt.Printf("Memo key: %s\n", pubKeys["memo"]) +} +``` + +### Get Private Keys (WIFs) + +```go +package main + +import ( + "fmt" + "github.com/steemit/steemgosdk" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + auth := client.GetAuth() + + accountName := "your-account-name" + password := "your-password" + roles := []string{"posting", "active"} + + // Get private keys and public keys + keys, err := auth.GetPrivateKeys(accountName, password, roles) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + fmt.Printf("Posting WIF: %s\n", keys["posting"]) + fmt.Printf("Posting Public Key: %s\n", keys["postingPubkey"]) + fmt.Printf("Active WIF: %s\n", keys["active"]) + fmt.Printf("Active Public Key: %s\n", keys["activePubkey"]) +} +``` + +### Convert Account Name and Password to WIF + +```go +package main + +import ( + "fmt" + "github.com/steemit/steemgosdk" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + auth := client.GetAuth() + + accountName := "your-account-name" + password := "your-password" + role := "posting" + + // Convert to WIF + wif, err := auth.ToWif(accountName, password, role) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + fmt.Printf("WIF for %s role: %s\n", role, wif) +} +``` + +### Validate WIF and Public Key + +```go +package main + +import ( + "fmt" + "github.com/steemit/steemgosdk" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + auth := client.GetAuth() + + // WARNING: This is a test/example key. NEVER use it in production! + wif := "5JRaypasxMx1L97ZUX7YuC5Psb5EAbF821kkAGtBj7xCJFQcbLg" + pubKey := "STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA" + + // Check if WIF is valid + isWif := auth.IsWif(wif) + fmt.Printf("Is valid WIF: %v\n", isWif) + + // Check if public key is valid + isPubkey := auth.IsPubkey(pubKey) + fmt.Printf("Is valid public key: %v\n", isPubkey) + + // Verify WIF matches public key + isValid := auth.WifIsValid(wif, pubKey) + fmt.Printf("WIF matches public key: %v\n", isValid) + + // Convert WIF to public key + derivedPubKey, err := auth.WifToPublic(wif) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + fmt.Printf("Derived public key: %s\n", derivedPubKey) +} +``` + +### Encrypt and Decrypt Memo + +```go +package main + +import ( + "fmt" + "github.com/steemit/steemgosdk" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + auth := client.GetAuth() + + // Sender's memo private key + // WARNING: This is a test/example key. NEVER use it in production! + senderMemoWif := "5JRaypasxMx1L97ZUX7YuC5Psb5EAbF821kkAGtBj7xCJFQcbLg" + + // Recipient's memo public key + recipientMemoKey := "STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA" + + // Original message (must start with '#' to be encrypted) + originalMemo := "#This is a secret message" + + // Encrypt memo + encryptedMemo, err := auth.EncodeMemo(senderMemoWif, recipientMemoKey, originalMemo) + if err != nil { + fmt.Printf("Error encrypting: %v\n", err) + return + } + fmt.Printf("Encrypted memo: %s\n", encryptedMemo) + + // Decrypt memo (recipient uses their memo private key) + // WARNING: This is a test/example key. NEVER use it in production! + recipientMemoWif := "5JRaypasxMx1L97ZUX7YuC5Psb5EAbF821kkAGtBj7xCJFQcbLg" + decryptedMemo, err := auth.DecodeMemo(recipientMemoWif, encryptedMemo) + if err != nil { + fmt.Printf("Error decrypting: %v\n", err) + return + } + fmt.Printf("Decrypted memo: %s\n", decryptedMemo) +} +``` + +## Steem URI Examples + +## Steem URI Examples + +The `steemuri` package implements the [Steem URI Signing Protocol](https://github.com/steemit/steem-uri-spec), allowing you to encode Steem transactions into shareable `steem://` links and decode them back. + +### Encode a Single Operation to URI + +```go +package main + +import ( + "fmt" + "github.com/steemit/steemgosdk/steemuri" +) + +func main() { + // Create a vote operation (as a JSON-compatible slice) + voteOp := []interface{}{"vote", map[string]interface{}{ + "voter": "alice", + "author": "bob", + "permlink": "my-post", + "weight": 10000, + }} + + // Encode to a steem URI (default protocol: web+steem) + uri, err := steemuri.EncodeOp(voteOp, steemuri.Parameters{}, "") + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + fmt.Println(uri) + // Output: web+steem://sign/op/WyJ2b3RlIix7... +} +``` + +### Encode with Parameters + +```go +// Encode with signer and callback URL +params := steemuri.Parameters{ + Signer: "alice", + Callback: "https://myapp.com/callback?tx={{id}}", +} + +uri, err := steemuri.EncodeOp(voteOp, params, steemuri.ProtocolSteem) +// Output: steem://sign/op/...?s=alice&cb=... +``` + +### Encode Multiple Operations + +```go +transferOp := []interface{}{"transfer", map[string]interface{}{ + "from": "alice", + "to": "bob", + "amount": "1.000 STEEM", + "memo": "Hello!", +}} + +ops := []interface{}{voteOp, transferOp} +uri, err := steemuri.EncodeOps(ops, steemuri.Parameters{}, "") +``` + +### Decode a Steem URI + +```go +result, err := steemuri.Decode(uri) +if err != nil { + fmt.Printf("Error: %v\n", err) + return +} + +fmt.Printf("Transaction: %v\n", result.Tx) +fmt.Printf("Signer: %s\n", result.Params.Signer) +fmt.Printf("Callback: %s\n", result.Params.Callback) +``` + +### Resolve Transaction Placeholders + +After decoding, transactions may contain placeholders (`__signer`, `__ref_block_num`, etc.) that need to be resolved before signing: + +```go +result, _ := steemuri.Decode(uri) + +resolved, err := steemuri.ResolveTransaction(result.Tx, result.Params, steemuri.ResolveOptions{ + RefBlockNum: 1234, + RefBlockPrefix: 5678900, + Expiration: "2025-01-01T00:00:00", + Signers: []string{"alice", "bob"}, + PreferredSigner: "alice", +}) +if err != nil { + fmt.Printf("Error: %v\n", err) + return +} + +fmt.Printf("Signer: %s\n", resolved.Signer) +fmt.Printf("Resolved TX: %v\n", resolved.Tx) +``` + +### Resolve Callback URL + +After a transaction is confirmed, resolve template variables in the callback URL: + +```go +callbackURL := "https://myapp.com/cb?sig={{sig}}&id={{id}}&block={{block}}&txn={{txn}}" +ctx := steemuri.TransactionConfirmation{ + Sig: "2050a...", + ID: "abc123", + Block: 12345678, + Txn: 0, +} + +resolved := steemuri.ResolveCallback(callbackURL, ctx) +fmt.Println(resolved) +// Output: https://myapp.com/cb?sig=2050a...&id=abc123&block=12345678&txn=0 +``` + +## Where to go next + +- [Broadcasting operations](/tutorials/steemgosdk/broadcast.html) - votes, transfers, comments, beneficiaries, custom_json and complete end-to-end examples. +- [SignedCall API](/tutorials/steemgosdk/signed-call.html) - authenticated JSON-RPC calls from Go. diff --git a/docs/tutorials/steemgosdk/signed-call.md b/docs/tutorials/steemgosdk/signed-call.md new file mode 100644 index 0000000..3245eb1 --- /dev/null +++ b/docs/tutorials/steemgosdk/signed-call.md @@ -0,0 +1,586 @@ +# SignedCall API Documentation + +## Overview + +The `SignedCall` functionality provides authenticated JSON-RPC calls to the Steem blockchain. It uses cryptographic signatures to prove account ownership and access private or restricted data. + +This implementation is fully compatible with the `steem-js` library's `signedCall` method, ensuring interoperability between JavaScript and Go applications. + +## Features + +- **Cryptographic Authentication**: Proves account ownership without transmitting private keys +- **Replay Protection**: Uses unique nonces and timestamps to prevent replay attacks +- **Time-based Expiration**: Signatures expire after 60 seconds for security +- **Multiple Key Support**: Can sign with multiple private keys simultaneously +- **HTTP Only**: Requires HTTP/HTTPS transport for security reasons + +## Quick Start + +### Basic Usage + +```go +package main + +import ( + "fmt" + "log" + + "github.com/steemit/steemgosdk" + "github.com/steemit/steemgosdk/consts" +) + +func main() { + // Create client + client := steemgosdk.GetClient("https://api.steemit.com") + client.AccountName = "your-account" + + // Import your private key + err := client.ImportWif(consts.ACTIVE_KEY, "your-private-key-wif") + if err != nil { + log.Fatal(err) + } + + // Make a signed call + var accounts []map[string]interface{} + err = client.SignedCallWithResult( + "condenser_api.get_accounts", + []interface{}{[]string{"your-account"}}, + consts.ACTIVE_KEY, + &accounts, + ) + if err != nil { + log.Fatal(err) + } + + fmt.Printf("Account: %v\n", accounts[0]["name"]) +} +``` + +## API Reference + +### Client Methods + +#### `SignedCall(method, params, keyType) -> (*RpcResultData, error)` + +Makes a signed RPC call using stored credentials. + +**Parameters:** +- `method` (string): The RPC method to call (e.g., "condenser_api.get_accounts") +- `params` ([]interface{}): Parameters for the RPC method +- `keyType` (string): Which private key to use ("active", "posting", "owner", "memo") + +**Returns:** +- `*RpcResultData`: Raw RPC response data +- `error`: Error if the call fails + +#### `SignedCallWithResult(method, params, keyType, result) -> error` + +Makes a signed RPC call and unmarshals the result into the provided object. + +**Parameters:** +- `method` (string): The RPC method to call +- `params` ([]interface{}): Parameters for the RPC method +- `keyType` (string): Which private key to use +- `result` (interface{}): Pointer to object to unmarshal result into + +**Returns:** +- `error`: Error if the call fails or unmarshaling fails + +### API Methods + +#### `SignedCall(method, params, account, privateKey) -> (*RpcResultData, error)` + +Low-level signed call method. + +**Parameters:** +- `method` (string): The RPC method to call +- `params` ([]interface{}): Parameters for the RPC method +- `account` (string): Account name to sign as +- `privateKey` (string): Private key in WIF format + +**Returns:** +- `*RpcResultData`: Raw RPC response data +- `error`: Error if the call fails + +#### `SignedCallWithResult(method, params, account, privateKey, result) -> error` + +Low-level signed call with result unmarshaling. + +## Common Use Cases + +### 1. Get Account Information + +```go +var accounts []map[string]interface{} +err := client.SignedCallWithResult( + "condenser_api.get_accounts", + []interface{}{[]string{"username"}}, + consts.ACTIVE_KEY, + &accounts, +) +``` + +### 2. Get Account History + +```go +var history []interface{} +err := client.SignedCallWithResult( + "condenser_api.get_account_history", + []interface{}{"username", -1, 100}, + consts.ACTIVE_KEY, + &history, +) +``` + +### 3. Get Followers/Following + +```go +var followers []interface{} +err := client.SignedCallWithResult( + "condenser_api.get_followers", + []interface{}{"username", "", "blog", 100}, + consts.POSTING_KEY, + &followers, +) +``` + +### 4. Batch Operations + +```go +// Multiple signed calls +operations := []struct { + method string + params []interface{} +}{ + {"condenser_api.get_accounts", []interface{}{[]string{"username"}}}, + {"condenser_api.get_account_history", []interface{}{"username", -1, 10}}, + {"condenser_api.get_followers", []interface{}{"username", "", "blog", 10}}, +} + +for _, op := range operations { + var result interface{} + err := client.SignedCallWithResult(op.method, op.params, consts.ACTIVE_KEY, &result) + if err != nil { + log.Printf("Operation %s failed: %v", op.method, err) + continue + } + // Process result... +} +``` + +## Error Handling + +### Common Errors + +#### Transport Error +```go +// Error: "signed calls can only be made when using HTTP transport" +client := steemgosdk.GetClient("wss://api.steemit.com") // WebSocket not supported +``` + +#### Authentication Error +```go +// Error: "invalid key type: invalid_key" +err := client.SignedCall(method, params, "invalid_key") +``` + +#### Missing Credentials +```go +// Error: "account name not set" +client := steemgosdk.GetClient(url) +// client.AccountName not set +err := client.SignedCall(method, params, consts.ACTIVE_KEY) +``` + +#### Signature Expiration +```go +// Error: "signature expired" +// Occurs when request takes longer than 60 seconds to reach server +``` + +### Error Handling Pattern + +```go +func makeSignedCall(client *steemgosdk.Client, method string, params []interface{}) { + var result interface{} + err := client.SignedCallWithResult(method, params, consts.ACTIVE_KEY, &result) + + switch { + case err == nil: + // Success + fmt.Printf("Call succeeded: %v\n", result) + + case strings.Contains(err.Error(), "transport"): + // Transport error - check URL scheme + log.Printf("Transport error: %v", err) + + case strings.Contains(err.Error(), "expired"): + // Signature expired - retry + log.Printf("Signature expired, retrying: %v", err) + // Implement retry logic + + case strings.Contains(err.Error(), "key"): + // Key-related error - check credentials + log.Printf("Authentication error: %v", err) + + default: + // Other error + log.Printf("Unexpected error: %v", err) + } +} +``` + +## Security Considerations + +### Best Practices + +1. **Use HTTPS Only**: Always use HTTPS endpoints for signed calls +2. **Validate Private Keys**: Verify key format before making calls +3. **Handle Expiration**: Implement retry logic for expired signatures +4. **Secure Key Storage**: Never log or expose private keys +5. **Environment Variables**: Use environment variables for sensitive data + +### Security Features + +- **No Key Transmission**: Private keys never leave your application +- **Unique Nonces**: Each request uses a unique 8-byte random nonce +- **Timestamp Validation**: Signatures expire after 60 seconds +- **Cross-Protocol Protection**: Uses protocol-specific signing constant + +### Example Secure Implementation + +```go +package main + +import ( + "os" + "log" + "github.com/steemit/steemgosdk" + "github.com/steemit/steemgosdk/consts" +) + +func main() { + // Get credentials from environment + account := os.Getenv("STEEM_ACCOUNT") + password := os.Getenv("STEEM_PASSWORD") + + if account == "" || password == "" { + log.Fatal("STEEM_ACCOUNT and STEEM_PASSWORD must be set") + } + + // Create client with HTTPS endpoint + client := steemgosdk.GetClient("https://api.steemit.com") + client.AccountName = account + + // Generate keys from password (more secure than storing WIF) + auth := client.GetAuth() + keys, err := auth.GetPrivateKeys(account, password) + if err != nil { + log.Fatalf("Failed to generate keys: %v", err) + } + + // Import only the keys you need + if err := client.ImportWif(consts.ACTIVE_KEY, keys.Active); err != nil { + log.Fatalf("Failed to import active key: %v", err) + } + + // Make signed calls... +} +``` + +## Advanced Usage + +### Custom Verification + +```go +import "github.com/steemit/steemutil/rpc" + +// Custom verification function +func customVerifyFunc(message []byte, signatures []string, account string) error { + // Implement custom signature verification logic + // This could involve checking against blockchain account keys + return nil +} + +// Use with low-level RPC signing +request := &rpc.RpcRequest{ + Method: "condenser_api.get_accounts", + Params: []interface{}{[]string{"username"}}, + ID: 1, +} + +signedRequest, err := rpc.Sign(request, "username", []string{"private-key"}) +if err != nil { + return err +} + +params, err := rpc.Validate(signedRequest, customVerifyFunc) +if err != nil { + return err +} +``` + +### Multiple Key Signing + +```go +// Sign with multiple keys +privateKeys := []string{ + "active-key-wif", + "posting-key-wif", +} + +signedRequest, err := rpc.Sign(request, account, privateKeys) +// signedRequest will contain multiple signatures +``` + +## Testing + +### Unit Tests + +```go +func TestSignedCall(t *testing.T) { + client := steemgosdk.GetClient("https://api.steemit.com") + client.AccountName = "testaccount" + + // Import test key + err := client.ImportWif(consts.ACTIVE_KEY, "test-private-key") + if err != nil { + t.Fatal(err) + } + + // Test signed call + var result interface{} + err = client.SignedCallWithResult( + "condenser_api.get_dynamic_global_properties", + []interface{}{}, + consts.ACTIVE_KEY, + &result, + ) + + // In test environment, expect network error, not validation error + if err != nil && !strings.Contains(err.Error(), "network") { + t.Errorf("Unexpected error: %v", err) + } +} +``` + +### Integration Tests + +See `test-gosdk/examples/signed_call/main.go` for a complete integration test example. + +## Compatibility + +This implementation is fully compatible with `steem-js` signed calls: + +- Uses the same signing algorithm and message format +- Generates identical signature structures +- Supports the same security features (nonces, timestamps, expiration) +- Can validate signatures created by `steem-js` and vice versa + +## Performance + +- **Signing Overhead**: ~1-5ms per signature +- **Network Latency**: Depends on node response time +- **Memory Usage**: Minimal additional overhead over regular RPC calls +- **Concurrent Calls**: Fully thread-safe, supports concurrent signed calls + +## Troubleshooting + +### Common Issues + +1. **"Transport Error"**: Ensure you're using HTTP/HTTPS, not WebSocket +2. **"Invalid Key"**: Verify private key format and permissions +3. **"Account Not Set"**: Set `client.AccountName` before making calls +4. **"Signature Expired"**: Implement retry logic for slow networks +5. **"Network Error"**: Check node availability and network connectivity + +### Debug Mode + +Set the `DEBUG` environment variable to enable detailed logging: + +```bash +DEBUG=1 go run your-program.go +``` + +This will show request/response details and signing information. + +--- + +## More SignedCall Examples + +## SignedCall Examples + +### Basic Signed API Call + +```go +package main + +import ( + "fmt" + "log" + "github.com/steemit/steemgosdk" + "github.com/steemit/steemgosdk/consts" +) + +func main() { + client := steemgosdk.GetClient("https://api.steemit.com") + client.AccountName = "your-account" + + // Import your active key + err := client.ImportWif(consts.ACTIVE_KEY, "your-active-key-wif") + if err != nil { + log.Fatal(err) + } + + // Get account information with authentication + var accounts []map[string]interface{} + err = client.SignedCallWithResult( + "condenser_api.get_accounts", + []interface{}{[]string{"your-account"}}, + consts.ACTIVE_KEY, + &accounts, + ) + if err != nil { + log.Fatal(err) + } + + if len(accounts) > 0 { + account := accounts[0] + fmt.Printf("Account: %s\n", account["name"]) + fmt.Printf("Balance: %s\n", account["balance"]) + fmt.Printf("SBD Balance: %s\n", account["sbd_balance"]) + } +} +``` + +### Get Account History (Authenticated) + +```go +func getAccountHistory(client *steemgosdk.Client, account string) { + var history []interface{} + err := client.SignedCallWithResult( + "condenser_api.get_account_history", + []interface{}{account, -1, 100}, + consts.ACTIVE_KEY, + &history, + ) + if err != nil { + log.Printf("Failed to get account history: %v", err) + return + } + + fmt.Printf("Retrieved %d history entries\n", len(history)) + + // Process history entries + for _, entry := range history { + if entryArray, ok := entry.([]interface{}); ok && len(entryArray) >= 2 { + if op, ok := entryArray[1].(map[string]interface{}); ok { + opType := op["op"].([]interface{})[0] + fmt.Printf("Operation: %s\n", opType) + } + } + } +} +``` + +### Batch Signed Calls + +```go +func performBatchSignedCalls(client *steemgosdk.Client, account string) { + operations := []struct { + name string + method string + params []interface{} + }{ + { + name: "Get Account Info", + method: "condenser_api.get_accounts", + params: []interface{}{[]string{account}}, + }, + { + name: "Get Followers", + method: "condenser_api.get_followers", + params: []interface{}{account, "", "blog", 100}, + }, + { + name: "Get Following", + method: "condenser_api.get_following", + params: []interface{}{account, "", "blog", 100}, + }, + } + + for _, op := range operations { + fmt.Printf("Executing: %s...", op.name) + + var result interface{} + err := client.SignedCallWithResult(op.method, op.params, consts.ACTIVE_KEY, &result) + if err != nil { + fmt.Printf(" Failed: %v\n", err) + continue + } + + if resultArray, ok := result.([]interface{}); ok { + fmt.Printf(" Success (%d items)\n", len(resultArray)) + } else { + fmt.Printf(" Success\n") + } + } +} +``` + +### Error Handling for Signed Calls + +```go +func robustSignedCall(client *steemgosdk.Client, method string, params []interface{}) { + var result interface{} + err := client.SignedCallWithResult(method, params, consts.ACTIVE_KEY, &result) + + switch { + case err == nil: + fmt.Printf("Call succeeded: %v\n", result) + + case strings.Contains(err.Error(), "transport"): + log.Printf("Transport error - check URL scheme: %v", err) + + case strings.Contains(err.Error(), "expired"): + log.Printf("Signature expired - implement retry logic: %v", err) + + case strings.Contains(err.Error(), "key"): + log.Printf("Authentication error - check credentials: %v", err) + + default: + log.Printf("Unexpected error: %v", err) + } +} +``` + +### Using Direct API Methods + +```go +func directAPISignedCall() { + client := steemgosdk.GetClient("https://api.steemit.com") + api := client.GetAPI() + + // Direct API call with explicit credentials + response, err := api.SignedCall( + "condenser_api.get_dynamic_global_properties", + []interface{}{}, + "your-account", + "your-private-key-wif", + ) + if err != nil { + log.Fatal(err) + } + + var dgp map[string]interface{} + if err := json.Unmarshal(response.Result, &dgp); err != nil { + log.Fatal(err) + } + + fmt.Printf("Head block: %.0f\n", dgp["head_block_number"]) +} +``` + +## Where to go next + +The steem-js side of the same protocol is covered in [steem-js: Signed Calls and Signature Verification](/tutorials/steem-js/signed-calls.html); the two implementations are wire-compatible.