Skip to main content

rshooks_api/api/
mod.rs

1use crate::_c;
2
3mod control;
4mod etxn;
5mod float;
6mod ledger;
7mod otxn;
8mod slot;
9mod state;
10mod sto;
11mod trace;
12mod util;
13
14pub use control::*;
15pub use etxn::*;
16pub use float::*;
17pub use ledger::*;
18pub use otxn::*;
19pub use slot::*;
20pub use state::*;
21pub use sto::*;
22pub use trace::*;
23pub use util::*;
24
25/// Flags canonical
26pub const TF_CANONICAL: u32 = _c::tfCANONICAL;
27
28/// Account id buffer lenght
29pub const ACC_ID_LEN: usize = 20;
30/// Public key buffer lenght
31pub const PUB_KEY_LEN: usize = 33;
32/// Currency code buffer lenght
33pub const CURRENCY_CODE_SIZE: usize = 20;
34/// Ledger hash buffer lenght
35pub const LEDGER_HASH_LEN: usize = 32;
36/// Keylet buffer lenght
37pub const KEYLET_LEN: usize = 34;
38/// State key buffer lenght
39pub const STATE_KEY_LEN: usize = 32;
40/// NameSpace buffer lenght
41pub const NAMESPACE_LEN: usize = 32;
42/// Nonce buffer lenght
43pub const NONCE_LEN: usize = 32;
44/// Hash buffer lenght
45pub const HASH_LEN: usize = 32;
46/// Native amount buffer lenght
47pub const NATIVE_AMOUNT_LEN: usize = 8;
48/// IOU amount buffer lenght
49pub const IOU_AMOUNT_LEN: usize = 48;
50/// Emit details buffer lenght
51pub const EMIT_DETAILS_SIZE: usize = 105;
52
53/// Buffer of the specified size
54pub type Buffer<const T: usize> = [u8; T];
55
56/// Account id buffer
57pub type AccountId = Buffer<ACC_ID_LEN>;
58/// Public key buffer
59pub type PublicKey = Buffer<PUB_KEY_LEN>;
60/// Hash buffer
61pub type Hash = Buffer<HASH_LEN>;
62/// Keylet buffer
63pub type Keylet = Buffer<KEYLET_LEN>;
64/// State key buffer
65pub type StateKey = Buffer<STATE_KEY_LEN>;
66/// Namespace key buffer
67pub type NameSpace = Buffer<NAMESPACE_LEN>;
68/// Nonce buffer
69pub type Nonce = Buffer<NONCE_LEN>;
70/// Native amount buffer
71pub type NativeAmount = Buffer<NATIVE_AMOUNT_LEN>;
72/// IOU amount buffer
73pub type NonNativeAmount = Buffer<IOU_AMOUNT_LEN>;
74/// Emit details buffer
75pub type EmitDetails = Buffer<EMIT_DETAILS_SIZE>;
76/// Currency code buffer
77pub type CurrencyCode = Buffer<CURRENCY_CODE_SIZE>;
78
79/// Transaction type
80#[allow(missing_docs)]
81#[derive(Clone, Copy)]
82#[repr(u32)]
83pub enum TxnType {
84    Payment = _c::ttPAYMENT,
85    EscrowCreate = 1,
86    EscrowFinish = 2,
87    AccountSet = 3,
88    EscrowCancel = 4,
89    RegularKeySet = 5,
90    // NicknameSet = 6,
91    OfferCreate = 7,
92    OfferCancel = 8,
93    TicketCreate = 10,
94    // SpinalTap = 11,
95    SignerListSet = 12,
96    PaychanCreate = 13,
97    PaychanFund = 14,
98    PaychanClaim = 15,
99    CheckCreate = 16,
100    CheckCash = 17,
101    CheckCancel = 18,
102    DepositPreauth = 19,
103    TrustSet = 20,
104    AccountDelete = 21,
105    HookSet = 22,
106    NFTokenMint = 25,
107    NFTokenBurn = 26,
108    NFTokenCreateOffer = 27,
109    NFTokenCancelOffer = 28,
110    NFTokenAcceptOffer = 29,
111    URITokenMint = 45,
112    URITokenBurn = 46,
113    URITokenBuy = 47,
114    URITokenCreateSellOffer = 48,
115    URITokenCancelSellOffer = 49,
116    Remit = 95,
117    GenesisMint = 96,
118    Import = 97,
119    ClaimReward = 98,
120    Invoke = 99,
121    Amendment = 100,
122    Fee = 101,
123    UnlModify = 102,
124}
125
126/// Account type
127#[allow(missing_docs)]
128#[derive(Clone, Copy)]
129#[repr(u32)]
130pub enum AccountType {
131    Account = _c::atACCOUNT,
132    Owner = _c::atOWNER,
133    Destination = _c::atDESTINATION,
134    Issuer = _c::atISSUER,
135    Authorize = _c::atAUTHORIZE,
136    Unauthorize = _c::atUNAUTHORIZE,
137    Target = _c::atTARGET,
138    RegularKey = _c::atREGULARKEY,
139    PseudoCallback = _c::atPSEUDOCALLBACK,
140}
141
142/// Amount type
143#[allow(missing_docs)]
144#[derive(Clone, Copy)]
145#[repr(u32)]
146pub enum AmountType {
147    Amount = _c::amAMOUNT,
148    Balance = _c::amBALANCE,
149    LimitAmount = _c::amLIMITAMOUNT,
150    TakerPays = _c::amTAKERPAYS,
151    TakerGets = _c::amTAKERGETS,
152    LowLimit = _c::amLOWLIMIT,
153    HighLimit = _c::amHIGHLIMIT,
154    Fee = _c::amFEE,
155    SendMax = _c::amSENDMAX,
156    DeliverMin = _c::amDELIVERMIN,
157    MinimumOffer = _c::amMINIMUMOFFER,
158    RippleEscrow = _c::amRIPPLEESCROW,
159    DeliveredAmount = _c::amDELIVEREDAMOUNT,
160}
161
162/// Keylet type
163#[allow(missing_docs)]
164#[derive(Clone, Copy)]
165pub enum KeyletType<'a> {
166    Hook(&'a AccountId),
167    HookState(&'a AccountId, &'a StateKey),
168    Account(&'a AccountId),
169    Amendments,
170    Child(&'a Hash),
171    Skip(Option<(u32, u32)>),
172    Fees,
173    NegativeUnl,
174    Line(&'a AccountId, &'a AccountId, &'a CurrencyCode),
175    Offer(&'a AccountId, u32),
176    Quality(&'a [u8], u32, u32),
177    EmittedDir,
178    Signers(&'a AccountId),
179    Check(&'a AccountId, u32),
180    DepositPreauth(&'a AccountId, &'a AccountId),
181    Unchecked(&'a Hash),
182    OwnerDir(&'a AccountId),
183    Page(&'a Hash, u32, u32),
184    Escrow(&'a AccountId, u32),
185    Paychan(&'a AccountId, &'a AccountId, u32),
186    EmittedTxn(&'a Hash),
187    NFTOffer(&'a AccountId, u32),
188    HookDefinition(&'a Hash),
189    HookStateDir(&'a AccountId, &'a NameSpace),
190}
191
192/// Field or amount type
193///
194/// Used as return of [slot_type] function
195#[derive(Clone, Copy)]
196pub enum FieldOrXrpAmount {
197    /// Field ID
198    Field(FieldId),
199    /// STI_AMOUNT type contains a native amount
200    NativeAmount,
201    /// STI_AMOUNT type contains non-native amount
202    NonNativeAmount,
203}
204
205/// Flags for [slot_type]
206#[derive(Clone, Copy)]
207pub enum SlotTypeFlags {
208    /// Field
209    Field,
210    /// STI_AMOUNT type contains a native amount
211    NativeAmount,
212}
213
214/// Field type
215#[allow(missing_docs)]
216#[derive(Clone, Copy)]
217#[repr(u32)]
218pub enum FieldId {
219    CloseResolution = _c::sfCloseResolution,
220    Method = _c::sfMethod,
221    TransactionResult = _c::sfTransactionResult,
222    TickSize = _c::sfTickSize,
223    UNLModifyDisabling = _c::sfUNLModifyDisabling,
224    HookResult = _c::sfHookResult,
225    LedgerEntryType = _c::sfLedgerEntryType,
226    TransactionType = _c::sfTransactionType,
227    SignerWeight = _c::sfSignerWeight,
228    TransferFee = _c::sfTransferFee,
229    Version = _c::sfVersion,
230    HookStateChangeCount = _c::sfHookStateChangeCount,
231    HookEmitCount = _c::sfHookEmitCount,
232    HookExecutionIndex = _c::sfHookExecutionIndex,
233    HookApiVersion = _c::sfHookApiVersion,
234    NetworkID = _c::sfNetworkID,
235    Flags = _c::sfFlags,
236    SourceTag = _c::sfSourceTag,
237    Sequence = _c::sfSequence,
238    PreviousTxnLgrSeq = _c::sfPreviousTxnLgrSeq,
239    LedgerSequence = _c::sfLedgerSequence,
240    CloseTime = _c::sfCloseTime,
241    ParentCloseTime = _c::sfParentCloseTime,
242    SigningTime = _c::sfSigningTime,
243    Expiration = _c::sfExpiration,
244    TransferRate = _c::sfTransferRate,
245    WalletSize = _c::sfWalletSize,
246    OwnerCount = _c::sfOwnerCount,
247    DestinationTag = _c::sfDestinationTag,
248    HighQualityIn = _c::sfHighQualityIn,
249    HighQualityOut = _c::sfHighQualityOut,
250    LowQualityIn = _c::sfLowQualityIn,
251    LowQualityOut = _c::sfLowQualityOut,
252    QualityIn = _c::sfQualityIn,
253    QualityOut = _c::sfQualityOut,
254    StampEscrow = _c::sfStampEscrow,
255    BondAmount = _c::sfBondAmount,
256    LoadFee = _c::sfLoadFee,
257    OfferSequence = _c::sfOfferSequence,
258    FirstLedgerSequence = _c::sfFirstLedgerSequence,
259    LastLedgerSequence = _c::sfLastLedgerSequence,
260    TransactionIndex = _c::sfTransactionIndex,
261    OperationLimit = _c::sfOperationLimit,
262    ReferenceFeeUnits = _c::sfReferenceFeeUnits,
263    ReserveBase = _c::sfReserveBase,
264    ReserveIncrement = _c::sfReserveIncrement,
265    SetFlag = _c::sfSetFlag,
266    ClearFlag = _c::sfClearFlag,
267    SignerQuorum = _c::sfSignerQuorum,
268    CancelAfter = _c::sfCancelAfter,
269    FinishAfter = _c::sfFinishAfter,
270    SignerListID = _c::sfSignerListID,
271    SettleDelay = _c::sfSettleDelay,
272    TicketCount = _c::sfTicketCount,
273    TicketSequence = _c::sfTicketSequence,
274    NFTokenTaxon = _c::sfNFTokenTaxon,
275    MintedNFTokens = _c::sfMintedNFTokens,
276    BurnedNFTokens = _c::sfBurnedNFTokens,
277    HookStateCount = _c::sfHookStateCount,
278    EmitGeneration = _c::sfEmitGeneration,
279    LockCount = _c::sfLockCount,
280    FirstNFTokenSequence = _c::sfFirstNFTokenSequence,
281    XahauActivationLgrSeq = _c::sfXahauActivationLgrSeq,
282    ImportSequence = _c::sfImportSequence,
283    RewardTime = _c::sfRewardTime,
284    RewardLgrFirst = _c::sfRewardLgrFirst,
285    RewardLgrLast = _c::sfRewardLgrLast,
286    IndexNext = _c::sfIndexNext,
287    IndexPrevious = _c::sfIndexPrevious,
288    BookNode = _c::sfBookNode,
289    OwnerNode = _c::sfOwnerNode,
290    BaseFee = _c::sfBaseFee,
291    ExchangeRate = _c::sfExchangeRate,
292    LowNode = _c::sfLowNode,
293    HighNode = _c::sfHighNode,
294    DestinationNode = _c::sfDestinationNode,
295    Cookie = _c::sfCookie,
296    ServerVersion = _c::sfServerVersion,
297    NFTokenOfferNode = _c::sfNFTokenOfferNode,
298    EmitBurden = _c::sfEmitBurden,
299    HookInstructionCount = _c::sfHookInstructionCount,
300    HookReturnCode = _c::sfHookReturnCode,
301    ReferenceCount = _c::sfReferenceCount,
302    AccountIndex = _c::sfAccountIndex,
303    AccountCount = _c::sfAccountCount,
304    RewardAccumulator = _c::sfRewardAccumulator,
305    EmailHash = _c::sfEmailHash,
306    TakerPaysCurrency = _c::sfTakerPaysCurrency,
307    TakerPaysIssuer = _c::sfTakerPaysIssuer,
308    TakerGetsCurrency = _c::sfTakerGetsCurrency,
309    TakerGetsIssuer = _c::sfTakerGetsIssuer,
310    LedgerHash = _c::sfLedgerHash,
311    ParentHash = _c::sfParentHash,
312    TransactionHash = _c::sfTransactionHash,
313    AccountHash = _c::sfAccountHash,
314    PreviousTxnID = _c::sfPreviousTxnID,
315    LedgerIndex = _c::sfLedgerIndex,
316    WalletLocator = _c::sfWalletLocator,
317    RootIndex = _c::sfRootIndex,
318    AccountTxnID = _c::sfAccountTxnID,
319    NFTokenID = _c::sfNFTokenID,
320    EmitParentTxnID = _c::sfEmitParentTxnID,
321    EmitNonce = _c::sfEmitNonce,
322    EmitHookHash = _c::sfEmitHookHash,
323    BookDirectory = _c::sfBookDirectory,
324    InvoiceID = _c::sfInvoiceID,
325    // Nickname = _c::sfNickname,
326    Amendment = _c::sfAmendment,
327    HookOn = _c::sfHookOn,
328    Digest = _c::sfDigest,
329    Channel = _c::sfChannel,
330    ConsensusHash = _c::sfConsensusHash,
331    CheckID = _c::sfCheckID,
332    ValidatedHash = _c::sfValidatedHash,
333    PreviousPageMin = _c::sfPreviousPageMin,
334    NextPageMin = _c::sfNextPageMin,
335    NFTokenBuyOffer = _c::sfNFTokenBuyOffer,
336    NFTokenSellOffer = _c::sfNFTokenSellOffer,
337    HookStateKey = _c::sfHookStateKey,
338    HookHash = _c::sfHookHash,
339    HookNamespace = _c::sfHookNamespace,
340    HookSetTxnID = _c::sfHookSetTxnID,
341    OfferID = _c::sfOfferID,
342    EscrowID = _c::sfEscrowID,
343    URITokenID = _c::sfURITokenID,
344    GovernanceFlags = _c::sfGovernanceFlags,
345    GovernanceMarks = _c::sfGovernanceMarks,
346    EmittedTxnID = _c::sfEmittedTxnID,
347    Amount = _c::sfAmount,
348    Balance = _c::sfBalance,
349    LimitAmount = _c::sfLimitAmount,
350    TakerPays = _c::sfTakerPays,
351    TakerGets = _c::sfTakerGets,
352    LowLimit = _c::sfLowLimit,
353    HighLimit = _c::sfHighLimit,
354    Fee = _c::sfFee,
355    SendMax = _c::sfSendMax,
356    DeliverMin = _c::sfDeliverMin,
357    MinimumOffer = _c::sfMinimumOffer,
358    RippleEscrow = _c::sfRippleEscrow,
359    DeliveredAmount = _c::sfDeliveredAmount,
360    NFTokenBrokerFee = _c::sfNFTokenBrokerFee,
361    LockedBalance = _c::sfLockedBalance,
362    BaseFeeDrops = _c::sfBaseFeeDrops,
363    ReserveBaseDrops = _c::sfReserveBaseDrops,
364    ReserveIncrementDrops = _c::sfReserveIncrementDrops,
365    PublicKey = _c::sfPublicKey,
366    MessageKey = _c::sfMessageKey,
367    SigningPubKey = _c::sfSigningPubKey,
368    TxnSignature = _c::sfTxnSignature,
369    URI = _c::sfURI,
370    Signature = _c::sfSignature,
371    Domain = _c::sfDomain,
372    FundCode = _c::sfFundCode,
373    RemoveCode = _c::sfRemoveCode,
374    ExpireCode = _c::sfExpireCode,
375    CreateCode = _c::sfCreateCode,
376    MemoType = _c::sfMemoType,
377    MemoData = _c::sfMemoData,
378    MemoFormat = _c::sfMemoFormat,
379    Fulfillment = _c::sfFulfillment,
380    Condition = _c::sfCondition,
381    MasterSignature = _c::sfMasterSignature,
382    UNLModifyValidator = _c::sfUNLModifyValidator,
383    ValidatorToDisable = _c::sfValidatorToDisable,
384    ValidatorToReEnable = _c::sfValidatorToReEnable,
385    HookStateData = _c::sfHookStateData,
386    HookReturnString = _c::sfHookReturnString,
387    HookParameterName = _c::sfHookParameterName,
388    HookParameterValue = _c::sfHookParameterValue,
389    Blob = _c::sfBlob,
390    Account = _c::sfAccount,
391    Owner = _c::sfOwner,
392    Destination = _c::sfDestination,
393    Issuer = _c::sfIssuer,
394    Authorize = _c::sfAuthorize,
395    Unauthorize = _c::sfUnauthorize,
396    RegularKey = _c::sfRegularKey,
397    NFTokenMinter = _c::sfNFTokenMinter,
398    EmitCallback = _c::sfEmitCallback,
399    HookAccount = _c::sfHookAccount,
400    Inform = _c::sfInform,
401    Indexes = _c::sfIndexes,
402    Hashes = _c::sfHashes,
403    Amendments = _c::sfAmendments,
404    NFTokenOffers = _c::sfNFTokenOffers,
405    HookNamespaces = _c::sfHookNamespaces,
406    URITokenIDs = _c::sfURITokenIDs,
407    Paths = _c::sfPaths,
408    TransactionMetaData = _c::sfTransactionMetaData,
409    CreatedNode = _c::sfCreatedNode,
410    DeletedNode = _c::sfDeletedNode,
411    ModifiedNode = _c::sfModifiedNode,
412    PreviousFields = _c::sfPreviousFields,
413    FinalFields = _c::sfFinalFields,
414    NewFields = _c::sfNewFields,
415    TemplateEntry = _c::sfTemplateEntry,
416    Memo = _c::sfMemo,
417    SignerEntry = _c::sfSignerEntry,
418    EmitDetails = _c::sfEmitDetails,
419    Hook = _c::sfHook,
420    Signer = _c::sfSigner,
421    Majority = _c::sfMajority,
422    DisabledValidator = _c::sfDisabledValidator,
423    EmittedTxn = _c::sfEmittedTxn,
424    HookExecution = _c::sfHookExecution,
425    HookDefinition = _c::sfHookDefinition,
426    HookParameter = _c::sfHookParameter,
427    HookGrant = _c::sfHookGrant,
428    GenesisMint = _c::sfGenesisMint,
429    ActiveValidator = _c::sfActiveValidator,
430    ImportVLKey = _c::sfImportVLKey,
431    HookEmission = _c::sfHookEmission,
432    MintURIToken = _c::sfMintURIToken,
433    AmountEntry = _c::sfAmountEntry,
434    Signers = _c::sfSigners,
435    SignerEntries = _c::sfSignerEntries,
436    Template = _c::sfTemplate,
437    Necessary = _c::sfNecessary,
438    Sufficient = _c::sfSufficient,
439    AffectedNodes = _c::sfAffectedNodes,
440    Memos = _c::sfMemos,
441    NFTokens = _c::sfNFTokens,
442    Majorities = _c::sfMajorities,
443    DisabledValidators = _c::sfDisabledValidators,
444    HookExecutions = _c::sfHookExecutions,
445    HookParameters = _c::sfHookParameters,
446    HookGrants = _c::sfHookGrants,
447    GenesisMints = _c::sfGenesisMints,
448    ActiveValidators = _c::sfActiveValidators,
449    ImportVLKeys = _c::sfImportVLKeys,
450    HookEmissions = _c::sfHookEmissions,
451    Amounts = _c::sfAmounts,
452}
453
454/// Data representation
455#[derive(Clone, Copy)]
456pub enum DataRepr {
457    /// As UTF-8
458    AsUTF8 = 0,
459    /// As hexadecimal
460    AsHex = 1,
461}
462
463/// Flags for otxn_id\
464/// If 0:\
465/// Write the canonical hash of the originating transaction.\
466///
467/// If 1 AND the originating transaction is an EMIT_FAILURE:\
468/// Write the canonical hash of the emitting transaction.\
469#[derive(Clone, Copy)]
470#[repr(u32)]
471pub enum TxnTypeFlags {
472    /// Write the canonical hash of the originating transaction.
473    OriginatingTxn = 0,
474    /// Write the canonical hash of the emitting transaction.
475    EmittingTxnIfEmitFailure = 1,
476}
477
478/// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]).
479//
480/// This is simple version of Result type
481/// to comply XRPL Hooks Webassembly restrictions
482#[must_use]
483pub enum Result<T> {
484    /// Contains the success value
485    Ok(T),
486    /// Contains the error value
487    Err(Error),
488}
489
490pub use self::Result::*;
491
492#[allow(unused_attributes)]
493#[must_use]
494impl<T> Result<T> {
495    /// Returns the contained [`Ok`] value, consuming the `self` value.
496    ///
497    /// # Rollbacks
498    ///
499    /// Rollbacks if the value is an [`Err`], with a rollback message and error code.
500    #[inline(always)]
501    pub fn expect(self, msg: &[u8]) -> T {
502        match self {
503            Err(e) => rollback(msg, e.code() as _),
504            Ok(val) => val,
505        }
506    }
507
508    /// Returns the contained [`Ok`] value, or a None if the value is an DOES_NOT_EXIST error.
509    ///
510    /// # Rollbacks
511    ///
512    /// Rollbacks if the value is an [`Err`] except for DOES_NOT_EXIST error.
513    #[inline(always)]
514    pub fn optional(self) -> Option<T> {
515        match self {
516            Ok(val) => Some(val),
517            Err(e) if e.code() == Error::DoesntExist.code() => None,
518            Err(e) => {
519                rollback(b"error", e.code() as _);
520            }
521        }
522    }
523
524    /// Returns the contained [`Ok`] value, consuming the `self` value.
525    ///
526    /// Because this function may rollback, its use is generally discouraged.
527    /// Instead, prefer to use pattern matching and handle the [`Err`]
528    /// case explicitly.
529    ///
530    /// # Rollbacks
531    ///
532    /// Rollbacks if the value is an [`Err`], with a "error" and error code provided by the
533    /// [`Err`]'s value.
534    #[inline(always)]
535    pub fn unwrap(self) -> T {
536        match self {
537            Err(e) => rollback(b"error", e.code() as _),
538            Ok(val) => val,
539        }
540    }
541
542    /// Returns the contained [`Ok`] value, consuming the `self` value,
543    /// without checking that the value is not an [`Err`].
544    ///
545    /// # Safety
546    ///
547    /// Calling this method on an [`Err`] is *[undefined behavior]*.
548    ///
549    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
550    #[inline(always)]
551    pub unsafe fn unwrap_unchecked(self) -> T {
552        match self {
553            Ok(val) => val,
554            // SAFETY: the safety contract must be upheld by the caller.
555            Err(_) => unsafe { core::hint::unreachable_unchecked() },
556        }
557    }
558
559    /// Returns `true` if the result is [`Ok`].
560    #[must_use]
561    #[inline(always)]
562    pub const fn is_ok(&self) -> bool {
563        matches!(*self, Ok(_))
564    }
565
566    /// Returns `true` if the result is [`Err`].
567    #[must_use]
568    #[inline(always)]
569    pub const fn is_err(&self) -> bool {
570        !self.is_ok()
571    }
572}
573
574/// Possible errors returned by Hook APIs.
575///
576/// Errors are global across all Hook APIs.
577#[derive(Clone, Copy)]
578#[repr(i32)]
579pub enum Error {
580    /// Non-negative return codes refer always to success and usually indicate the number of bytes written or events performed, depending on the specific API.
581    // SUCCESS = _c::SUCCESS,
582    /// A pointer or buffer length provided as a parameter described memory outside of the Hook's allowed memory region.
583    OutOfBounds = _c::OUT_OF_BOUNDS,
584    /// Reserved for internal invariant trips, generally unrelated to inputs.
585    /// These should be reported with an issue.
586    InternalError = _c::INTERNAL_ERROR,
587    /// Attempted to set a parameter or value larger than the allowed space .
588    TooBig = _c::TOO_BIG,
589    /// The API was unable to produce output to the write_ptr because the specified write_len was too small
590    TooSmall = _c::TOO_SMALL,
591    /// The requested object or item wasn't found
592    DoesntExist = _c::DOESNT_EXIST,
593    /// The Hook attempted to allocate an item into a slot, but there were no slots free.
594    /// To avoid ensure re-use of existing slots. The maximum number of slots is 255.
595    NoFreeSlots = _c::NO_FREE_SLOTS,
596    /// One or more of the parameters to the API were invalid according to the individual API's specification.
597    InvalidArgument = _c::INVALID_ARGUMENT,
598    /// Some APIs allow for a once-per-execution parameter to be set.
599    /// A second attempt to set a once-per-execution parameter results in this error.
600    AlreadySet = _c::ALREADY_SET,
601    /// An API required the Hook to do something before the API is allowed to be called.
602    /// Check the API's documentation.
603    PrerequisiteNotMet = _c::PREREQUISITE_NOT_MET,
604    /// During fee calculation if an absurdly large fee is calculated this error is returned.
605    FeeTooLarge = _c::FEE_TOO_LARGE,
606    /// An attempt to emit() a TXN was unsccessful for any of a number of reasons.
607    /// Check the trace log of the rippled to which you are submitting the originating TXN.
608    EmissionFailure = _c::EMISSION_FAILURE,
609    /// A Hook may only use up to 256 calls to nonce() per execution.
610    /// Further calls result in this error code.
611    TooManyNonces = _c::TOO_MANY_NONCES,
612    /// A Hook must declare ahead of time how many TXN it intends to emit().
613    /// If it emits fewer than this many, this is allowed.
614    /// If it emits more than this many this error is returned.
615    TooManyEmittedTxn = _c::TOO_MANY_EMITTED_TXN,
616    /// While Hooks is/was in development an API may return this if some or all of that API is planned but not yet implemented.
617    NotImplemented = _c::NOT_IMPLEMENTED,
618    /// An API which accepts a 20 byte Account ID may return this if, in its opinion, the Account ID was not valid for any reason.
619    InvalidAccount = _c::INVALID_ACCOUNT,
620    /// All loops inside a Hook must declare at the top of the loop, as the first non trivial instruction,
621    /// before any branch instruction, the promised maximum number of iterations of the loop.
622    /// If this promise is violated the hook terminates immediately with this error code.
623    GuardViolation = _c::GUARD_VIOLATION,
624    /// The requested serialized field could not be found in the specified object.
625    InvalidField = _c::INVALID_FIELD,
626    /// While parsing serialized content an error was encountered (typically indicating an invalidly serialized object).
627    ParseError = _c::PARSE_ERROR,
628    /// Used internally to communicate a rollback event.
629    RcRollback = _c::RC_ROLLBACK,
630    /// Used internally to communicate an accept event.
631    RcAccept = _c::RC_ACCEPT,
632    /// Specified keylet could not be found, or keylet is invalid
633    NoSuchKeylet = _c::NO_SUCH_KEYLET,
634    /// API was asked to assume object under analysis is an STArray but it was not.
635    NotAnArray = _c::NOT_AN_ARRAY,
636    /// API was asked to assume object under analysis is an STObject but it was not.
637    NotAnObject = _c::NOT_AN_OBJECT,
638    /// A floating point operation resulted in Not-A-Number or API call attempted to specify an XFL floating point number outside of the expressible range of XFL.
639    InvalidFloat = _c::INVALID_FLOAT,
640    /// API call would result in a division by zero, so API ended early.
641    DivisionByZero = _c::DIVISION_BY_ZERO,
642    /// When attempting to create an XFL the mantissa must be 16 decimal digits.
643    MantissaOversized = _c::MANTISSA_OVERSIZED,
644    /// When attempting to create an XFL the mantissa must be 16 decimal digits.
645    MantissaUndersized = _c::MANTISSA_UNDERSIZED,
646    /// When attempting to create an XFL the exponent must not exceed 80.
647    ExponentOversized = _c::EXPONENT_OVERSIZED,
648    /// When attempting to create an XFL the exponent must not be less than -96.
649    ExponentUndersized = _c::EXPONENT_UNDERSIZED,
650    /// A floating point operation done on an XFL resulted in a value larger than XFL format is able to represent.
651    XflOverflow = _c::XFL_OVERFLOW,
652    /// An API assumed an STAmount was an IOU when in fact it was XRP.
653    NotIouAmount = _c::NOT_IOU_AMOUNT,
654    /// An API assumed an STObject was an STAmount when in fact it was not.
655    NotAnAmount = _c::NOT_AN_AMOUNT,
656    /// An API would have returned a negative integer except that negative integers are reserved for error codes (i.e. what you are reading.)
657    CantReturnNegative = _c::CANT_RETURN_NEGATIVE,
658    /// Hook attempted to set foreign state but was not authorized to do so (grant was missing or invalid.)
659    NotAuthorized = _c::NOT_AUTHORIZED,
660    /// Hook previously received a NOT_AUTHORIZED return code and is not allowed to retry.
661    PreviousFailurePreventsRetry = _c::PREVIOUS_FAILURE_PREVENTS_RETRY,
662    /// Attempted to set a hook parameter for a later hook in the chain, but there are now too many parameters.
663    TooManyParams = _c::TOO_MANY_PARAMS,
664    /// Serialized transaction was not a valid transaction (usually because of a missing required field or data corruption / truncation.)
665    InvalidTxn = _c::INVALID_TXN,
666    /// Setting an additional state object on this account would cause the reserve requirements to exceed the account's balance.
667    ReserveInssuficient = _c::RESERVE_INSUFFICIENT,
668    /// Hook API would be forced to return a complex number, which it cannot do.
669    ComplexNotSupported = _c::COMPLEX_NOT_SUPPORTED,
670    /// Two arguments were required to be of the same type but are not.
671    DoesNotMatch = _c::DOES_NOT_MATCH,
672    /// The provided public key was not valid.
673    InvalidKey = _c::INVALID_KEY,
674    /// The buffer did not contain a nul terminated string.
675    NotAString = _c::NOT_A_STRING,
676    /// The writing pointer points to a buffer that overlaps with the reading pointer.
677    MemOverlap = _c::MEM_OVERLAP,
678    /// More than 5000 modified state entries in the combined hook chains
679    TooManyStateModifications = _c::TOO_MANY_STATE_MODIFICATIONS,
680    /// More than 256 namespaces on this account
681    TooManyNamespaces = _c::TOO_MANY_NAMESPACES,
682}
683
684impl Error {
685    #[inline(always)]
686    fn from_code(code: i32) -> Self {
687        unsafe { core::mem::transmute(code) }
688    }
689
690    /// Error code
691    #[inline(always)]
692    pub fn code(self) -> i32 {
693        self as _
694    }
695}
696
697type Api1ArgsU32 = unsafe extern "C" fn(u32) -> i64;
698type Api2ArgsU32 = unsafe extern "C" fn(u32, u32) -> i64;
699type Api3ArgsU32 = unsafe extern "C" fn(u32, u32, u32) -> i64;
700type Api4ArgsU32 = unsafe extern "C" fn(u32, u32, u32, u32) -> i64;
701type Api6ArgsU32 = unsafe extern "C" fn(u32, u32, u32, u32, u32, u32) -> i64;
702
703type BufWriter = Api2ArgsU32;
704type BufReader = Api2ArgsU32;
705type Buf2Reader = Api4ArgsU32;
706type BufWriterReader = Api4ArgsU32;
707type Buf3Reader = Api6ArgsU32;
708type BufWriter1Arg = Api3ArgsU32;
709
710#[inline(always)]
711fn api_1arg_call(arg: u32, fun: Api1ArgsU32) -> Result<i64> {
712    let res = unsafe { fun(arg) };
713
714    result_i64(res)
715}
716
717#[inline(always)]
718fn api_3arg_call(arg_1: u32, arg_2: u32, arg_3: u32, fun: Api3ArgsU32) -> Result<i64> {
719    let res = unsafe { fun(arg_1, arg_2, arg_3) };
720
721    result_i64(res)
722}
723
724#[inline(always)]
725fn buf_write(buf_write: &mut [u8], fun: BufWriter) -> Result<i64> {
726    let res = unsafe { fun(buf_write.as_mut_ptr() as u32, buf_write.len() as u32) };
727
728    result_i64(res)
729}
730
731#[inline(always)]
732fn buf_write_1arg(buf_write: &mut [u8], arg: u32, fun: BufWriter1Arg) -> Result<i64> {
733    let res = unsafe { fun(buf_write.as_mut_ptr() as u32, buf_write.len() as u32, arg) };
734
735    result_i64(res)
736}
737
738#[inline(always)]
739fn buf_read(buf: &[u8], fun: BufReader) -> Result<i64> {
740    let res = unsafe { fun(buf.as_ptr() as u32, buf.len() as u32) };
741
742    result_i64(res)
743}
744
745#[inline(always)]
746fn buf_2read(buf_1: &[u8], buf_2: &[u8], fun: Buf2Reader) -> Result<i64> {
747    let res = unsafe {
748        fun(
749            buf_1.as_ptr() as u32,
750            buf_1.len() as u32,
751            buf_2.as_ptr() as u32,
752            buf_2.len() as u32,
753        )
754    };
755
756    result_i64(res)
757}
758
759#[inline(always)]
760fn buf_write_read(buf_write: &mut [u8], buf_read: &[u8], fun: BufWriterReader) -> Result<i64> {
761    let res = unsafe {
762        fun(
763            buf_write.as_mut_ptr() as u32,
764            buf_write.len() as u32,
765            buf_read.as_ptr() as u32,
766            buf_read.len() as u32,
767        )
768    };
769
770    result_i64(res)
771}
772
773#[inline(always)]
774fn buf_3_read(
775    buf_read_1: &[u8],
776    buf_read_2: &[u8],
777    buf_read_3: &[u8],
778    fun: Buf3Reader,
779) -> Result<i64> {
780    let res = unsafe {
781        fun(
782            buf_read_1.as_ptr() as u32,
783            buf_read_1.len() as u32,
784            buf_read_2.as_ptr() as u32,
785            buf_read_2.len() as u32,
786            buf_read_3.as_ptr() as u32,
787            buf_read_3.len() as u32,
788        )
789    };
790
791    result_i64(res)
792}
793
794#[inline(always)]
795fn range_from_location(location: i64) -> core::ops::Range<usize> {
796    let offset: i32 = (location >> 32) as _;
797    let lenght: i32 = (location & 0xFFFFFFFF) as _;
798
799    core::ops::Range {
800        start: offset as _,
801        end: (offset + lenght) as _,
802    }
803}
804
805#[inline(always)]
806fn all_zeroes(buf_write: &mut [u8], keylet_type_c: u32) -> Result<i64> {
807    let res = unsafe {
808        _c::util_keylet(
809            buf_write.as_mut_ptr() as _,
810            buf_write.len() as _,
811            keylet_type_c,
812            0,
813            0,
814            0,
815            0,
816            0,
817            0,
818        )
819    };
820
821    result_i64(res)
822}
823
824#[inline(always)]
825fn buf_read_and_zeroes(buf_write: &mut [u8], buf_read: &[u8], keylet_type_c: u32) -> Result<i64> {
826    let res = unsafe {
827        _c::util_keylet(
828            buf_write.as_mut_ptr() as _,
829            buf_write.len() as _,
830            keylet_type_c,
831            buf_read.as_ptr() as _,
832            buf_read.len() as _,
833            0,
834            0,
835            0,
836            0,
837        )
838    };
839
840    result_i64(res)
841}
842
843#[inline(always)]
844fn buf_read_and_1_arg(
845    buf_write: &mut [u8],
846    buf_read: &[u8],
847    arg: u32,
848    keylet_type_c: u32,
849) -> Result<i64> {
850    let res = unsafe {
851        _c::util_keylet(
852            buf_write.as_mut_ptr() as _,
853            buf_write.len() as _,
854            keylet_type_c,
855            buf_read.as_ptr() as _,
856            buf_read.len() as _,
857            arg,
858            0,
859            0,
860            0,
861        )
862    };
863
864    result_i64(res)
865}
866
867#[inline(always)]
868fn buf_read_and_2_args(
869    buf_write: &mut [u8],
870    buf_read: &[u8],
871    arg_1: u32,
872    arg_2: u32,
873    keylet_type_c: u32,
874) -> Result<i64> {
875    let res = unsafe {
876        _c::util_keylet(
877            buf_write.as_mut_ptr() as _,
878            buf_write.len() as _,
879            keylet_type_c,
880            buf_read.as_ptr() as _,
881            buf_read.len() as _,
882            arg_1,
883            arg_2,
884            0,
885            0,
886        )
887    };
888
889    result_i64(res)
890}
891
892#[inline(always)]
893fn buf_2_read_and_zeroes(
894    buf_write: &mut [u8],
895    buf_1_read: &[u8],
896    buf_2_read: &[u8],
897    keylet_type_c: u32,
898) -> Result<i64> {
899    let res = unsafe {
900        _c::util_keylet(
901            buf_write.as_mut_ptr() as _,
902            buf_write.len() as _,
903            keylet_type_c,
904            buf_1_read.as_ptr() as _,
905            buf_1_read.len() as _,
906            buf_2_read.as_ptr() as _,
907            buf_2_read.len() as _,
908            0,
909            0,
910        )
911    };
912
913    result_i64(res)
914}
915
916#[inline(always)]
917fn result_i64(res: i64) -> Result<i64> {
918    match res {
919        res if res >= 0 => Ok(res as _),
920        _ => Err(Error::from_code(res as _)),
921    }
922}
923
924#[inline(always)]
925fn result_xfl(res: i64) -> Result<XFL> {
926    match res {
927        res if res >= 0 => Ok(XFL(res)),
928        _ => Err(Error::from_code(res as _)),
929    }
930}