Compare commits

...

19 Commits

Author SHA1 Message Date
Denis Angell
d2b8a0b928 patch for @transia 2023-07-19 03:07:21 +02:00
dependabot[bot]
82436918b7 build(deps-dev): bump webpack-bundle-analyzer from 4.8.0 to 4.9.0 (#2367) 2023-07-07 14:34:26 +00:00
dependabot[bot]
74de24cf75 build(deps-dev): bump @types/chai from 4.3.4 to 4.3.5 (#2363)
Bumps [@types/chai](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/chai) from 4.3.4 to 4.3.5.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/chai)

---
updated-dependencies:
- dependency-name: "@types/chai"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-07-05 18:16:19 -05:00
dependabot[bot]
eccba409c0 build(deps-dev): bump webpack from 5.83.0 to 5.88.1 (#2365) 2023-07-05 16:46:15 +00:00
dependabot[bot]
c02b33be08 build(deps-dev): bump karma-chrome-launcher from 3.1.1 to 3.2.0 (#2366) 2023-07-05 16:03:10 +00:00
Caleb Kniffen
dbd5852ba6 feat(types): Export most of the types (#2360)
Expose most of the types in the `xrpl` package. Some renames will only
affect you if you were deep importing these types previously.

Renames of deep importable types:
- `methods/bookOffers`: `TakerAmount` -> `BookOfferCurrency`
- `methods/accountLines`: `Trustline` -> `AccountLinesTrustline`
2023-07-03 17:03:51 -05:00
Caleb Kniffen
5925ad2f00 feat: expose LedgerEntry singletons (#2358)
Adds the new fields for `XRPFees` amendment and id for the `FeeSettings`
singleton ledger entry.

Closes #2219
2023-07-03 16:34:42 -05:00
Caleb Kniffen
9b0c1e53e3 fix(types): SignerList was missing WalletLocator (#2359)
`SignerEntry` on `SignerList` (LedgerEntry) was missing `WalletLocator`.

This was found while trying to use types on the xrpl.org explorer.
2023-07-03 11:08:07 -05:00
Caleb Kniffen
23256aed5d feat(types): Update FeeSettings and add id (#2357)
Adds the new fields for `XRPFees` amendment and id for the `FeeSettings`
singleton ledger entry.

Closes #2219
2023-06-29 16:27:00 -05:00
Caleb Kniffen
70500dcc15 feat(types): Add pseudo transactions (#2351)
Add types for `EnableAmendment`, `SetFee`, and `UNLModify` transactions.
2023-06-29 14:20:36 -05:00
Caleb Kniffen
fd0b2275c1 feat: enable 1.10.0 amendments for tests (#2356)
- `NFTokenMint` needs `NonFungibleTokensV1_1` enabled instead of `NonFungibleTokensV1` .  
- `fee_ref` is no longer returned after `XRPFees` amendment is enabled.
2023-06-29 13:10:52 -05:00
Caleb Kniffen
97552cc1a5 feat(types): define new account_flags field (#2352)
The `account_flags` field was added to the `account_info` response for `rippled@1.11.0`
2023-06-27 15:14:48 -05:00
Caleb Kniffen
b152ebc4ce feat: add ledger entry types for NFTokens (#2349)
Add `NFToken`, `NFTokenPage`, and `NFTokenOffer`
2023-06-26 12:57:47 -05:00
Caleb Kniffen
b6d6fafebc feat: cleanup types and add missing request fields (#2346)
- Add `ledger_hash` and `ledger_index` to `account_nfts`,
`nft_buy_offers`, and `nft_sell_offers` requests.
- Add `nft_page` to `ledger_entry` request.
- Create `LookupByLedgerRequest` to clean up `ledger_hash` and
`ledger_index` which are optional on most request objects.

Closes #2135
2023-06-26 12:47:15 -05:00
Jackson Mills
dc51e3a704 Update getNFTokenID to properly handle binary blob (#2247)
* Update NFTokenMint test

* Ensure the binary version works as well

* Remove meta being undefined in txResponse

* Remove error test

* Re-add test, error, and lint

* Add meta to test, and add string to allowed type

* Re-add meta being undefined with proper docs
2023-06-23 16:17:29 -07:00
Mayukha Vadari
6228f91c00 test: run snippets in CI (#2345)
* run snippets in CI

* add name, try to avoid building

* better printing

* refactors

* fix getTransaction test
2023-06-22 13:26:16 -04:00
Caleb Kniffen
fa98bd8d26 feat: add missing AccountRoot fields (#2347)
Add `BurnedNFTokens`, `FirstNFTSequence`, `MintedNFTokens`,
`NFTokenMinter`, and `WalletLocator` to `AccountRoot`.
2023-06-21 12:49:34 -05:00
justinr1234
6fa3eacd19 fix: CJS default exports (#2340) 2023-06-20 20:55:47 -05:00
Denis Angell
5b0989df51 feature NetworkID (#2216)
Added network id to the base transaction
Added network id to the server_info response
Added network id to the binary codec
Added network id to client and modify on client.connect()
Added network id to autofill when rippled_version is 1.11.0 or later or network is hooks testnet

Co-authored-by: Phu Pham <ppham@ripple.com>
Co-authored-by: pdp2121 <71317875+pdp2121@users.noreply.github.com>
Co-authored-by: Jackson Mills <aim4math@gmail.com>
Co-authored-by: Mayukha Vadari <mvadari@gmail.com>
2023-06-14 15:15:18 -04:00
101 changed files with 3701 additions and 2977 deletions

View File

@@ -110,7 +110,7 @@ validators.txt
# If you need the version of rippled to be more up to date, you may need to make a comment on this repo: https://github.com/WietseWind/docker-rippled
[amendments]
# Devnet amendments as of March 28th, 2023
# Devnet amendments as of June 28th, 2023
B4E4F5D2D6FB84DF7399960A732309C9FD530EAE5941838160042833625A6076 NegativeUNL
DF8B4536989BDACE3F934F29423848B9F1D76D09BE6A1FCFE7E7F06AA26ABEAD fixRemoveNFTokenAutoTrustLine
3C43D9A973AA4443EF3FC38E42DD306160FBFFDAB901CD8BAA15D09F2597EB87 NonFungibleTokensV1
@@ -156,3 +156,11 @@ E2E6F2866106419B88C50045ACE96368558C345566AC8F2BDF5A5B5587F0E6FA fix1368
42EEA5E28A97824821D4EF97081FE36A54E9593C6E4F20CBAE098C69D2E072DC fix1373
4C97EBA926031A7CF7D7B36FDE3ED66DDA5421192D63DE53FFB46E43B9DC8373 MultiSign
157D2D480E006395B76F948E3E07A45A05FE10230D88A7993C71F97AE4B1F2D1 Checks
32A122F1352A4C7B3A6D790362CC34749C5E57FCE896377BFDC6CCD14F6CD627 NonFungibleTokensV1_1
# 1.10.0 Amendments
47C3002ABA31628447E8E9A8B315FAA935CE30183F9A9B86845E469CA2CDC3DF DisallowIncoming
73761231F7F3D94EC3D8C63D91BDD0D89045C6F71B917D1925C01253515A6669 fixNonFungibleTokensV1_2
F1ED6B4A411D8B872E65B9DCB4C8B100375B0DD3D62D07192E011D6D7F339013 fixTrustLinesToSelf
2E2FB9CF8A44EB80F4694D38AADAE9B8B7ADAFD2F092E10068E61C98C4F092B0 fixUniversalNumber
75A7E01C505DD5A179DFE3E000A9B6F1EDDEB55A12F95579A23E15B15DC8BE5A ImmediateOfferKilled
93E516234E35E08CA689FA33A6D38E103881F8DCB53023F728C307AA89D515A7 XRPFees

View File

@@ -195,3 +195,45 @@ jobs:
- name: Stop docker container
if: always()
run: docker stop rippled-service
snippets:
runs-on: ubuntu-latest
timeout-minutes: 10
strategy:
matrix:
node-version: [14.x, 16.x, 18.x, 20.x]
steps:
- uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- name: Setup npm version 9
run: |
npm i -g npm@9 --registry=https://registry.npmjs.org
- name: Cache node modules
id: cache-nodemodules
uses: actions/cache@v3
env:
cache-name: cache-node-modules
with:
# caching node_modules
path: |
node_modules
*/*/node_modules
key: ${{ runner.os }}-deps-${{ matrix.node-version }}-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-deps-${{ matrix.node-version }}-
${{ runner.os }}-deps-
- name: Install Dependencies
if: steps.cache-nodemodules.outputs.cache-hit != 'true'
run: npm ci
- run: npm run build
- name: Run Snippets
run: (for i in packages/xrpl/snippets/src/*.ts; do echo "Running $i" && npx ts-node $i || exit 1; done)

5082
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -13,10 +13,10 @@
"update:confirm": "npx npm-check-updates --configFileName .ncurc.json -u"
},
"dependencies": {
"ripple-address-codec": "file:packages/ripple-address-codec",
"ripple-binary-codec": "file:packages/ripple-binary-codec",
"ripple-keypairs": "file:packages/ripple-keypairs",
"xrpl": "file:packages/xrpl"
"@transia/ripple-address-codec": "file:packages/ripple-address-codec",
"@transia/ripple-binary-codec": "file:packages/ripple-binary-codec",
"@transia/ripple-keypairs": "file:packages/ripple-keypairs",
"@transia/xrpl": "file:packages/xrpl"
},
"devDependencies": {
"@types/brorand": "^1.0.30",

View File

@@ -1,5 +1,5 @@
{
"name": "ripple-address-codec",
"name": "@transia/ripple-address-codec",
"version": "4.3.0",
"description": "encodes/decodes base58 encoded XRP Ledger identifiers",
"files": [
@@ -15,7 +15,7 @@
},
"repository": {
"type": "git",
"url": "git@github.com:XRPLF/xrpl.js.git"
"url": "git@github.com/Transia-RnD/xrpl.js/tree/beta"
},
"prepublish": "tsc -b",
"prepublishOnly": "tslint -b ./ && jest",

View File

@@ -1,5 +1,5 @@
{
"name": "ripple-binary-codec",
"name": "@transia/ripple-binary-codec",
"version": "1.6.0",
"description": "XRP Ledger binary codec",
"files": [
@@ -17,7 +17,7 @@
"buffer": "6.0.3",
"create-hash": "^1.2.0",
"decimal.js": "^10.2.0",
"ripple-address-codec": "^4.3.0"
"@transia/ripple-address-codec": "^4.3.0"
},
"scripts": {
"build": "tsc -b && copyfiles ./src/enums/definitions.json ./dist/enums/",
@@ -28,7 +28,7 @@
},
"repository": {
"type": "git",
"url": "git@github.com:XRPLF/xrpl.js.git"
"url": "git@github.com/Transia-RnD/xrpl.js/tree/beta"
},
"bugs": {
"url": "https://github.com/XRPLF/xrpl.js/issues"

View File

@@ -321,6 +321,16 @@
"type": "UInt16"
}
],
[
"NetworkID",
{
"nth": 1,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"Flags",
{
@@ -2176,6 +2186,9 @@
"telCAN_NOT_QUEUE_BLOCKED": -389,
"telCAN_NOT_QUEUE_FEE": -388,
"telCAN_NOT_QUEUE_FULL": -387,
"telWRONG_NETWORK": -386,
"telREQUIRES_NETWORK_ID": -385,
"telNETWORK_ID_MAKES_TX_NON_CANONICAL": -384,
"temMALFORMED": -299,
"temBAD_AMOUNT": -298,

View File

@@ -3,7 +3,7 @@ import {
encodeAccountID,
isValidXAddress,
xAddressToClassicAddress,
} from 'ripple-address-codec'
} from '@transia/ripple-address-codec'
import { Hash160 } from './hash-160'
import { Buffer } from 'buffer/'

View File

@@ -5,7 +5,7 @@ import {
XrplDefinitionsBase,
} from '../enums'
import { SerializedType, JsonObject } from './serialized-type'
import { xAddressToClassicAddress, isValidXAddress } from 'ripple-address-codec'
import { xAddressToClassicAddress, isValidXAddress } from '@transia/ripple-address-codec'
import { BinaryParser } from '../serdes/binary-parser'
import { BinarySerializer, BytesList } from '../serdes/binary-serializer'
import { Buffer } from 'buffer/'

View File

@@ -1,7 +1,7 @@
const { coreTypes } = require('../src/types')
const Decimal = require('decimal.js')
const { encodeAccountID } = require('ripple-address-codec')
const { encodeAccountID } = require('@transia/ripple-address-codec')
const { binary } = require('../src/coretypes')
const { Amount, Hash160 } = coreTypes
const { makeParser, readJSON } = binary

View File

@@ -1,5 +1,5 @@
{
"name": "ripple-keypairs",
"name": "@transia/ripple-keypairs",
"version": "1.3.0",
"description": "Cryptographic key pairs for the XRP Ledger",
"scripts": {
@@ -21,11 +21,11 @@
"brorand": "^1.0.5",
"elliptic": "^6.5.4",
"hash.js": "^1.0.3",
"ripple-address-codec": "^4.3.0"
"@transia/ripple-address-codec": "^4.3.0"
},
"repository": {
"type": "git",
"url": "git@github.com:XRPLF/xrpl.js.git"
"url": "git@github.com/Transia-RnD/xrpl.js/tree/beta"
},
"license": "ISC",
"prettier": "@xrplf/prettier-config",

View File

@@ -3,7 +3,7 @@ import brorand = require('brorand')
import * as hashjs from 'hash.js'
import * as elliptic from 'elliptic'
import * as addressCodec from 'ripple-address-codec'
import * as addressCodec from '@transia/ripple-address-codec'
import { derivePrivateKey, accountPublicFromPublicGenerator } from './secp256k1'
import * as utils from './utils'

View File

@@ -1,5 +1,5 @@
import assert from 'assert'
import * as api from 'ripple-address-codec'
import * as api from '@transia/ripple-address-codec'
function toHex(bytes) {
return Buffer.from(bytes).toString('hex').toUpperCase()

View File

@@ -1,5 +1,5 @@
import assert from 'assert'
import * as api from 'ripple-address-codec'
import * as api from '@transia/ripple-address-codec'
function toHex(bytes: Buffer) {
return Buffer.from(bytes).toString('hex').toUpperCase()

View File

@@ -59,9 +59,13 @@ module.exports = {
'no-shadow': 'off',
'@typescript-eslint/no-shadow': ['error'],
'jsdoc/check-examples': 'off',
// We want to use certain fields like "@interface" to make join types treated as interfaces.
'jsdoc/check-tag-names': 'off',
'jsdoc/require-hyphen-before-param-description': 'off',
'tsdoc/syntax': 'off',
'jsdoc/require-description-complete-sentence': 'off',
'import/prefer-default-export': 'off',
},
overrides: [
{

View File

@@ -3,12 +3,34 @@
Subscribe to [the **xrpl-announce** mailing list](https://groups.google.com/g/xrpl-announce) for release announcements. We recommend that xrpl.js (ripple-lib) users stay up-to-date with the latest stable release.
## Unreleased
### Added
* Add `BurnedNFTokens`, `FirstNFTSequence`, `MintedNFTokens`,
`NFTokenMinter`, and `WalletLocator` to `AccountRoot`.
* Add `ledger_hash` and `ledger_index` to `account_nfts`,
`nft_buy_offers`, and `nft_sell_offers` requests.
* Add `nft_page` to `ledger_entry` request.
* Add types for `NFTokenPage` and `NFTokenOffer` LedgerEntries.
* Add type for NFToken object that is stored on a `NFTokenPage`.
* Add type for `account_info`'s `account_flags` property.
* Add types for `EnableAmendment`, `SetFee`, and `UNLModify` transactions.
* Add the new fields for `XRPFees` amendment and id for the `FeeSettings`
* Add `FeeSettings`, `NegativeUNL`, and `Amendments` singleton ledger entry ids.
* Add `WalletLocator` to `SignerEntry` on `SignerList` (LedgerEntry).
* Export many nested types and interfaces
### Breaking
* If you were deep importing these types previously you will need to import them from `xrpl` and rename them:
* `methods/accountLines`: `Trustline` -> `AccountLinesTrustline`
* `methods/bookOffers`: `TakerAmount` -> `BookOfferCurrency`
* `methods/ledgerData`: `BinaryLedgerEntry` -> `LedgerDataBinaryLedgerEntry`
## 2.8.0 (2023-06-13)
### Added
* Adds support for npm v9
### Fixed
* `getNFTokenID` now also accepts metadata from `tx` in binary format
* Fixed `ServerState.transitions` typing, it is now a string instead of a number. (Only used in return from `server_state` request)
* Added `destination_amount` to `PathOption` which is returned as part of a `path_find` request
* Removed the `decode(encode(tx)) == tx` check from the wallet signing process

View File

@@ -1,5 +1,5 @@
{
"name": "xrpl",
"name": "@transia/xrpl",
"version": "2.8.1",
"license": "ISC",
"description": "A TypeScript/JavaScript API for interacting with the XRP Ledger in Node.js and the browser",
@@ -27,9 +27,9 @@
"bip39": "^3.0.4",
"https-proxy-agent": "^5.0.0",
"lodash": "^4.17.4",
"ripple-address-codec": "^4.3.0",
"ripple-binary-codec": "^1.6.0",
"ripple-keypairs": "^1.3.0",
"@transia/ripple-address-codec": "^4.3.0",
"@transia/ripple-binary-codec": "^1.6.0",
"@transia/ripple-keypairs": "^1.3.0",
"ws": "^8.2.2"
},
"devDependencies": {
@@ -75,7 +75,7 @@
"prettier": "@xrplf/prettier-config",
"repository": {
"type": "git",
"url": "git@github.com:XRPLF/xrpl.js.git"
"url": "git@github.com/Transia-RnD/xrpl.js/tree/beta"
},
"readmeFilename": "README.md",
"engines": {

View File

@@ -1,6 +1,6 @@
import { Client, LedgerResponse, TxResponse } from '../../src'
const client = new Client('wss://s.altnet.rippletest.net:51233')
const client = new Client('wss://s2.ripple.com:51233')
async function getTransaction(): Promise<void> {
await client.connect()
@@ -19,10 +19,11 @@ async function getTransaction(): Promise<void> {
})
console.log(tx)
// The meta field would be a string(hex) when the `binary` parameter is `true` for the `tx` request.
// The meta field can be undefined if the transaction has not been validated yet (and so has not changed the ledger).
if (tx.result.meta == null) {
throw new Error('meta not included in the response')
}
/*
* delivered_amount is the amount actually received by the destination account.
* Use this field to determine how much was delivered, regardless of whether the transaction is a partial payment.

View File

@@ -4,6 +4,7 @@ import {
AccountSet,
convertStringToHex,
SignerListSet,
Wallet,
} from '../../src'
const client = new Client('wss://s.altnet.rippletest.net:51233')
@@ -15,12 +16,8 @@ async function multisigning(): Promise<void> {
* In practice, users generally will not have all keys in one spot,
* hence, users need to implement a way to get signatures.
*/
const { wallet: wallet1 } = await client.fundWallet(null, {
usageContext: 'code snippets',
})
const { wallet: wallet2 } = await client.fundWallet(null, {
usageContext: 'code snippets',
})
const wallet1 = Wallet.generate()
const wallet2 = Wallet.generate()
const { wallet: walletMaster } = await client.fundWallet(null, {
usageContext: 'code snippets',
})

View File

@@ -1,7 +1,7 @@
import { IncomingMessage } from 'http'
import { request as httpsRequest, RequestOptions } from 'https'
import { isValidClassicAddress } from 'ripple-address-codec'
import { isValidClassicAddress } from '@transia/ripple-address-codec'
import type { Client } from '../client'
import { RippledError, XRPLFaucetError } from '../errors'
@@ -12,7 +12,7 @@ import {
getDefaultFaucetPath,
} from './defaultFaucets'
import Wallet from '.'
import { Wallet } from '.'
// Interval to check an account balance
const INTERVAL_SECONDS = 1

View File

@@ -7,20 +7,20 @@ import {
isValidXAddress,
xAddressToClassicAddress,
encodeSeed,
} from 'ripple-address-codec'
} from '@transia/ripple-address-codec'
import {
decode,
encodeForSigning,
encodeForMultisigning,
encode,
} from 'ripple-binary-codec'
} from '@transia/ripple-binary-codec'
import {
deriveAddress,
deriveKeypair,
generateSeed,
verify,
sign,
} from 'ripple-keypairs'
} from '@transia/ripple-keypairs'
import ECDSA from '../ECDSA'
import { ValidationError } from '../errors'
@@ -76,7 +76,7 @@ function hexFromBuffer(buffer: Buffer): string {
*
* @category Signing
*/
class Wallet {
export class Wallet {
public readonly publicKey: string
public readonly privateKey: string
public readonly classicAddress: string
@@ -502,5 +502,3 @@ function removeTrailingZeros(tx: Transaction): void {
tx.Amount.value = new BigNumber(tx.Amount.value).toString()
}
}
export default Wallet

View File

@@ -1,19 +1,19 @@
import { BigNumber } from 'bignumber.js'
import { flatMap } from 'lodash'
import { decodeAccountID } from 'ripple-address-codec'
import { decodeAccountID } from '@transia/ripple-address-codec'
import {
decode,
encode,
encodeForSigning,
encodeForSigningClaim,
} from 'ripple-binary-codec'
import { sign as signWithKeypair, verify } from 'ripple-keypairs'
} from '@transia/ripple-binary-codec'
import { sign as signWithKeypair, verify } from '@transia/ripple-keypairs'
import { ValidationError } from '../errors'
import { Signer } from '../models/common'
import { Transaction, validate } from '../models/transactions'
import Wallet from '.'
import { Wallet } from '.'
/**
* Takes several transactions with Signer fields (in object or blob form) and creates a
@@ -32,9 +32,13 @@ function multisign(transactions: Array<Transaction | string>): string {
throw new ValidationError('There were 0 transactions to multisign')
}
transactions.forEach((txOrBlob) => {
const tx: Transaction = getDecodedTransaction(txOrBlob)
const decodedTransactions: Transaction[] = transactions.map(
(txOrBlob: string | Transaction) => {
return getDecodedTransaction(txOrBlob)
},
)
decodedTransactions.forEach((tx) => {
/*
* This will throw a more clear error for JS users if any of the supplied transactions has incorrect formatting
*/
@@ -53,12 +57,6 @@ function multisign(transactions: Array<Transaction | string>): string {
}
})
const decodedTransactions: Transaction[] = transactions.map(
(txOrBlob: string | Transaction) => {
return getDecodedTransaction(txOrBlob)
},
)
validateTransactionEquivalence(decodedTransactions)
return encode(getTransactionWithAllSigners(decodedTransactions))
@@ -154,10 +152,11 @@ function compareSigners(left: Signer, right: Signer): number {
)
}
const NUM_BITS_IN_HEX = 16
function addressToBigNumber(address: string): BigNumber {
const hex = Buffer.from(decodeAccountID(address)).toString('hex')
const numberOfBitsInHex = 16
return new BigNumber(hex, numberOfBitsInHex)
return new BigNumber(hex, NUM_BITS_IN_HEX)
}
function getDecodedTransaction(txOrBlob: Transaction | string): Transaction {

View File

@@ -15,7 +15,7 @@ import { Client, ClientOptions } from '.'
*
* @category Clients
*/
export default class BroadcastClient extends Client {
export class BroadcastClient extends Client {
private readonly clients: Client[]
/**

View File

@@ -205,6 +205,18 @@ class Client extends EventEmitter {
*/
public readonly maxFeeXRP: string
/**
* Network ID of the server this client is connected to
*
*/
public networkID: number | undefined
/**
* Rippled Version used by the server this client is connected to
*
*/
public buildVersion: string | undefined
/**
* Creates a new Client with a websocket connection to a rippled server.
*
@@ -230,8 +242,8 @@ class Client extends EventEmitter {
this.emit('error', errorCode, errorMessage, data)
})
this.connection.on('connected', () => {
this.emit('connected')
this.connection.on('reconnect', () => {
this.connection.on('connected', () => this.emit('connected'))
})
this.connection.on('disconnected', (code: number) => {
@@ -568,6 +580,22 @@ class Client extends EventEmitter {
return results
}
/**
* Get networkID and buildVersion from server_info
*/
public async getServerInfo(): Promise<void> {
try {
const response = await this.request({
command: 'server_info',
})
this.networkID = response.result.info.network_id ?? undefined
this.buildVersion = response.result.info.build_version
} catch (error) {
// eslint-disable-next-line no-console -- Print the error to console but allows client to be connected.
console.error(error)
}
}
/**
* Tells the Client instance to connect to its rippled server.
*
@@ -588,7 +616,10 @@ class Client extends EventEmitter {
* @category Network
*/
public async connect(): Promise<void> {
return this.connection.connect()
return this.connection.connect().then(async () => {
await this.getServerInfo()
this.emit('connected')
})
}
/**

View File

@@ -1,9 +1,10 @@
import BigNumber from 'bignumber.js'
import { decode } from 'ripple-binary-codec'
import { decode } from '@transia/ripple-binary-codec'
import type {
AccountTxResponse,
Response,
ResponseWarning,
TransactionEntryResponse,
TransactionStream,
TxResponse,
@@ -111,7 +112,7 @@ export function handlePartialPayment(
response: Response,
): void {
if (hasPartialPayment(command, response)) {
const warnings = response.warnings ?? []
const warnings: ResponseWarning[] = response.warnings ?? []
const warning = {
id: WARN_PARTIAL_PAYMENT_CODE,

View File

@@ -1,5 +1,5 @@
// Broadcast client is experimental
export { default as BroadcastClient } from './client/BroadcastClient'
export { BroadcastClient } from './client/BroadcastClient'
export { Client, ClientOptions } from './client'
@@ -7,9 +7,11 @@ export * from './models'
export * from './utils'
export { default as ECDSA } from './ECDSA'
export * from './errors'
export { default as Wallet } from './Wallet'
export { Wallet } from './Wallet'
export { keyToRFC1751Mnemonic, rfc1751MnemonicToKey } from './Wallet/rfc1751'

View File

@@ -1,10 +1,10 @@
export type LedgerIndex = number | ('validated' | 'closed' | 'current')
interface XRP {
export interface XRP {
currency: 'XRP'
}
interface IssuedCurrency {
export interface IssuedCurrency {
currency: string
issuer: string
}
@@ -43,7 +43,7 @@ export type StreamType =
| 'server'
| 'validations'
interface PathStep {
export interface PathStep {
account?: string
currency?: string
issuer?: string
@@ -119,7 +119,7 @@ export interface NFTOffer {
}
/**
* One NFToken that might be returned from either an {@link NFTInfoResponse}
* One NFToken that might be returned from an {@link NFTInfoResponse}
*
* @category Responses
*/

View File

@@ -13,3 +13,4 @@ export {
} from './utils/flags'
export * from './methods'
export * from './transactions'
export * from './common'

View File

@@ -72,6 +72,16 @@ export default interface AccountRoot extends BaseLedgerEntry {
* account to each other.
*/
TransferRate?: number
/** An arbitrary 256-bit value that users can set. */
WalletLocator?: string
/** Total NFTokens this account's issued that have been burned. This number is always equal or less than MintedNFTokens. */
BurnedNFTokens?: number
/** The sequence that the account first minted an NFToken */
FirstNFTSequence: number
/** Total NFTokens have been minted by and on behalf of this account. */
MintedNFTokens?: number
/** Another account that can mint NFTokens on behalf of this account. */
NFTokenMinter?: string
}
/**

View File

@@ -1,6 +1,12 @@
import BaseLedgerEntry from './BaseLedgerEntry'
interface Majority {
/**
* The unique id for the Amendments object https://xrpl.org/amendments-object.html#amendments-id-format
*/
export const AMENDMENTS_ID =
'7DB0788C020F02780A673DC74757F23823FA3014C1866E72CC4CD8B226CD6EF4'
export interface Majority {
Majority: {
/** The Amendment ID of the pending amendment. */
Amendment: string

View File

@@ -1,17 +1,13 @@
import BaseLedgerEntry from './BaseLedgerEntry'
/**
* The FeeSettings object type contains the current base transaction cost and
* reserve amounts as determined by fee voting.
*
* @category Ledger Entries
* The unique id for the FeeSettings object https://xrpl.org/feesettings.html#feesettings-id-format
*/
export default interface FeeSettings extends BaseLedgerEntry {
LedgerEntryType: 'FeeSettings'
/**
* The transaction cost of the "reference transaction" in drops of XRP as
* hexadecimal.
*/
export const FEE_SETTINGS_ID =
'4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A651'
export interface FeeSettingsPreAmendmentFields {
/** The transaction cost of the "reference transaction" in drops of XRP as hexadecimal. */
BaseFee: string
/** The BaseFee translated into "fee units". */
ReferenceFeeUnits: number
@@ -19,9 +15,38 @@ export default interface FeeSettings extends BaseLedgerEntry {
ReserveBase: number
/** The incremental owner reserve for owning objects, as drops of XRP. */
ReserveIncrement: number
/**
* A bit-map of boolean flags for this object. No flags are defined for this
* type.
*/
Flags: number
}
export interface FeeSettingsPostAmendmentFields {
/** The transaction cost of the "reference transaction" in drops of XRP as hexadecimal. */
BaseFeeDrops: string
/** The base reserve for an account in the XRP Ledger, as drops of XRP. */
ReserveBaseDrops: string
/** The incremental owner reserve for owning objects, as drops of XRP. */
ReserveIncrementDrops: string
}
export interface FeeSettingsBase extends BaseLedgerEntry {
LedgerEntryType: 'FeeSettings'
/**
* A bit-map of boolean flags for this object. No flags are defined for this type.
*/
Flags: 0
}
/**
* The FeeSettings object type contains the current base transaction cost and
* reserve amounts as determined by fee voting.
*
* The fields will be based on the status of the `XRPFees` amendment.
* - Before: {@link FeeSettingsPreAmendmentFields}
* - After: {@link FeeSettingsPostAmendmentFields}
*
* @interface
*
* @category Ledger Entries
*/
type FeeSettings = FeeSettingsBase &
(FeeSettingsPreAmendmentFields | FeeSettingsPostAmendmentFields)
export default FeeSettings

View File

@@ -0,0 +1,16 @@
import { Amount } from '../common'
import BaseLedgerEntry from './BaseLedgerEntry'
export interface NFTokenOffer extends BaseLedgerEntry {
LedgerEntryType: 'NFTokenOffer'
Amount: Amount
Destination?: string
Expiration: number
Flags: number
NFTokenOfferNode?: string
Owner: string
OwnerNode?: string
PreviousTxnID: string
PreviousTxnLgrSeq: number
}

View File

@@ -0,0 +1,20 @@
import BaseLedgerEntry from './BaseLedgerEntry'
export interface NFToken {
NFToken: {
Flags: number
Issuer: string
NFTokenID: string
NFTokenTaxon: number
URI?: string
}
}
export interface NFTokenPage extends BaseLedgerEntry {
LedgerEntryType: 'NFTokenPage'
NextPageMin?: string
NFTokens: NFToken[]
PreviousPageMin?: string
PreviousTxnID?: string
PreviousTxnLgrSeq?: number
}

View File

@@ -1,9 +1,10 @@
import BaseLedgerEntry from './BaseLedgerEntry'
interface DisabledValidator {
FirstLedgerSequence: number
PublicKey: string
}
/**
* The unique id for the nUNL object https://xrpl.org/negativeunl.html#negativeunl-id-format
*/
export const NEGATIVE_UNL_ID =
'2E8A59AA9D3B5B186B0B9E0F62E6C02587CA74A4D778938E957B6357D364B244'
/**
* The NegativeUNL object type contains the current status of the Negative UNL,
@@ -16,7 +17,10 @@ export default interface NegativeUNL extends BaseLedgerEntry {
/**
* A list of trusted validators that are currently disabled.
*/
DisabledValidators?: DisabledValidator[]
DisabledValidators?: Array<{
FirstLedgerSequence: number
PublicKey: string
}>
/**
* The public key of a trusted validator that is scheduled to be disabled in
* the next flag ledger.

View File

@@ -1,11 +1,6 @@
import BaseLedgerEntry from './BaseLedgerEntry'
import { SignerEntry } from '../common'
interface SignerEntry {
SignerEntry: {
Account: string
SignerWeight: number
}
}
import BaseLedgerEntry from './BaseLedgerEntry'
/**
* The SignerList object type represents a list of parties that, as a group,

View File

@@ -2,16 +2,22 @@ import AccountRoot, {
AccountRootFlags,
AccountRootFlagsInterface,
} from './AccountRoot'
import Amendments from './Amendments'
import Amendments, { Majority, AMENDMENTS_ID } from './Amendments'
import Check from './Check'
import DepositPreauth from './DepositPreauth'
import DirectoryNode from './DirectoryNode'
import Escrow from './Escrow'
import FeeSettings from './FeeSettings'
import FeeSettings, {
FeeSettingsPreAmendmentFields,
FeeSettingsPostAmendmentFields,
FEE_SETTINGS_ID,
} from './FeeSettings'
import Ledger from './Ledger'
import LedgerEntry from './LedgerEntry'
import LedgerHashes from './LedgerHashes'
import NegativeUNL from './NegativeUNL'
import NegativeUNL, { NEGATIVE_UNL_ID } from './NegativeUNL'
import { NFTokenOffer } from './NFTokenOffer'
import { NFToken, NFTokenPage } from './NFTokenPage'
import Offer, { OfferFlags } from './Offer'
import PayChannel from './PayChannel'
import RippleState, { RippleStateFlags } from './RippleState'
@@ -22,16 +28,25 @@ export {
AccountRoot,
AccountRootFlags,
AccountRootFlagsInterface,
AMENDMENTS_ID,
Amendments,
Check,
DepositPreauth,
DirectoryNode,
Escrow,
FEE_SETTINGS_ID,
FeeSettings,
FeeSettingsPreAmendmentFields,
FeeSettingsPostAmendmentFields,
Ledger,
LedgerEntry,
LedgerHashes,
Majority,
NEGATIVE_UNL_ID,
NegativeUNL,
NFTokenOffer,
NFTokenPage,
NFToken,
Offer,
OfferFlags,
PayChannel,

View File

@@ -1,8 +1,6 @@
import { LedgerIndex } from '../common'
import { BaseRequest, BaseResponse, LookupByLedgerRequest } from './baseMethod'
import { BaseRequest, BaseResponse } from './baseMethod'
interface Channel {
export interface Channel {
account: string
amount: string
balance: string
@@ -26,7 +24,9 @@ interface Channel {
*
* @category Requests
*/
export interface AccountChannelsRequest extends BaseRequest {
export interface AccountChannelsRequest
extends BaseRequest,
LookupByLedgerRequest {
command: 'account_channels'
/**
* The unique identifier of an account, typically the account's address. The
@@ -40,13 +40,6 @@ export interface AccountChannelsRequest extends BaseRequest {
* account.
*/
destination_account?: string
/** 20-byte hex string for the ledger version to use. */
ledger_hash?: string
/**
* The ledger index of the ledger to use, or a shortcut string to choose a
* ledger automatically.
*/
ledger_index?: LedgerIndex
/**
* Limit the number of transactions to retrieve. Cannot be less than 10 or
* more than 400. The default is 200.

View File

@@ -1,6 +1,4 @@
import { LedgerIndex } from '../common'
import { BaseRequest, BaseResponse } from './baseMethod'
import { BaseRequest, BaseResponse, LookupByLedgerRequest } from './baseMethod'
/**
* The `account_currencies` command retrieves a list of currencies that an
@@ -9,17 +7,12 @@ import { BaseRequest, BaseResponse } from './baseMethod'
*
* @category Requests
*/
export interface AccountCurrenciesRequest extends BaseRequest {
export interface AccountCurrenciesRequest
extends BaseRequest,
LookupByLedgerRequest {
command: 'account_currencies'
/** A unique identifier for the account, most commonly the account's address. */
account: string
/** A 20-byte hex string for the ledger version to use. */
ledger_hash?: string
/**
* The ledger index of the ledger to use, or a shortcut string to choose a
* ledger automatically.
*/
ledger_index?: LedgerIndex
/**
* If true, then the account field only accepts a public key or XRP Ledger
* address. Otherwise, account can be a secret or passphrase (not

View File

@@ -1,7 +1,6 @@
import { LedgerIndex } from '../common'
import { AccountRoot, SignerList } from '../ledger'
import { BaseRequest, BaseResponse } from './baseMethod'
import { BaseRequest, BaseResponse, LookupByLedgerRequest } from './baseMethod'
/**
* The `account_info` command retrieves information about an account, its
@@ -10,17 +9,10 @@ import { BaseRequest, BaseResponse } from './baseMethod'
*
* @category Requests
*/
export interface AccountInfoRequest extends BaseRequest {
export interface AccountInfoRequest extends BaseRequest, LookupByLedgerRequest {
command: 'account_info'
/** A unique identifier for the account, most commonly the account's address. */
account: string
/** A 20-byte hex string for the ledger version to use. */
ledger_hash?: string
/**
* The ledger index of the ledger to use, or a shortcut string to choose a
* ledger automatically.
*/
ledger_index?: LedgerIndex
/**
* Whether to get info about this account's queued transactions. Can only be
* used when querying for the data from the current open ledger. Not available
@@ -39,7 +31,7 @@ export interface AccountInfoRequest extends BaseRequest {
strict?: boolean
}
interface QueueTransaction {
export interface AccountQueueTransaction {
/**
* Whether this transaction changes this address's ways of authorizing
* transactions.
@@ -58,7 +50,7 @@ interface QueueTransaction {
seq: number
}
interface QueueData {
export interface AccountQueueData {
/** Number of queued transactions from this address. */
txn_count: number
/**
@@ -78,7 +70,63 @@ interface QueueData {
*/
max_spend_drops_total?: string
/** Information about each queued transaction from this address. */
transactions?: QueueTransaction[]
transactions?: AccountQueueTransaction[]
}
export interface AccountInfoAccountFlags {
/**
* Enable rippling on this address's trust lines by default. Required for issuing addresses; discouraged for others.
*/
defaultRipple: boolean
/**
* This account can only receive funds from transactions it sends, and from preauthorized accounts.
* (It has DepositAuth enabled.)
*/
depositAuth: boolean
/**
* Disallows use of the master key to sign transactions for this account.
*/
disableMasterKey: boolean
/**
* Disallow incoming Checks from other accounts.
*/
disallowIncomingCheck?: boolean
/**
* Disallow incoming NFTOffers from other accounts. Part of the DisallowIncoming amendment.
*/
disallowIncomingNFTokenOffer?: boolean
/**
* Disallow incoming PayChannels from other accounts. Part of the DisallowIncoming amendment.
*/
disallowIncomingPayChan?: boolean
/**
* Disallow incoming Trustlines from other accounts. Part of the DisallowIncoming amendment.
*/
disallowIncomingTrustline?: boolean
/**
* Client applications should not send XRP to this account. Not enforced by rippled.
*/
disallowIncomingXRP: boolean
/**
* All assets issued by this address are frozen.
*/
globalFreeze: boolean
/**
* This address cannot freeze trust lines connected to it. Once enabled, cannot be disabled.
*/
noFreeze: boolean
/**
* The account has used its free SetRegularKey transaction.
*/
passwordSpent: boolean
/**
* This account must individually approve other users for those users to hold this account's issued currencies.
*/
requireAuthorization: boolean
/**
* Requires incoming payments to specify a Destination Tag.
*/
requireDestinationTag: boolean
}
/**
@@ -97,6 +145,11 @@ export interface AccountInfoResponse extends BaseResponse {
* present.
*/
account_data: AccountRoot & { signer_lists?: SignerList[] }
/**
* A map of account flags parsed out. This will only be available for rippled nodes 1.11.0 and higher.
*/
account_flags?: AccountInfoAccountFlags
/**
* The ledger index of the current in-progress ledger, which was used when
* retrieving this information.
@@ -115,7 +168,7 @@ export interface AccountInfoResponse extends BaseResponse {
* fields may be omitted because the values are calculated "lazily" by the
* queuing mechanism.
*/
queue_data?: QueueData
queue_data?: AccountQueueData
/**
* True if this data is from a validated ledger version; if omitted or set
* to false, this data is not final.

View File

@@ -1,8 +1,6 @@
import { LedgerIndex } from '../common'
import { BaseRequest, BaseResponse, LookupByLedgerRequest } from './baseMethod'
import { BaseRequest, BaseResponse } from './baseMethod'
export interface Trustline {
export interface AccountLinesTrustline {
/** The unique Address of the counterparty to this trust line. */
account: string
/**
@@ -74,17 +72,12 @@ export interface Trustline {
*
* @category Requests
*/
export interface AccountLinesRequest extends BaseRequest {
export interface AccountLinesRequest
extends BaseRequest,
LookupByLedgerRequest {
command: 'account_lines'
/** A unique identifier for the account, most commonly the account's Address. */
account: string
/** A 20-byte hex string for the ledger version to use. */
ledger_hash?: string
/**
* The ledger index of the ledger to use, or a shortcut string to choose a
* ledger automatically.
*/
ledger_index?: LedgerIndex
/**
* The Address of a second account. If provided, show only lines of trust
* connecting the two accounts.
@@ -118,7 +111,7 @@ export interface AccountLinesResponse extends BaseResponse {
* Array of trust line objects. If the number of trust lines is large, only
* returns up to the limit at a time.
*/
lines: Trustline[]
lines: AccountLinesTrustline[]
/**
* The ledger index of the current open ledger, which was used when
* retrieving this information.

View File

@@ -1,4 +1,4 @@
import { BaseRequest, BaseResponse } from './baseMethod'
import { BaseRequest, BaseResponse, LookupByLedgerRequest } from './baseMethod'
/**
* The `account_nfts` method retrieves all of the NFTs currently owned by the
@@ -6,7 +6,7 @@ import { BaseRequest, BaseResponse } from './baseMethod'
*
* @category Requests
*/
export interface AccountNFTsRequest extends BaseRequest {
export interface AccountNFTsRequest extends BaseRequest, LookupByLedgerRequest {
command: 'account_nfts'
/**
* The unique identifier of an account, typically the account's address. The

View File

@@ -1,4 +1,3 @@
import { LedgerIndex } from '../common'
import {
Check,
DepositPreauth,
@@ -10,9 +9,9 @@ import {
Ticket,
} from '../ledger'
import { BaseRequest, BaseResponse } from './baseMethod'
import { BaseRequest, BaseResponse, LookupByLedgerRequest } from './baseMethod'
type AccountObjectType =
export type AccountObjectType =
| 'check'
| 'deposit_preauth'
| 'escrow'
@@ -31,7 +30,9 @@ type AccountObjectType =
*
* @category Requests
*/
export interface AccountObjectsRequest extends BaseRequest {
export interface AccountObjectsRequest
extends BaseRequest,
LookupByLedgerRequest {
command: 'account_objects'
/** A unique identifier for the account, most commonly the account's address. */
account: string
@@ -46,13 +47,6 @@ export interface AccountObjectsRequest extends BaseRequest {
* from being deleted. The default is false.
*/
deletion_blockers_only?: boolean
/** A 20-byte hex string for the ledger version to use. */
ledger_hash?: string
/**
* The ledger index of the ledger to use, or a shortcut string to choose a
* Ledger automatically.
*/
ledger_index?: LedgerIndex
/**
* The maximum number of objects to include in the results. Must be within
* the inclusive range 10 to 400 on non-admin connections. The default is 200.
@@ -69,7 +63,7 @@ export interface AccountObjectsRequest extends BaseRequest {
* Account Objects can be a Check, a DepositPreauth, an Escrow, an Offer, a
* PayChannel, a SignerList, a Ticket, or a RippleState.
*/
type AccountObject =
export type AccountObject =
| Check
| DepositPreauth
| Escrow

View File

@@ -1,6 +1,6 @@
import { Amount, LedgerIndex } from '../common'
import { Amount } from '../common'
import { BaseRequest, BaseResponse } from './baseMethod'
import { BaseRequest, BaseResponse, LookupByLedgerRequest } from './baseMethod'
/**
* The account_offers method retrieves a list of offers made by a given account
@@ -9,17 +9,12 @@ import { BaseRequest, BaseResponse } from './baseMethod'
*
* @category Requests
*/
export interface AccountOffersRequest extends BaseRequest {
export interface AccountOffersRequest
extends BaseRequest,
LookupByLedgerRequest {
command: 'account_offers'
/** A unique identifier for the account, most commonly the account's Address. */
account: string
/** A 20-byte hex string identifying the ledger version to use. */
ledger_hash?: string
/**
* The ledger index of the ledger to use, or "current", "closed", or
* "validated" to select a ledger dynamically.
*/
ledger_index?: LedgerIndex
/**
* Limit the number of transactions to retrieve. The server is not required
* to honor this value. Must be within the inclusive range 10 to 400.

View File

@@ -1,7 +1,7 @@
import { LedgerIndex, ResponseOnlyTxInfo } from '../common'
import { ResponseOnlyTxInfo } from '../common'
import { Transaction, TransactionMetadata } from '../transactions'
import { BaseRequest, BaseResponse } from './baseMethod'
import { BaseRequest, BaseResponse, LookupByLedgerRequest } from './baseMethod'
/**
* The account_tx method retrieves a list of transactions that involved the
@@ -10,7 +10,7 @@ import { BaseRequest, BaseResponse } from './baseMethod'
*
* @category Requests
*/
export interface AccountTxRequest extends BaseRequest {
export interface AccountTxRequest extends BaseRequest, LookupByLedgerRequest {
command: 'account_tx'
/** A unique identifier for the account, most commonly the account's address. */
account: string
@@ -26,10 +26,6 @@ export interface AccountTxRequest extends BaseRequest {
* version available.
*/
ledger_index_max?: number
/** Use to look for transactions from a single ledger only. */
ledger_hash?: string
/** Use to look for transactions from a single ledger only. */
ledger_index?: LedgerIndex
/**
* If true, return transactions as hex strings instead of JSON. The default is
* false.
@@ -53,7 +49,7 @@ export interface AccountTxRequest extends BaseRequest {
marker?: unknown
}
interface AccountTransaction {
export interface AccountTxTransaction {
/** The ledger index of the ledger version that included this transaction. */
ledger_index: number
/**
@@ -102,7 +98,7 @@ export interface AccountTxResponse extends BaseResponse {
* Array of transactions matching the request's criteria, as explained
* below.
*/
transactions: AccountTransaction[]
transactions: AccountTxTransaction[]
/**
* If included and set to true, the information in this response comes from
* a validated ledger version. Otherwise, the information is subject to

View File

@@ -1,3 +1,5 @@
import { LedgerIndex } from '../common'
import type { Request } from '.'
export interface BaseRequest {
@@ -14,7 +16,14 @@ export interface BaseRequest {
api_version?: number
}
interface Warning {
export interface LookupByLedgerRequest {
/** A 20-byte hex string for the ledger version to use. */
ledger_hash?: string
/** The ledger index of the ledger to use, or a shortcut string. */
ledger_index?: LedgerIndex
}
export interface ResponseWarning {
id: number
message: string
details?: { [key: string]: string }
@@ -26,7 +35,7 @@ export interface BaseResponse {
type: 'response' | string
result: unknown
warning?: 'load'
warnings?: Warning[]
warnings?: ResponseWarning[]
forwarded?: boolean
api_version?: number
}

View File

@@ -1,9 +1,9 @@
import { Amount, LedgerIndex } from '../common'
import { Amount } from '../common'
import { Offer } from '../ledger'
import { BaseRequest, BaseResponse } from './baseMethod'
import { BaseRequest, BaseResponse, LookupByLedgerRequest } from './baseMethod'
export interface TakerAmount {
export interface BookOfferCurrency {
currency: string
issuer?: string
}
@@ -14,15 +14,8 @@ export interface TakerAmount {
*
* @category Requests
*/
export interface BookOffersRequest extends BaseRequest {
export interface BookOffersRequest extends BaseRequest, LookupByLedgerRequest {
command: 'book_offers'
/** A 20-byte hex string for the ledger version to use. */
ledger_hash?: string
/**
* The ledger index of the ledger to use, or a shortcut string to choose a
* ledger automatically.
*/
ledger_index?: LedgerIndex
/**
* If provided, the server does not provide more than this many offers in the
* results. The total number of results returned may be fewer than the limit,
@@ -39,13 +32,13 @@ export interface BookOffersRequest extends BaseRequest {
* receive, as an object with currency and issuer fields (omit issuer for
* XRP), like currency amounts.
*/
taker_gets: TakerAmount
taker_gets: BookOfferCurrency
/**
* Specification of which currency the account taking the offer would pay, as
* an object with currency and issuer fields (omit issuer for XRP), like
* currency amounts.
*/
taker_pays: TakerAmount
taker_pays: BookOfferCurrency
}
export interface BookOffer extends Offer {

View File

@@ -1,6 +1,4 @@
import { LedgerIndex } from '../common'
import { BaseRequest, BaseResponse } from './baseMethod'
import { BaseRequest, BaseResponse, LookupByLedgerRequest } from './baseMethod'
/**
* The deposit_authorized command indicates whether one account is authorized to
@@ -9,19 +7,14 @@ import { BaseRequest, BaseResponse } from './baseMethod'
*
* @category Requests
*/
export interface DepositAuthorizedRequest extends BaseRequest {
export interface DepositAuthorizedRequest
extends BaseRequest,
LookupByLedgerRequest {
command: 'deposit_authorized'
/** The sender of a possible payment. */
source_account: string
/** The recipient of a possible payment. */
destination_account: string
/** A 20-byte hex string for the ledger version to use. */
ledger_hash?: string
/**
* The ledger index of the ledger to use, or a shortcut string to choose a
* ledger automatically.
*/
ledger_index?: LedgerIndex
}
/**

View File

@@ -1,6 +1,4 @@
import { LedgerIndex } from '../common'
import { BaseRequest, BaseResponse } from './baseMethod'
import { BaseRequest, BaseResponse, LookupByLedgerRequest } from './baseMethod'
/**
* The gateway_balances command calculates the total balances issued by a given
@@ -21,7 +19,9 @@ import { BaseRequest, BaseResponse } from './baseMethod'
*
* @category Requests
*/
export interface GatewayBalancesRequest extends BaseRequest {
export interface GatewayBalancesRequest
extends BaseRequest,
LookupByLedgerRequest {
command: 'gateway_balances'
/** The Address to check. This should be the issuing address. */
account: string
@@ -35,16 +35,9 @@ export interface GatewayBalancesRequest extends BaseRequest {
* Such addresses.
*/
hotwallet?: string | string[]
/** A 20-byte hex string for the ledger version to use. */
ledger_hash?: string
/**
* The ledger index of the ledger version to use, or a shortcut string to
* choose a ledger automatically.
*/
ledger_index?: LedgerIndex
}
interface Balance {
export interface GatewayBalance {
currency: string
value: string
}
@@ -67,12 +60,12 @@ export interface GatewayBalancesResponse extends BaseResponse {
* Amounts issued to the hotwallet addresses from the request. The keys are
* addresses and the values are arrays of currency amounts they hold.
*/
balances?: { [address: string]: Balance[] }
balances?: { [address: string]: GatewayBalance[] }
/**
* Total amounts held that are issued by others. In the recommended
* configuration, the issuing address should have none.
*/
assets?: { [address: string]: Balance[] }
assets?: { [address: string]: GatewayBalance[] }
/**
* The identifying hash of the ledger version that was used to generate
* this response.

View File

@@ -1,23 +1,58 @@
/* eslint-disable max-lines -- There is a lot to export */
import {
AccountChannelsRequest,
AccountChannelsResponse,
Channel,
} from './accountChannels'
import {
AccountCurrenciesRequest,
AccountCurrenciesResponse,
} from './accountCurrencies'
import { AccountInfoRequest, AccountInfoResponse } from './accountInfo'
import { AccountLinesRequest, AccountLinesResponse } from './accountLines'
import { AccountNFTsRequest, AccountNFTsResponse } from './accountNFTs'
import { AccountObjectsRequest, AccountObjectsResponse } from './accountObjects'
import {
AccountInfoAccountFlags,
AccountInfoRequest,
AccountInfoResponse,
AccountQueueData,
AccountQueueTransaction,
} from './accountInfo'
import {
AccountLinesRequest,
AccountLinesResponse,
AccountLinesTrustline,
} from './accountLines'
import {
AccountNFToken,
AccountNFTsRequest,
AccountNFTsResponse,
} from './accountNFTs'
import {
AccountObject,
AccountObjectsRequest,
AccountObjectsResponse,
AccountObjectType,
} from './accountObjects'
import {
AccountOffer,
AccountOffersRequest,
AccountOffersResponse,
} from './accountOffers'
import { AccountTxRequest, AccountTxResponse } from './accountTx'
import { ErrorResponse } from './baseMethod'
import { BookOffersRequest, BookOffer, BookOffersResponse } from './bookOffers'
import {
AccountTxRequest,
AccountTxResponse,
AccountTxTransaction,
} from './accountTx'
import {
BaseRequest,
BaseResponse,
ErrorResponse,
ResponseWarning,
} from './baseMethod'
import {
BookOffersRequest,
BookOffer,
BookOffersResponse,
BookOfferCurrency,
} from './bookOffers'
import { ChannelVerifyRequest, ChannelVerifyResponse } from './channelVerify'
import {
DepositAuthorizedRequest,
@@ -25,17 +60,34 @@ import {
} from './depositAuthorized'
import { FeeRequest, FeeResponse } from './fee'
import {
GatewayBalance,
GatewayBalancesRequest,
GatewayBalancesResponse,
} from './gatewayBalances'
import { LedgerRequest, LedgerResponse } from './ledger'
import {
LedgerBinary,
LedgerModifiedOfferCreateTransaction,
LedgerQueueData,
LedgerRequest,
LedgerResponse,
} from './ledger'
import { LedgerClosedRequest, LedgerClosedResponse } from './ledgerClosed'
import { LedgerCurrentRequest, LedgerCurrentResponse } from './ledgerCurrent'
import { LedgerDataRequest, LedgerDataResponse } from './ledgerData'
import {
LedgerDataBinaryLedgerEntry,
LedgerDataLabeledLedgerEntry,
LedgerDataLedgerState,
LedgerDataRequest,
LedgerDataResponse,
} from './ledgerData'
import { LedgerEntryRequest, LedgerEntryResponse } from './ledgerEntry'
import { ManifestRequest, ManifestResponse } from './manifest'
import { NFTBuyOffersRequest, NFTBuyOffersResponse } from './nftBuyOffers'
import { NFTHistoryRequest, NFTHistoryResponse } from './nftHistory'
import {
NFTHistoryRequest,
NFTHistoryResponse,
NFTHistoryTransaction,
} from './nftHistory'
import { NFTInfoRequest, NFTInfoResponse } from './nftInfo'
import { NFTSellOffersRequest, NFTSellOffersResponse } from './nftSellOffers'
import { NoRippleCheckRequest, NoRippleCheckResponse } from './norippleCheck'
@@ -45,11 +97,24 @@ import {
PathFindCreateRequest,
PathFindStatusRequest,
PathFindResponse,
PathFindPathOption,
} from './pathFind'
import { PingRequest, PingResponse } from './ping'
import { RandomRequest, RandomResponse } from './random'
import { RipplePathFindRequest, RipplePathFindResponse } from './ripplePathFind'
import { ServerInfoRequest, ServerInfoResponse } from './serverInfo'
import {
RipplePathFindPathOption,
RipplePathFindRequest,
RipplePathFindResponse,
SourceCurrencyAmount,
} from './ripplePathFind'
import {
JobType,
ServerInfoRequest,
ServerInfoResponse,
ServerState,
StateAccounting,
StateAccountingFinal,
} from './serverInfo'
import { ServerStateRequest, ServerStateResponse } from './serverState'
import { SubmitRequest, SubmitResponse } from './submit'
import {
@@ -57,12 +122,15 @@ import {
SubmitMultisignedResponse,
} from './submitMultisigned'
import {
BooksSnapshot,
ConsensusStream,
LedgerStream,
LedgerStreamResponse,
OrderBookStream,
PathFindStream,
PeerStatusStream,
Stream,
SubscribeBook,
SubscribeRequest,
SubscribeResponse,
TransactionStream,
@@ -73,7 +141,11 @@ import {
TransactionEntryResponse,
} from './transactionEntry'
import { TxRequest, TxResponse } from './tx'
import { UnsubscribeRequest, UnsubscribeResponse } from './unsubscribe'
import {
UnsubscribeBook,
UnsubscribeRequest,
UnsubscribeResponse,
} from './unsubscribe'
/**
* @category Requests
*/
@@ -177,19 +249,31 @@ type Response =
| NFTHistoryResponse
export {
// Allow users to define their own requests and responses. This is useful for releasing experimental versions
BaseRequest,
BaseResponse,
Request,
Response,
// account methods
ResponseWarning,
// account methods with types
Channel,
AccountChannelsRequest,
AccountChannelsResponse,
AccountCurrenciesRequest,
AccountCurrenciesResponse,
AccountInfoAccountFlags,
AccountInfoRequest,
AccountInfoResponse,
AccountQueueData,
AccountQueueTransaction,
AccountLinesRequest,
AccountLinesResponse,
AccountLinesTrustline,
AccountNFToken,
AccountNFTsRequest,
AccountNFTsResponse,
AccountObject,
AccountObjectType,
AccountObjectsRequest,
AccountObjectsResponse,
AccountOffer,
@@ -197,6 +281,8 @@ export {
AccountOffersResponse,
AccountTxRequest,
AccountTxResponse,
AccountTxTransaction,
GatewayBalance,
GatewayBalancesRequest,
GatewayBalancesResponse,
NoRippleCheckRequest,
@@ -204,15 +290,21 @@ export {
// ledger methods
LedgerRequest,
LedgerResponse,
LedgerQueueData,
LedgerBinary,
LedgerModifiedOfferCreateTransaction,
LedgerClosedRequest,
LedgerClosedResponse,
LedgerCurrentRequest,
LedgerCurrentResponse,
LedgerDataRequest,
LedgerDataLabeledLedgerEntry,
LedgerDataBinaryLedgerEntry,
LedgerDataResponse,
LedgerDataLedgerState,
LedgerEntryRequest,
LedgerEntryResponse,
// transaction methods
// transaction methods with types
SubmitRequest,
SubmitResponse,
SubmitMultisignedRequest,
@@ -221,27 +313,34 @@ export {
TransactionEntryResponse,
TxRequest,
TxResponse,
// path and order book methods
// path and order book methods with types
BookOffersRequest,
BookOffer,
BookOfferCurrency,
BookOffersResponse,
DepositAuthorizedRequest,
DepositAuthorizedResponse,
PathFindRequest,
PathFindCreateRequest,
PathFindCloseRequest,
PathFindPathOption,
PathFindStatusRequest,
PathFindResponse,
RipplePathFindPathOption,
RipplePathFindRequest,
RipplePathFindResponse,
SourceCurrencyAmount,
// payment channel methods
ChannelVerifyRequest,
ChannelVerifyResponse,
// Subscribe methods/streams
// Subscribe methods/streams with types
SubscribeRequest,
SubscribeResponse,
SubscribeBook,
Stream,
BooksSnapshot,
LedgerStream,
LedgerStreamResponse,
ValidationStream,
TransactionStream,
PathFindStream,
@@ -250,7 +349,8 @@ export {
ConsensusStream,
UnsubscribeRequest,
UnsubscribeResponse,
// server info methods
UnsubscribeBook,
// server info methods with types
FeeRequest,
FeeResponse,
ManifestRequest,
@@ -259,6 +359,10 @@ export {
ServerInfoResponse,
ServerStateRequest,
ServerStateResponse,
JobType,
ServerState,
StateAccountingFinal,
StateAccounting,
// utility methods
PingRequest,
PingResponse,
@@ -275,4 +379,5 @@ export {
NFTInfoResponse,
NFTHistoryRequest,
NFTHistoryResponse,
NFTHistoryTransaction,
}

View File

@@ -1,9 +1,8 @@
import { LedgerIndex } from '../common'
import { Ledger } from '../ledger'
import { Transaction, TransactionAndMetadata } from '../transactions'
import { TransactionMetadata } from '../transactions/metadata'
import { BaseRequest, BaseResponse } from './baseMethod'
import { BaseRequest, BaseResponse, LookupByLedgerRequest } from './baseMethod'
/**
* Retrieve information about the public ledger. Expects a response in the form
@@ -25,15 +24,8 @@ import { BaseRequest, BaseResponse } from './baseMethod'
*
* @category Requests
*/
export interface LedgerRequest extends BaseRequest {
export interface LedgerRequest extends BaseRequest, LookupByLedgerRequest {
command: 'ledger'
/** A 20-byte hex string for the ledger version to use. */
ledger_hash?: string
/**
* The ledger index of the ledger to use, or a shortcut string to choose a
* ledger automatically.
*/
ledger_index?: LedgerIndex
/**
* Admin required If true, return full information on the entire ledger.
* Ignored if you did not specify a ledger version. Defaults to false.
@@ -75,20 +67,19 @@ export interface LedgerRequest extends BaseRequest {
queue?: boolean
}
interface ModifiedMetadata extends TransactionMetadata {
owner_funds: string
}
interface ModifiedOfferCreateTransaction {
/**
* Special case transaction definition when the request contains `owner_funds: true`.
*/
export interface LedgerModifiedOfferCreateTransaction {
transaction: Transaction
metadata: ModifiedMetadata
metadata: TransactionMetadata & { owner_funds: string }
}
interface LedgerQueueData {
export interface LedgerQueueData {
account: string
tx:
| TransactionAndMetadata
| ModifiedOfferCreateTransaction
| LedgerModifiedOfferCreateTransaction
| { tx_blob: string }
retries_remaining: number
preflight_result: string
@@ -99,7 +90,7 @@ interface LedgerQueueData {
max_spend_drops?: string
}
interface BinaryLedger
export interface LedgerBinary
extends Omit<Omit<Ledger, 'transactions'>, 'accountState'> {
accountState?: string[]
transactions?: string[]
@@ -113,7 +104,7 @@ interface BinaryLedger
export interface LedgerResponse extends BaseResponse {
result: {
/** The complete header data of this {@link Ledger}. */
ledger: Ledger | BinaryLedger
ledger: Ledger | LedgerBinary
/** Unique identifying hash of the entire ledger. */
ledger_hash: string
/** The Ledger Index of this ledger. */

View File

@@ -1,7 +1,6 @@
import { LedgerIndex } from '../common'
import { LedgerEntry } from '../ledger'
import { BaseRequest, BaseResponse } from './baseMethod'
import { BaseRequest, BaseResponse, LookupByLedgerRequest } from './baseMethod'
/**
* The `ledger_data` method retrieves contents of the specified ledger. You can
@@ -21,15 +20,8 @@ import { BaseRequest, BaseResponse } from './baseMethod'
*
* @category Requests
*/
export interface LedgerDataRequest extends BaseRequest {
export interface LedgerDataRequest extends BaseRequest, LookupByLedgerRequest {
command: 'ledger_data'
/** A 20-byte hex string for the ledger version to use. */
ledger_hash?: string
/**
* The ledger index of the ledger to use, or a shortcut string to choose a
* ledger automatically.
*/
ledger_index?: LedgerIndex
/**
* If set to true, return ledger objects as hashed hex strings instead of
* JSON.
@@ -47,13 +39,18 @@ export interface LedgerDataRequest extends BaseRequest {
marker?: unknown
}
type LabeledLedgerEntry = { ledgerEntryType: string } & LedgerEntry
export type LedgerDataLabeledLedgerEntry = {
ledgerEntryType: string
} & LedgerEntry
export interface BinaryLedgerEntry {
export interface LedgerDataBinaryLedgerEntry {
data: string
}
type State = { index: string } & (BinaryLedgerEntry | LabeledLedgerEntry)
export type LedgerDataLedgerState = { index: string } & (
| LedgerDataBinaryLedgerEntry
| LedgerDataLabeledLedgerEntry
)
/**
* The response expected from a {@link LedgerDataRequest}.
@@ -70,7 +67,7 @@ export interface LedgerDataResponse extends BaseResponse {
* Array of JSON objects containing data from the ledger's state tree,
* as defined below.
*/
state: State[]
state: LedgerDataLedgerState[]
/**
* Server-defined value indicating the response is paginated. Pass this to
* the next call to resume where this call left off.

View File

@@ -1,7 +1,6 @@
import { LedgerIndex } from '../common'
import { LedgerEntry } from '../ledger'
import { BaseRequest, BaseResponse } from './baseMethod'
import { BaseRequest, BaseResponse, LookupByLedgerRequest } from './baseMethod'
/**
* The `ledger_entry` method returns a single ledger object from the XRP Ledger
@@ -19,7 +18,7 @@ import { BaseRequest, BaseResponse } from './baseMethod'
*
* @category Requests
*/
export interface LedgerEntryRequest extends BaseRequest {
export interface LedgerEntryRequest extends BaseRequest, LookupByLedgerRequest {
command: 'ledger_entry'
/**
* If true, return the requested ledger object's contents as a hex string in
@@ -27,10 +26,6 @@ export interface LedgerEntryRequest extends BaseRequest {
* default is false.
*/
binary?: boolean
/** A 20-byte hex string for the ledger version to use. */
ledger_hash?: string
/** The ledger index of the ledger to use, or a shortcut string. */
ledger_index?: LedgerIndex
/*
* Only one of the following properties should be defined in a single request
@@ -137,6 +132,11 @@ export interface LedgerEntryRequest extends BaseRequest {
ticket_sequence: number
}
| string
/**
* Must be the object ID of the NFToken page, as hexadecimal
*/
nft_page?: string
}
/**

View File

@@ -1,6 +1,6 @@
import { NFTOffer } from '../common'
import { BaseRequest, BaseResponse } from './baseMethod'
import { BaseRequest, BaseResponse, LookupByLedgerRequest } from './baseMethod'
/**
* The `nft_buy_offers` method retrieves all of buy offers for the specified
@@ -8,7 +8,9 @@ import { BaseRequest, BaseResponse } from './baseMethod'
*
* @category Requests
*/
export interface NFTBuyOffersRequest extends BaseRequest {
export interface NFTBuyOffersRequest
extends BaseRequest,
LookupByLedgerRequest {
command: 'nft_buy_offers'
/**
* The unique identifier of an NFToken. The request returns buy offers for this NFToken.

View File

@@ -1,7 +1,7 @@
import { LedgerIndex, ResponseOnlyTxInfo } from '../common'
import { ResponseOnlyTxInfo } from '../common'
import { Transaction, TransactionMetadata } from '../transactions'
import { BaseRequest, BaseResponse } from './baseMethod'
import { BaseRequest, BaseResponse, LookupByLedgerRequest } from './baseMethod'
/**
* The nft_history method retrieves a list of transactions that involved the
@@ -10,7 +10,7 @@ import { BaseRequest, BaseResponse } from './baseMethod'
*
* @category Requests
*/
export interface NFTHistoryRequest extends BaseRequest {
export interface NFTHistoryRequest extends BaseRequest, LookupByLedgerRequest {
command: 'nft_history'
/**
* The unique identifier of an NFToken.
@@ -28,10 +28,6 @@ export interface NFTHistoryRequest extends BaseRequest {
* version available.
*/
ledger_index_max?: number
/** Use to look for transactions from a single ledger only. */
ledger_hash?: string
/** Use to look for transactions from a single ledger only. */
ledger_index?: LedgerIndex
/**
* If true, return transactions as hex strings instead of JSON. The default is
* false.
@@ -55,7 +51,7 @@ export interface NFTHistoryRequest extends BaseRequest {
marker?: unknown
}
interface NFTokenTransaction {
export interface NFTHistoryTransaction {
/** The ledger index of the ledger version that included this transaction. */
ledger_index: number
/**
@@ -106,7 +102,7 @@ export interface NFTHistoryResponse extends BaseResponse {
* Array of transactions matching the request's criteria, as explained
* below.
*/
transactions: NFTokenTransaction[]
transactions: NFTHistoryTransaction[]
/**
* If included and set to true, the information in this response comes from
* a validated ledger version. Otherwise, the information is subject to

View File

@@ -1,26 +1,18 @@
import { LedgerIndex, NFToken } from '../common'
import { NFToken } from '../common'
import { BaseRequest, BaseResponse } from './baseMethod'
import { BaseRequest, BaseResponse, LookupByLedgerRequest } from './baseMethod'
/**
* The `nft_info` method retrieves information about NFToken
* NFToken.
* The `nft_info` method retrieves information about an NFToken.
*
* @category Requests
*/
export interface NFTInfoRequest extends BaseRequest {
export interface NFTInfoRequest extends BaseRequest, LookupByLedgerRequest {
command: 'nft_info'
/**
* The unique identifier of an NFToken.
*/
nft_id: string
/** A 20-byte hex string for the ledger version to use. */
ledger_hash?: string
/**
* The ledger index of the ledger to use, or a shortcut string to choose a
* ledger automatically.
*/
ledger_index?: LedgerIndex
}
/**

View File

@@ -1,6 +1,6 @@
import { NFTOffer } from '../common'
import { BaseRequest, BaseResponse } from './baseMethod'
import { BaseRequest, BaseResponse, LookupByLedgerRequest } from './baseMethod'
/**
* The `nft_sell_offers` method retrieves all of sell offers for the specified
@@ -8,7 +8,9 @@ import { BaseRequest, BaseResponse } from './baseMethod'
*
* @category Requests
*/
export interface NFTSellOffersRequest extends BaseRequest {
export interface NFTSellOffersRequest
extends BaseRequest,
LookupByLedgerRequest {
command: 'nft_sell_offers'
/**
* The unique identifier of an NFToken. The request returns sell offers for this NFToken.

View File

@@ -55,7 +55,7 @@ export type PathFindRequest =
| PathFindCloseRequest
| PathFindStatusRequest
interface PathOption {
export interface PathFindPathOption {
/** Array of arrays of objects defining payment paths. */
paths_computed: Path[]
/**
@@ -82,7 +82,7 @@ export interface PathFindResponse extends BaseResponse {
* empty, then no paths were found connecting the source and destination
* accounts.
*/
alternatives: PathOption[]
alternatives: PathFindPathOption[]
/** Unique address of the account that would receive a transaction. */
destination_account: string
/** Currency amount provided in the WebSocket request. */

View File

@@ -1,8 +1,8 @@
import { Amount, LedgerIndex, Path } from '../common'
import { Amount, Path } from '../common'
import { BaseRequest, BaseResponse } from './baseMethod'
import { BaseRequest, BaseResponse, LookupByLedgerRequest } from './baseMethod'
interface SourceCurrencyAmount {
export interface SourceCurrencyAmount {
currency: string
issuer?: string
}
@@ -14,7 +14,9 @@ interface SourceCurrencyAmount {
*
* @category Requests
*/
export interface RipplePathFindRequest extends BaseRequest {
export interface RipplePathFindRequest
extends BaseRequest,
LookupByLedgerRequest {
command: 'ripple_path_find'
/** Unique address of the account that would send funds in a transaction. */
source_account: string
@@ -35,17 +37,10 @@ export interface RipplePathFindRequest extends BaseRequest {
* entry in the array should be a JSON object with a mandatory currency field
* and optional issuer field, like how currency amounts are specified.
*/
source_currencies?: SourceCurrencyAmount
/** A 20-byte hex string for the ledger version to use. */
ledger_hash?: string
/**
* The ledger index of the ledger to use, or a shortcut string to choose a
* ledger automatically.
*/
ledger_index?: LedgerIndex
source_currencies?: SourceCurrencyAmount[]
}
interface PathOption {
export interface RipplePathFindPathOption {
/** Array of arrays of objects defining payment paths. */
paths_computed: Path[]
/**
@@ -67,7 +62,7 @@ export interface RipplePathFindResponse extends BaseResponse {
* empty, then there are no paths connecting the source and destination
* accounts.
*/
alternatives: PathOption[]
alternatives: RipplePathFindPathOption[]
/** Unique address of the account that would receive a payment transaction. */
destination_account: string
/**

View File

@@ -136,6 +136,10 @@ export interface ServerInfoResponse extends BaseResponse {
* overall network's load factor.
*/
load_factor?: number
/**
* The network id of the server.
*/
network_id?: number
/**
* Current multiplier to the transaction cost based on
* load to this server.

View File

@@ -14,7 +14,7 @@ export interface SubmitMultisignedRequest extends BaseRequest {
/**
* Transaction in JSON format with an array of Signers. To be successful, the
* weights of the signatures must be equal or higher than the quorum of the.
* {@link SignerList}.
* {@link Transaction Type/SignerList}.
*/
tx_json: Transaction
/**

View File

@@ -11,7 +11,7 @@ import { TransactionMetadata } from '../transactions/metadata'
import type { BaseRequest, BaseResponse } from './baseMethod'
interface Book {
export interface SubscribeBook {
/**
* Specification of which currency the account taking the Offer would
* receive, as a currency object with no amount.
@@ -60,7 +60,7 @@ export interface SubscribeRequest extends BaseRequest {
* Array of objects defining order books to monitor for updates, as detailed
* Below.
*/
books?: Book[]
books?: SubscribeBook[]
/**
* URL where the server sends a JSON-RPC callbacks for each event.
* Admin-only.
@@ -72,7 +72,7 @@ export interface SubscribeRequest extends BaseRequest {
url_password?: string
}
type BooksSnapshot = Offer[]
export type BooksSnapshot = Offer[]
/**
* Response expected from a {@link SubscribeRequest}.
@@ -102,8 +102,8 @@ export interface LedgerStream extends BaseStream {
* Transaction cost applies starting with the following ledger version.
*/
fee_base: number
/** The reference transaction cost in "fee units". */
fee_ref: number
/** The reference transaction cost in "fee units". This is not returned after the SetFees amendment is enabled. */
fee_ref?: number
/** The identifying hash of the ledger version that was closed. */
ledger_hash: string
/** The ledger index of the ledger that was closed. */
@@ -143,8 +143,8 @@ export interface LedgerStreamResponse {
* Transaction cost applies starting with the following ledger version.
*/
fee_base: number
/** The reference transaction cost in "fee units". */
fee_ref: number
/** The reference transaction cost in "fee units". This is not returned after the SetFees amendment is enabled. */
fee_ref?: number
/** The identifying hash of the ledger version that was closed. */
ledger_hash: string
/** The ledger index of the ledger that was closed. */

View File

@@ -1,7 +1,7 @@
import { LedgerIndex, ResponseOnlyTxInfo } from '../common'
import { ResponseOnlyTxInfo } from '../common'
import { Transaction, TransactionMetadata } from '../transactions'
import { BaseRequest, BaseResponse } from './baseMethod'
import { BaseRequest, BaseResponse, LookupByLedgerRequest } from './baseMethod'
/**
* The `transaction_entry` method retrieves information on a single transaction
@@ -10,15 +10,11 @@ import { BaseRequest, BaseResponse } from './baseMethod'
*
* @category Requests
*/
export interface TransactionEntryRequest extends BaseRequest {
export interface TransactionEntryRequest
extends BaseRequest,
LookupByLedgerRequest {
command: 'transaction_entry'
/** A 20-byte hex string for the ledger version to use. */
ledger_hash?: string
/**
* The ledger index of the ledger to use, or a shortcut string to choose a
* ledger automatically.
*/
ledger_index?: LedgerIndex
/** Unique hash of the transaction you are looking up. */
tx_hash: string
}

View File

@@ -46,7 +46,8 @@ export interface TxResponse<T extends BaseTransaction = Transaction>
hash: string
/** The ledger index of the ledger that includes this transaction. */
ledger_index?: number
/** Transaction metadata, which describes the results of the transaction. */
/** Transaction metadata, which describes the results of the transaction.
* Can be undefined if a transaction has not been validated yet. */
meta?: TransactionMetadata | string
/**
* If true, this data comes from a validated ledger version; if omitted or.

View File

@@ -2,7 +2,7 @@ import { Currency, StreamType } from '../common'
import type { BaseRequest, BaseResponse } from './baseMethod'
interface Book {
export interface UnsubscribeBook {
taker_gets: Currency
taker_pays: Currency
both?: boolean
@@ -36,7 +36,7 @@ export interface UnsubscribeRequest extends BaseRequest {
* Array of objects defining order books to unsubscribe from, as explained
* below.
*/
books?: Book[]
books?: UnsubscribeBook[]
}
/**

View File

@@ -0,0 +1,20 @@
/**
* Mark a change to the Negative UNL.
*
* @category Pseudo Transaction Models
*/
export interface UNLModify {
TransactionType: 'UNLModify'
/**
* The ledger index where this pseudo-transaction appears.
* This distinguishes the pseudo-transaction from other occurrences of the same change.
*/
LedgerSequence: number
/**
* If 0, this change represents removing a validator from the Negative UNL.
* If 1, this change represents adding a validator to the Negative UNL.
*/
UNLModifyDisabling: 0 | 1
/** The validator to add or remove, as identified by its master public key. */
UNLModifyValidator: string
}

View File

@@ -1,6 +1,6 @@
/* eslint-disable complexity -- Necessary for validateAccountSet */
import { isValidClassicAddress } from 'ripple-address-codec'
import { isValidClassicAddress } from '@transia/ripple-address-codec'
import { ValidationError } from '../../errors'

View File

@@ -1,7 +1,7 @@
/* eslint-disable max-lines-per-function -- Necessary for validateBaseTransaction */
/* eslint-disable complexity -- Necessary for validateBaseTransaction */
/* eslint-disable max-statements -- Necessary for validateBaseTransaction */
import { TRANSACTION_TYPES } from 'ripple-binary-codec'
import { TRANSACTION_TYPES } from '@transia/ripple-binary-codec'
import { ValidationError } from '../../errors'
import { Amount, IssuedCurrencyAmount, Memo, Signer } from '../common'
@@ -157,6 +157,10 @@ export interface BaseTransaction {
* account it says it is from.
*/
TxnSignature?: string
/**
* The network id of the transaction.
*/
NetworkID?: number
}
/**
@@ -250,6 +254,9 @@ export function validateBaseTransaction(common: Record<string, unknown>): void {
) {
throw new ValidationError('BaseTransaction: invalid TxnSignature')
}
if (common.NetworkID !== undefined && typeof common.NetworkID !== 'number') {
throw new ValidationError('BaseTransaction: invalid NetworkID')
}
}
/**

View File

@@ -0,0 +1,26 @@
import { BaseTransaction } from './common'
/**
* Transaction Flags for an EnableAmendment Transaction.
*
* @category Transaction Flags
*/
export enum EnableAmendmentFlags {
/** Support for this amendment increased to at least 80% of trusted validators starting with this ledger version. */
tfGotMajority = 0x00010000,
/** Support for this amendment decreased to less than 80% of trusted validators starting with this ledger version. */
tfLostMajority = 0x00020000,
}
/**
* Mark a change in the status of a proposed amendment when it gains majority, looses majority, or is enabled.
*
* @category Pseudo Transaction Models
*/
export interface EnableAmendment extends BaseTransaction {
TransactionType: 'EnableAmendment'
/** A unique identifier for the amendment. */
Amendment: string
/** The ledger index where this pseudo-transaction appears. */
LedgerSequence: number
}

View File

@@ -1,5 +1,6 @@
export { BaseTransaction } from './common'
export { validate, TransactionAndMetadata, Transaction } from './transaction'
export { TransactionMetadata } from './metadata'
export * from './metadata'
export {
AccountSetAsfFlags,
AccountSetTfFlags,
@@ -14,6 +15,7 @@ export { DepositPreauth } from './depositPreauth'
export { EscrowCancel } from './escrowCancel'
export { EscrowCreate } from './escrowCreate'
export { EscrowFinish } from './escrowFinish'
export { EnableAmendment, EnableAmendmentFlags } from './enableAmendment'
export { NFTokenAcceptOffer } from './NFTokenAcceptOffer'
export { NFTokenBurn } from './NFTokenBurn'
export { NFTokenCancelOffer } from './NFTokenCancelOffer'
@@ -41,7 +43,9 @@ export {
} from './paymentChannelClaim'
export { PaymentChannelCreate } from './paymentChannelCreate'
export { PaymentChannelFund } from './paymentChannelFund'
export { SetFee, SetFeePreAmendment, SetFeePostAmendment } from './setFee'
export { SetRegularKey } from './setRegularKey'
export { SignerListSet } from './signerListSet'
export { TicketCreate } from './ticketCreate'
export { TrustSetFlagsInterface, TrustSetFlags, TrustSet } from './trustSet'
export { UNLModify } from './UNLModify'

View File

@@ -0,0 +1,48 @@
import { BaseTransaction } from './common'
export interface SetFeePreAmendment extends BaseTransaction {
/**
* The charge, in drops of XRP, for the reference transaction, as hex. (This is the transaction cost before scaling for load.)
*/
BaseFee: string
/**
* The cost, in fee units, of the [reference transaction](https://xrpl.org/transaction-cost.html#reference-transaction-cost)
*/
ReferenceFeeUnits: number
/**
* The base reserve, in drops
*/
ReserveBase: number
/**
* The incremental reserve, in drops
*/
ReserveIncrement: number
}
export interface SetFeePostAmendment extends BaseTransaction {
/**
* The charge, in drops of XRP, for the reference transaction. (This is the transaction cost before scaling for load.)
*/
BaseFeeDrops: string
/**
* The base reserve, in drops
*/
ReserveBaseDrops: string
/**
* The incremental reserve, in drops
*/
ReserveIncrementDrops: string
}
/**
* Marks a change in transaction cost or reserve requirements as a result of Fee Voting.
*
* The output will be based on the status of the `XRPFees` amendment at the time of this transaction.
* - Before: {@link SetFeePostAmendment}
* - After: {@link SetFeePostAmendment}
*
* @category Pseudo Transaction Models
*/
export type SetFee = {
TransactionType: 'SetFee'
} & (SetFeePreAmendment | SetFeePostAmendment)

View File

@@ -1,5 +1,5 @@
import BigNumber from 'bignumber.js'
import { xAddressToClassicAddress, isValidXAddress } from 'ripple-address-codec'
import { xAddressToClassicAddress, isValidXAddress } from '@transia/ripple-address-codec'
import type { Client } from '..'
import { ValidationError, XrplError } from '../errors'
@@ -12,6 +12,13 @@ import getFeeXrp from './getFeeXrp'
// Expire unconfirmed transactions after 20 ledger versions, approximately 1 minute, by default
const LEDGER_OFFSET = 20
// Sidechains are expected to have network IDs above this.
// Networks with ID above this restricted number are expected specify an accurate NetworkID field
// in every transaction to that chain to prevent replay attacks.
// Mainnet and testnet are exceptions. More context: https://github.com/XRPLF/rippled/pull/4370
const RESTRICTED_NETWORKS = 1024
const REQUIRED_NETWORKID_VERSION = '1.11.0'
const HOOKS_TESTNET_ID = 21338
interface ClassicAccountAndTag {
classicAccount: string
tag: number | false | undefined
@@ -70,8 +77,10 @@ async function autofill<T extends Transaction>(
setValidAddresses(tx)
setTransactionFlagsToNumber(tx)
const promises: Array<Promise<void>> = []
if (tx.NetworkID == null) {
tx.NetworkID = txNeedsNetworkID(this) ? this.networkID : undefined
}
if (tx.Sequence == null) {
promises.push(setNextValidSequenceNumber(this, tx))
}
@@ -88,6 +97,101 @@ async function autofill<T extends Transaction>(
return Promise.all(promises).then(() => tx)
}
/**
* Determines whether the source rippled version is not later than the target rippled version.
* Example usage: isNotLaterRippledVersion('1.10.0', '1.11.0') returns true.
* isNotLaterRippledVersion('1.10.0', '1.10.0-b1') returns false.
*
* @param source -- The source rippled version.
* @param target -- The target rippled version.
* @returns True if source is earlier than target, false otherwise.
*/
// eslint-disable-next-line max-lines-per-function, max-statements -- Disable for this helper functions.
function isNotLaterRippledVersion(source: string, target: string): boolean {
if (source === target) {
return true
}
const sourceDecomp = source.split('.')
const targetDecomp = target.split('.')
const sourceMajor = parseInt(sourceDecomp[0], 10)
const sourceMinor = parseInt(sourceDecomp[1], 10)
const targetMajor = parseInt(targetDecomp[0], 10)
const targetMinor = parseInt(targetDecomp[1], 10)
// Compare major version
if (sourceMajor !== targetMajor) {
return sourceMajor < targetMajor
}
// Compare minor version
if (sourceMinor !== targetMinor) {
return sourceMinor < targetMinor
}
const sourcePatch = sourceDecomp[2].split('-')
const targetPatch = targetDecomp[2].split('-')
const sourcePatchVersion = parseInt(sourcePatch[0], 10)
const targetPatchVersion = parseInt(targetPatch[0], 10)
// Compare patch version
if (sourcePatchVersion !== targetPatchVersion) {
return sourcePatchVersion < targetPatchVersion
}
// Compare release version
if (sourcePatch.length !== targetPatch.length) {
return sourcePatch.length > targetPatch.length
}
if (sourcePatch.length === 2) {
// Compare different release types
if (!sourcePatch[1][0].startsWith(targetPatch[1][0])) {
return sourcePatch[1] < targetPatch[1]
}
// Compare beta version
if (sourcePatch[1].startsWith('b')) {
return (
parseInt(sourcePatch[1].slice(1), 10) <
parseInt(targetPatch[1].slice(1), 10)
)
}
// Compare rc version
return (
parseInt(sourcePatch[1].slice(2), 10) <
parseInt(targetPatch[1].slice(2), 10)
)
}
return false
}
/**
* Determine if the transaction required a networkID to be valid.
* Transaction needs networkID if later than restricted ID and either the network is hooks testnet
* or build version is >= 1.11.0
*
* @param client -- The connected client.
* @returns True if required networkID, false otherwise.
*/
function txNeedsNetworkID(client: Client): boolean {
if (
client.networkID !== undefined &&
client.networkID > RESTRICTED_NETWORKS
) {
// TODO: remove the buildVersion logic when 1.11.0 is out and widely used.
// Issue: https://github.com/XRPLF/xrpl.js/issues/2339
if (
(client.buildVersion &&
isNotLaterRippledVersion(
REQUIRED_NETWORKID_VERSION,
client.buildVersion,
)) ||
client.networkID === HOOKS_TESTNET_ID
) {
return true
}
}
return false
}
function setValidAddresses(tx: Transaction): void {
validateAccountAddress(tx, 'Account', 'SourceTag')
// eslint-disable-next-line @typescript-eslint/dot-notation -- Destination can exist on Transaction

View File

@@ -1,9 +1,12 @@
import flatMap from 'lodash/flatMap'
import type { Client } from '..'
import { LedgerIndex } from '../models/common'
import { AccountInfoRequest } from '../models/methods'
import { AccountLinesRequest, Trustline } from '../models/methods/accountLines'
import {
AccountLinesRequest,
AccountLinesTrustline,
LedgerIndex,
AccountInfoRequest,
} from '../models'
import { dropsToXrp } from '../utils'
interface Balance {
@@ -12,7 +15,7 @@ interface Balance {
issuer?: string
}
function formatBalances(trustlines: Trustline[]): Balance[] {
function formatBalances(trustlines: AccountLinesTrustline[]): Balance[] {
return trustlines.map((trustline) => ({
value: trustline.balance,
currency: trustline.currency,

View File

@@ -8,8 +8,8 @@ import { LedgerIndex } from '../models/common'
import { OfferFlags } from '../models/ledger/Offer'
import {
BookOffer,
BookOfferCurrency,
BookOffersRequest,
TakerAmount,
} from '../models/methods/bookOffers'
const DEFAULT_LIMIT = 20
@@ -51,8 +51,8 @@ const getOrderbookOptionsSet = new Set([
// eslint-disable-next-line max-params, complexity -- Once bound to Client, getOrderbook only has 3 parameters.
async function getOrderbook(
this: Client,
currency1: TakerAmount,
currency2: TakerAmount,
currency1: BookOfferCurrency,
currency2: BookOfferCurrency,
options: {
limit?: number
ledger_index?: LedgerIndex

View File

@@ -1,4 +1,4 @@
import { decode, encode } from 'ripple-binary-codec'
import { decode, encode } from '@transia/ripple-binary-codec'
import type { Client, SubmitRequest, SubmitResponse, Wallet } from '..'
import { ValidationError, XrplError } from '../errors'

View File

@@ -1,4 +1,4 @@
import { xAddressToClassicAddress, isValidXAddress } from 'ripple-address-codec'
import { xAddressToClassicAddress, isValidXAddress } from '@transia/ripple-address-codec'
/**
* If an address is an X-Address, converts it to a classic address.
@@ -7,7 +7,6 @@ import { xAddressToClassicAddress, isValidXAddress } from 'ripple-address-codec'
* @returns The account's classic address.
* @throws Error if the X-Address has an associated tag.
*/
// eslint-disable-next-line import/prefer-default-export -- okay for a utils file - there could be more exports later
export function ensureClassicAddress(account: string): string {
if (isValidXAddress(account)) {
const { classicAddress, tag } = xAddressToClassicAddress(account)

View File

@@ -1,5 +1,5 @@
import { classicAddressToXAddress } from 'ripple-address-codec'
import { deriveKeypair, deriveAddress } from 'ripple-keypairs'
import { classicAddressToXAddress } from '@transia/ripple-address-codec'
import { deriveKeypair, deriveAddress } from '@transia/ripple-keypairs'
/**
* Derive an X-Address from a public key and a destination tag.

View File

@@ -1,5 +1,7 @@
import { decode } from '@transia/ripple-binary-codec'
import flatMap from 'lodash/flatMap'
import { NFToken } from '../models/ledger/NFTokenPage'
import {
CreatedNode,
isCreatedNode,
@@ -8,31 +10,41 @@ import {
TransactionMetadata,
} from '../models/transactions/metadata'
interface NFToken {
NFToken: {
NFTokenID: string
URI: string
/**
* Ensures that the metadata is in a deserialized format to parse.
*
* @param meta - the metadata from a `tx` method call. Can be in json format or binary format.
* @returns the metadata in a deserialized format.
*/
function ensureDecodedMeta(
meta: TransactionMetadata | string,
): TransactionMetadata {
if (typeof meta === 'string') {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Meta is either metadata or serialized metadata.
return decode(meta) as unknown as TransactionMetadata
}
return meta
}
/**
* Gets the NFTokenID for an NFT recently minted with NFTokenMint.
*
* @param meta - Metadata from the response to submitting an NFTokenMint transaction.
* @param meta - Metadata from the response to submitting and waiting for an NFTokenMint transaction or from a `tx` method call.
* @returns The NFTokenID for the minted NFT.
* @throws if meta is not TransactionMetadata.
*/
export default function getNFTokenID(
meta: TransactionMetadata,
meta: TransactionMetadata | string | undefined,
): string | undefined {
/* eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Provides a nicer error for js users */
if (meta.AffectedNodes === undefined) {
throw new TypeError(`Unable to parse the parameter given to getNFTokenID.
'meta' must be the metadata from an NFTokenMint transaction. Received ${JSON.stringify(
meta,
)} instead.`)
if (typeof meta !== 'string' && meta?.AffectedNodes === undefined) {
throw new TypeError(`Unable to parse the parameter given to getNFTokenID.
'meta' must be the metadata from an NFTokenMint transaction. Received ${JSON.stringify(
meta,
)} instead.`)
}
const decodedMeta = ensureDecodedMeta(meta)
/*
* When a mint results in splitting an existing page,
* it results in a created page and a modified node. Sometimes,
@@ -46,7 +58,7 @@ export default function getNFTokenID(
* if the PreviousFields contains NFTokens
*/
const affectedNodes = meta.AffectedNodes.filter((node) => {
const affectedNodes = decodedMeta.AffectedNodes.filter((node) => {
if (isCreatedNode(node)) {
return node.CreatedNode.LedgerEntryType === 'NFTokenPage'
}

View File

@@ -4,7 +4,7 @@
bitwise operators for and-ing numbers with a mask and bit shifting. */
import BigNumber from 'bignumber.js'
import { decode, encode } from 'ripple-binary-codec'
import { decode, encode } from '@transia/ripple-binary-codec'
import { ValidationError, XrplError } from '../../errors'
import type { Ledger } from '../../models/ledger'

View File

@@ -4,7 +4,7 @@
bitwise operators for and-ing numbers with a mask and bit shifting. */
import BigNumber from 'bignumber.js'
import { decodeAccountID } from 'ripple-address-codec'
import { decodeAccountID } from '@transia/ripple-address-codec'
import hashLedger, {
hashLedgerHeader,

View File

@@ -13,9 +13,9 @@ import {
isValidClassicAddress,
isValidXAddress,
xAddressToClassicAddress,
} from 'ripple-address-codec'
import * as rbc from 'ripple-binary-codec'
import { verify as verifyKeypairSignature } from 'ripple-keypairs'
} from '@transia/ripple-address-codec'
import * as rbc from '@transia/ripple-binary-codec'
import { verify as verifyKeypairSignature } from '@transia/ripple-keypairs'
import { LedgerEntry } from '../models/ledger'
import { Response } from '../models/methods'

View File

@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/no-magic-numbers -- Doing hex string parsing. */
import BigNumber from 'bignumber.js'
import { encodeAccountID } from 'ripple-address-codec'
import { encodeAccountID } from '@transia/ripple-address-codec'
import { XrplError } from '../errors'

View File

@@ -1,5 +1,5 @@
import { encodeForSigningClaim } from 'ripple-binary-codec'
import { sign } from 'ripple-keypairs'
import { encodeForSigningClaim } from '@transia/ripple-binary-codec'
import { sign } from '@transia/ripple-keypairs'
import { xrpToDrops } from './xrpConversion'

View File

@@ -1,5 +1,5 @@
import { encodeForSigningClaim } from 'ripple-binary-codec'
import { verify } from 'ripple-keypairs'
import { encodeForSigningClaim } from '@transia/ripple-binary-codec'
import { verify } from '@transia/ripple-keypairs'
import { xrpToDrops } from './xrpConversion'

View File

@@ -15,13 +15,32 @@ import {
} from '../setupClient'
import { assertRejects } from '../testUtils'
const NetworkID = 1025
const Fee = '10'
const Sequence = 1432
const LastLedgerSequence = 2908734
const HOOKS_TESTNET_ID = 21338
describe('client.autofill', function () {
let testContext: XrplTestContext
async function setupMockRippledVersionAndID(
buildVersion: string,
networkID: number,
): Promise<void> {
await testContext.client.disconnect()
rippled.server_info.withNetworkId.result.info.build_version = buildVersion
rippled.server_info.withNetworkId.result.info.network_id = networkID
testContext.client.connection.on('connected', () => {
testContext.mockRippled?.addResponse(
'server_info',
rippled.server_info.withNetworkId,
)
})
await testContext.client.connect()
}
beforeEach(async () => {
testContext = await setupClient()
})
@@ -32,17 +51,116 @@ describe('client.autofill', function () {
TransactionType: 'DepositPreauth',
Account: 'rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf',
Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo',
NetworkID,
Fee,
Sequence,
LastLedgerSequence,
}
const txResult = await testContext.client.autofill(tx)
assert.strictEqual(txResult.NetworkID, NetworkID)
assert.strictEqual(txResult.Fee, Fee)
assert.strictEqual(txResult.Sequence, Sequence)
assert.strictEqual(txResult.LastLedgerSequence, LastLedgerSequence)
})
it('ignores network ID if missing', async function () {
const tx: Payment = {
TransactionType: 'Payment',
Account: 'XVLhHMPHU98es4dbozjVtdWzVrDjtV18pX8yuPT7y4xaEHi',
Amount: '1234',
Destination: 'X7AcgcsBL6XDcUb289X4mJ8djcdyKaB5hJDWMArnXr61cqZ',
Fee,
Sequence,
LastLedgerSequence,
}
testContext.mockRippled!.addResponse('ledger', rippled.ledger.normal)
const txResult = await testContext.client.autofill(tx)
assert.strictEqual(txResult.NetworkID, undefined)
})
// NetworkID is required in transaction for network > 1024 and from version 1.11.0 or later.
// More context: https://github.com/XRPLF/rippled/pull/4370
it('overrides network ID if > 1024 and version is later than 1.11.0', async function () {
await setupMockRippledVersionAndID('1.11.1', 1025)
const tx: Payment = {
TransactionType: 'Payment',
Account: 'XVLhHMPHU98es4dbozjVtdWzVrDjtV18pX8yuPT7y4xaEHi',
Amount: '1234',
Destination: 'X7AcgcsBL6XDcUb289X4mJ8djcdyKaB5hJDWMArnXr61cqZ',
Fee,
Sequence,
LastLedgerSequence,
}
testContext.mockRippled!.addResponse('ledger', rippled.ledger.normal)
const txResult = await testContext.client.autofill(tx)
assert.strictEqual(txResult.NetworkID, 1025)
})
// NetworkID is only required in transaction for version 1.11.0 or later.
// More context: https://github.com/XRPLF/rippled/pull/4370
it('ignores network ID if > 1024 but version is earlier than 1.11.0', async function () {
await setupMockRippledVersionAndID('1.10.0', 1025)
const tx: Payment = {
TransactionType: 'Payment',
Account: 'XVLhHMPHU98es4dbozjVtdWzVrDjtV18pX8yuPT7y4xaEHi',
Amount: '1234',
Destination: 'X7AcgcsBL6XDcUb289X4mJ8djcdyKaB5hJDWMArnXr61cqZ',
Fee,
Sequence,
LastLedgerSequence,
}
testContext.mockRippled!.addResponse('ledger', rippled.ledger.normal)
const txResult = await testContext.client.autofill(tx)
assert.strictEqual(txResult.NetworkID, undefined)
})
// NetworkID <= 1024 does not require a newtorkID in transaction.
// More context: https://github.com/XRPLF/rippled/pull/4370
it('ignores network ID if <= 1024', async function () {
await setupMockRippledVersionAndID('1.11.1', 1023)
const tx: Payment = {
TransactionType: 'Payment',
Account: 'XVLhHMPHU98es4dbozjVtdWzVrDjtV18pX8yuPT7y4xaEHi',
Amount: '1234',
Destination: 'X7AcgcsBL6XDcUb289X4mJ8djcdyKaB5hJDWMArnXr61cqZ',
Fee,
Sequence,
LastLedgerSequence,
}
testContext.mockRippled!.addResponse('ledger', rippled.ledger.normal)
const txResult = await testContext.client.autofill(tx)
assert.strictEqual(txResult.NetworkID, undefined)
})
// Hooks Testnet requires networkID in transaction regardless of version.
// More context: https://github.com/XRPLF/rippled/pull/4370
it('overrides network ID for hooks testnet', async function () {
await setupMockRippledVersionAndID('1.10.1', HOOKS_TESTNET_ID)
const tx: Payment = {
TransactionType: 'Payment',
Account: 'XVLhHMPHU98es4dbozjVtdWzVrDjtV18pX8yuPT7y4xaEHi',
Amount: '1234',
Destination: 'X7AcgcsBL6XDcUb289X4mJ8djcdyKaB5hJDWMArnXr61cqZ',
Fee,
Sequence,
LastLedgerSequence,
}
testContext.mockRippled!.addResponse('ledger', rippled.ledger.normal)
const txResult = await testContext.client.autofill(tx)
assert.strictEqual(txResult.NetworkID, HOOKS_TESTNET_ID)
})
it('converts Account & Destination X-address to their classic address', async function () {
const tx: Payment = {
TransactionType: 'Payment',

View File

@@ -4,7 +4,7 @@ import cloneDeep from 'lodash/cloneDeep'
import { multisign, ValidationError } from '../../src'
import { Transaction } from '../../src/models/transactions'
import Wallet from '../../src/Wallet'
import { Wallet } from '../../src/Wallet'
import rippled from '../fixtures/rippled'
import {
setupClient,

View File

@@ -10,7 +10,7 @@ import type {
import { destroyServer, getFreePort } from './testUtils'
function createResponse(
export function createResponse(
request: { id: number | string },
response: Record<string, unknown>,
): string {

View File

@@ -12,6 +12,7 @@ import iouPartialPayment from './partialPaymentIOU.json'
import xrpPartialPayment from './partialPaymentXRP.json'
import normalServerInfo from './serverInfo.json'
import highLoadFactor from './serverInfoHighLoadFactor.json'
import withNetworkIDServerInfo from './serverInfoNetworkID.json'
import consensusStream from './streams/consensusPhase.json'
import ledgerStream from './streams/ledger.json'
import manifestStream from './streams/manifest.json'
@@ -84,6 +85,7 @@ const ledger_data = {
const server_info = {
normal: normalServerInfo,
highLoadFactor,
withNetworkId: withNetworkIDServerInfo,
}
const tx = {

View File

@@ -0,0 +1,31 @@
{
"id": 0,
"status": "success",
"type": "response",
"result": {
"info": {
"build_version": "1.11.0-rc2",
"complete_ledgers": "37621036-38327626",
"hostid": "JANE",
"io_latency_ms": 1,
"last_close": {
"converge_time_s": 2,
"proposers": 6
},
"load_factor": 1,
"network_id": 1,
"peers": 113,
"pubkey_node": "n9L6MAkAvZKakewLSJPkCKLxuSQ9jrYXJBd2L4fouhpXauyFh6ZM",
"server_state": "full",
"validated_ledger": {
"age": 0,
"base_fee_xrp": 0.00001,
"hash": "A219F66BB8C9992E80A3C93A5EA408CD54B8F47F2AC1246C271C495F833752BA",
"reserve_base_xrp": 10,
"reserve_inc_xrp": 2,
"seq": 38327626
},
"validation_quorum": 5
}
}
}

View File

@@ -4,7 +4,6 @@
"type": "response",
"result": {
"fee_base": 10,
"fee_ref": 10,
"hostid": "NAP",
"ledger_hash": "60EBABF55F6AB58864242CADA0B24FBEA027F2426917F39CA56576B335C0065A",
"ledger_index": 8819951,

View File

@@ -1,7 +1,6 @@
import { assert } from 'chai'
import { LedgerDataRequest } from '../../../src'
import type { BinaryLedgerEntry } from '../../../src/models/methods/ledgerData'
import { LedgerDataBinaryLedgerEntry, LedgerDataRequest } from '../../../src'
import serverUrl from '../serverUrl'
import {
setupClient,
@@ -58,7 +57,7 @@ describe('ledger_data', function () {
assert.equal(ledgerDataResponse.result.state.length, 5)
ledgerDataResponse.result.state.forEach((item) => {
assert.typeOf((item as BinaryLedgerEntry).data, 'string')
assert.typeOf((item as LedgerDataBinaryLedgerEntry).data, 'string')
assert.typeOf(item.index, 'string')
})
},

View File

@@ -1,5 +1,5 @@
import { assert } from 'chai'
import { decode } from 'ripple-binary-codec'
import { decode } from '@transia/ripple-binary-codec'
import {
AccountSet,

View File

@@ -1,5 +1,5 @@
import { assert } from 'chai'
import { decode } from 'ripple-binary-codec'
import { decode } from '@transia/ripple-binary-codec'
import {
AccountSet,

View File

@@ -158,7 +158,6 @@ describe('subscribe', function () {
// Explicitly checking that there are only known fields in the return
const expectedResult = {
fee_base: ledgerResponse.fee_base,
fee_ref: ledgerResponse.fee_ref,
ledger_hash: ledgerResponse.ledger_hash,
ledger_index: ledgerResponse.ledger_index,
ledger_time: ledgerResponse.ledger_time,
@@ -166,7 +165,6 @@ describe('subscribe', function () {
reserve_inc: ledgerResponse.reserve_inc,
validated_ledgers: ledgerResponse.validated_ledgers,
}
assert.equal(response.type, 'response')
assert.deepEqual(response.result, expectedResult)

View File

@@ -1,69 +1,87 @@
import { assert } from 'chai'
import _ from 'lodash'
import { Client } from 'xrpl'
import { TransactionMetadata, TxRequest } from 'xrpl'
import { convertStringToHex, getNFTokenID, NFTokenMint } from '../../../src'
import { hashSignedTx } from '../../../src/utils/hashes'
import serverUrl from '../serverUrl'
import {
convertStringToHex,
getNFTokenID,
NFTokenMint,
TransactionMetadata,
} from '../../../src'
setupClient,
teardownClient,
type XrplIntegrationTestContext,
} from '../setup'
import { testTransaction } from '../utils'
// how long before each test case times out
const TIMEOUT = 20000
describe('NFTokenMint', function () {
// TODO: Once we update our integration tests to handle NFTs, replace this client with XrplIntegrationTestContext
let testContext: XrplIntegrationTestContext
beforeEach(async () => {
testContext = await setupClient(serverUrl)
})
afterEach(async () => teardownClient(testContext))
it(
'get NFTokenID',
async function () {
const client = new Client('wss://s.altnet.rippletest.net:51233/')
await client.connect()
const { wallet, balance: _balance } = await client.fundWallet(null, {
usageContext: 'integration-test',
})
const tx: NFTokenMint = {
TransactionType: 'NFTokenMint',
Account: wallet.address,
Account: testContext.wallet.address,
URI: convertStringToHex('https://www.google.com'),
NFTokenTaxon: 0,
}
try {
const response = await client.submitAndWait(tx, {
wallet,
})
assert.equal(response.type, 'response')
assert.equal(
(response.result.meta as TransactionMetadata).TransactionResult,
'tesSUCCESS',
)
const response = await testTransaction(
testContext.client,
tx,
testContext.wallet,
)
assert.equal(response.type, 'response')
const accountNFTs = await client.request({
command: 'account_nfts',
account: wallet.address,
})
const nftokenID =
getNFTokenID(response.result.meta as TransactionMetadata) ??
'undefined'
const accountHasNFT = accountNFTs.result.account_nfts.some(
(value) => value.NFTokenID === nftokenID,
)
assert.isTrue(
accountHasNFT,
`Expected to find an NFT with NFTokenID ${nftokenID} in account ${
wallet.address
} but did not find it.
\n\nHere's what was returned from 'account_nfts' for ${
wallet.address
}: ${JSON.stringify(accountNFTs)}`,
)
} finally {
await client.disconnect()
const txRequest: TxRequest = {
command: 'tx',
transaction: hashSignedTx(response.result.tx_blob),
}
const txResponse = await testContext.client.request(txRequest)
assert.equal(
(txResponse.result.meta as TransactionMetadata).TransactionResult,
'tesSUCCESS',
)
const accountNFTs = await testContext.client.request({
command: 'account_nfts',
account: testContext.wallet.address,
})
const nftokenID =
getNFTokenID(txResponse.result.meta as TransactionMetadata) ??
'undefined'
const accountHasNFT = accountNFTs.result.account_nfts.some(
(value) => value.NFTokenID === nftokenID,
)
assert.isTrue(
accountHasNFT,
`Expected to find an NFT with NFTokenID ${nftokenID} in account ${
testContext.wallet.address
} but did not find it.
\n\nHere's what was returned from 'account_nfts' for ${
testContext.wallet.address
}: ${JSON.stringify(accountNFTs)}`,
)
const binaryTxResponse = await testContext.client.request({
...txRequest,
binary: true,
})
assert.equal(
nftokenID,
getNFTokenID(binaryTxResponse.result.meta) ?? 'undefined',
`getNFTokenID produced a different outcome when decoding the metadata in binary format.`,
)
},
TIMEOUT,
)

View File

@@ -1,7 +1,7 @@
import { assert } from 'chai'
import omit from 'lodash/omit'
import throttle from 'lodash/throttle'
import { decode } from 'ripple-binary-codec'
import { decode } from '@transia/ripple-binary-codec'
import {
Client,

View File

@@ -22,7 +22,7 @@ describe('mock rippled tests', function () {
}
await assertRejects(
testContext.client.request({ command: 'server_info' }),
testContext.client.request({ command: 'account_info' }),
RippledError,
)
})

View File

@@ -232,4 +232,17 @@ describe('BaseTransaction', function () {
'BaseTransaction: invalid Memos',
)
})
it(`Handles invalid NetworkID`, function () {
const invalidNetworkID = {
Account: 'r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe',
TransactionType: 'Payment',
NetworkID: '1024',
}
assert.throws(
() => validateBaseTransaction(invalidNetworkID),
ValidationError,
'BaseTransaction: invalid NetworkID',
)
})
})

View File

@@ -1,10 +1,11 @@
import { Client } from '../src/client'
// eslint-disable-next-line import/no-deprecated -- Will remove in 3.0.0
import BroadcastClient from '../src/client/BroadcastClient'
import { BroadcastClient } from '../src/client/BroadcastClient'
import createMockRippled, {
type MockedWebSocketServer,
} from './createMockRippled'
import rippled from './fixtures/rippled'
import { destroyServer, getFreePort } from './testUtils'
export interface XrplTestContext {
@@ -29,6 +30,10 @@ async function setupMockRippledConnection(
context.client.on('error', () => {
// We must have an error listener attached for reconnect errors
})
context.mockRippled?.addResponse(
'server_info',
rippled.server_info.withNetworkId,
)
return context.client.connect().then(() => context)
}

View File

@@ -2,7 +2,7 @@ import fs from 'fs'
import path from 'path'
import { assert } from 'chai'
import { encode } from 'ripple-binary-codec'
import { encode } from '@transia/ripple-binary-codec'
import { OfferCreate, Transaction, ValidationError } from '../../src'
import {

View File

@@ -1,9 +1,9 @@
import { assert } from 'chai'
import { decode } from 'ripple-binary-codec'
import { decode } from '@transia/ripple-binary-codec'
import { NFTokenMint, Payment, Transaction } from '../../src'
import ECDSA from '../../src/ECDSA'
import Wallet from '../../src/Wallet'
import { Wallet } from '../../src/Wallet'
import requests from '../fixtures/requests'
import responses from '../fixtures/responses'

Some files were not shown because too many files have changed in this diff Show More