Giter Site home page Giter Site logo

transia-rnd / xrplcsharp Goto Github PK

View Code? Open in Web Editor NEW
13.0 1.0 6.0 97.04 MB

A C# library to interact with the XRP Ledger (XRPL) blockchain

License: Apache License 2.0

C# 97.76% JavaScript 1.91% CSS 0.31% Batchfile 0.02%
dotnet blockchain ledger cryptocurrency xrp xrp-ledger xrpl xrplf

xrplcsharp's Introduction

NuGet Badge

XrplCSharp

  • This library would not be possible without Chris Williams.

A pure C# implementation for interacting with the XRP Ledger, the XrplCSharp library simplifies the hardest parts of XRP Ledger interaction, like serialization and transaction signing, by providing native C# methods and models for XRP Ledger transactions and core server API (rippled) objects.

// create a network client
using System.Diagnostics;
using Xrpl.Client;
var client = new XrplClient("wss://s.altnet.rippletest.net:51233");
client.OnConnected += async () =>
{
    Debug.WriteLine("CONNECTED");
};
await client.Connect();

// create a wallet on the testnet
XrplWallet testWallet = XrplWallet.Generate();
await WalletSugar.FundWallet(client, testWallet);
Debug.WriteLine(testWallet);
// public_key: ED3CC1BBD0952A60088E89FA502921895FC81FBD79CAE9109A8FE2D23659AD5D56
// private_key: -HIDDEN -
// classic_address: rBtXmAdEYcno9LWRnAGfT9qBxCeDvuVRZo

// look up account info
//using System.Diagnostics;
//using Xrpl.Model.Account;
string account = "rBtXmAdEYcno9LWRnAGfT9qBxCeDvuVRZo";
AccountInfoRequest request = new AccountInfoRequest(account);
AccountInfo accountInfo = await client.AccountInfo(request);
Debug.WriteLine(accountInfo);
// {
//     "Account": "rBtXmAdEYcno9LWRnAGfT9qBxCeDvuVRZo",
//     "Balance": "1000000000",
//     "Flags": 0,
//     "LedgerEntryType": "AccountRoot",
//     "OwnerCount": 0,
//     "PreviousTxnID": "73CD4A37537A992270AAC8472F6681F44E400CBDE04EC8983C34B519F56AB107",
//     "PreviousTxnLgrSeq": 16233962,
//     "Sequence": 16233962,
//     "index": "FD66EC588B52712DCE74831DCB08B24157DC3198C29A0116AA64D310A58512D7"
// }

Installation and supported versions

The XrplCSharp library is available on DotNet. Install with dotnet:

dotnet add package XrplCSharp --version 1.0.0

The library supports Dotnet 6 and later.

Features

Use XrplCSharp to build C# applications that leverage the XRP Ledger. The library helps with all aspects of interacting with the XRP Ledger, including:

  • Key and wallet management
  • Serialization
  • Transaction Signing

XrplCSharp also provides:

  • A network client — See xrpl.clients for more information.
  • Methods for inspecting accounts — See XRPL Account Methods for more information.
  • Codecs for encoding and decoding addresses and other objects — See Core Codecs for more information.

See the complete XrplCSharp reference documentation on Read the Docs.

Usage

The following sections describe some of the most commonly used modules in the XrplCSharp library and provide sample code.

Network client

Use the Xrpl.Client library to create a network client for connecting to the XRP Ledger.

using System.Diagnostics;
using Xrpl.Client;
var client = new XrplClient("wss://s.altnet.rippletest.net:51233");
client.OnConnected += async () =>
{
    Debug.WriteLine("CONNECTED");
};
await client.Connect();

Manage keys and wallets

Xrpl.Wallet

Use the Xrpl.Wallet module to create a wallet from a given seed or or via a Testnet faucet.

To create a wallet from a seed (in this case, the value generated using Xrpl.Keypairs):

using System.Diagnostics;
using Xrpl.Wallet;
// ...
string seed = "s";
XrplWallet wallet = XrplWallet.FromSeed(seed);
Debug.WriteLine(wallet);
// pub_key: ED46949E414A3D6D758D347BAEC9340DC78F7397FEE893132AAF5D56E4D7DE77B0
// priv_key: -HIDDEN-
// classic_address: rG5ZvYsK5BPi9f1Nb8mhFGDTNMJhEhufn6

To create a wallet from a Testnet faucet:

using System.Diagnostics;
using Xrpl.Wallet;
XrplWallet testWallet = XrplWallet.Generate();
await WalletSugar.FundWallet(client, testWallet);
Debug.WriteLine(testWallet.ClassicAddress);
# Classic address: rEQB2hhp3rg7sHj6L8YyR4GG47Cb7pfcuw

Xrpl.Keypairs

Use the Xrpl.Keypairs module to generate seeds and derive keypairs and addresses from those seed values.

Here's an example of how to generate a seed value and derive an XRP Ledger "classic" address from that seed.

using System.Diagnostics;
using Xrpl.Wallet;
// ...
XrplWallet wallet = XrplWallet.Generate();
string publicKey = wallet.PublicKey;
string privateKey = wallet.PrivateKey;
Debug.WriteLine("Here's the public key:");
Debug.WriteLine(publicKey);
Debug.WriteLine("Here's the private key:");
Debug.WriteLine(privateKey);
Debug.WriteLine("Store this in a secure place!");
// Here's the public key:
// ED3CC1BBD0952A60088E89FA502921895FC81FBD79CAE9109A8FE2D23659AD5D56
// Here's the private key:
// EDE65EE7882847EF5345A43BFB8E6F5EEC60F45461696C384639B99B26AAA7A5CD
// Store this in a secure place!

Note: You can use Keypairs to sign transactions but XrplCSharp also provides explicit methods for safely signing and submitting transactions. See Transaction Signing and XRPL Transaction Methods for more information.

Serialize and sign transactions

To securely submit transactions to the XRP Ledger, you need to first serialize data from JSON and other formats into the XRP Ledger's canonical format, then to authorize the transaction by digitally signing it with the account's private key. The XrplCSharp library provides several methods to simplify this process.

Use the xrpl.transaction module to sign and submit transactions. The module offers three ways to do this:

using System.Diagnostics;
using Xrpl.Models.Transactions;
using Xrpl.Models.Methods;
using Newtonsoft.Json;
// ...
string classicAddress = "rBtXmAdEYcno9LWRnAGfT9qBxCeDvuVRZo";
AccountInfoRequest request = new AccountInfoRequest(wallet.ClassicAddress);
AccountInfo accountInfo = await client.AccountInfo(request);

// prepare the transaction
// the amount is expressed in drops, not XRP
// see https://xrpl.org/basic-data-types.html#specifying-currency-amounts
IPayment tx = new Payment()
{
    Account = wallet.ClassicAddress,
    Destination = "rEqtEHKbinqm18wQSQGstmqg9SFpUELasT",
    Amount = new Xrpl.Models.Common.Currency { ValueAsXrp = 1 },
    Sequence = accountInfo.AccountData.Sequence
};

// submit the transaction
Dictionary<string, dynamic> txJson = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(tx.ToJson());
Submit response = await client.Submit(txJson, wallet);
Debug.WriteLine(response);

Get fee from the XRP Ledger

In most cases, you can specify the minimum transaction cost of "10" for the fee field unless you have a strong reason not to. But if you want to get the current load-balanced transaction cost from the network, you can use the Fees function:

using System.Diagnostics;
using Xrpl.Models.Transactions;
FeeRequest feeRequest = new FeeRequest();
Fee fee = await client.Fee(feeRequest);
Debug.WriteLine(fee);
# 10

Contributing

If you want to contribute to this project, see CONTRIBUTING.md.

Mailing Lists

We have a low-traffic mailing list for announcements of new XrplCSharp releases. (About 1 email per week)

If you're using the XRP Ledger in production, you should run a rippled server and subscribe to the ripple-server mailing list as well.

License

The XrplCSharp library is licensed under the ISC License. See LICENSE for more information.

Repository Credit

The credit of this repository goes to Chris Williams.

https://github.com/chriswill

Thank you Chris.

xrplcsharp's People

Contributors

dangell7 avatar dominiqueblomsma avatar platonenkov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

xrplcsharp's Issues

Documentation

The repo needs to be documented. Every file in the repo also needs to, and likely already includes the link to the js repo that it has been ported from at the top of the file.

  • AddressCodec
  • BinaryCodec (IGNORE)
  • Keypairs (IGNORE the signing algorithms)
  • Xrpl/Client
  • Xrpl/Wallet
  • Generate into html

For functions that are not documented in the js repo please just tag with a TODO and continue. If you can create some documentation based on what you see, please tag it with REVIEW so I know that its not documentation from another xrpl sdk.

Ripple.Binary.Codec Error

occurs when trying to create an offer

Transaction is not valid. (Parameter 'tx')

Xrpl.Wallet.InvalidTxException: Transaction is not valid. (Parameter 'tx')
 ---> Ripple.Binary.Codec.Types.InvalidJsonException: Can't decode `TakerGets` from `0.82637`
 ---> System.FormatException: Input string was not in a correct format.
   at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
   at System.Int64.Parse(String s)
   at Ripple.Binary.Codec.Types.NativeValue..ctor(String value) in D:\_MainData\XRPL\xrpl.CSharp\Xrpl.C\Ripple.Binary.Codec\Types\AmountValue.cs:line 262
   at Ripple.Binary.Codec.Types.AmountValue.FromString(String value, Boolean native) in D:\_MainData\XRPL\xrpl.CSharp\Xrpl.C\Ripple.Binary.Codec\Types\AmountValue.cs:line 18
   at Ripple.Binary.Codec.Types.Amount..ctor(String v, Currency c, AccountId i) in D:\_MainData\XRPL\xrpl.CSharp\Xrpl.C\Ripple.Binary.Codec\Types\Amount.cs:line 30
   at Ripple.Binary.Codec.Types.Amount.FromJson(JToken token) in D:\_MainData\XRPL\xrpl.CSharp\Xrpl.C\Ripple.Binary.Codec\Types\Amount.cs:line 70
   at Ripple.Binary.Codec.Types.StObject.FromJson(JToken token, Boolean strict) in D:\_MainData\XRPL\xrpl.CSharp\Xrpl.C\Ripple.Binary.Codec\Types\StObject.cs:line 126
   --- End of inner exception stack trace ---
   at Ripple.Binary.Codec.Types.StObject.FromJson(JToken token, Boolean strict) in D:\_MainData\XRPL\xrpl.CSharp\Xrpl.C\Ripple.Binary.Codec\Types\StObject.cs:line 133
   at Xrpl.Wallet.TxSigner.SignJson(JObject tx) in D:\_MainData\XRPL\xrpl.CSharp\Xrpl.C\Xrpl\Wallet\TxSigner.cs:line 39
   --- End of inner exception stack trace ---
   at Xrpl.Wallet.TxSigner.SignJson(JObject tx) in D:\_MainData\XRPL\xrpl.CSharp\Xrpl.C\Xrpl\Wallet\TxSigner.cs:line 42

I think that the Error is related to culture, but I cannot figure out what is happening here
image
https://github.com/Transia-RnD/xrpl.c/blob/main/Xrpl.C/Ripple.Binary.Codec/Types/Amount.cs

I need your help

Currency with code more than 3 characters

In case the user requests data for a coin with a code of more than 3 characters - we need a reverse converter, until I know where to put it, there are ideas?

        /// <summary>
        /// check currency code for HEX 
        /// </summary>
        /// <param name="code">currency code</param>
        /// <returns></returns>
        public static bool IsHexCurrencyCode(this string code) => Regex.IsMatch(code, @"[0-9a-fA-F]{40}", RegexOptions.IgnoreCase);

        /// <summary>
        /// checks and generates a token code for transmission to the network
        /// </summary>
        /// <param name="CurrencyCode">Currency code</param>
        /// <returns></returns>
        /// <exception cref="ArgumentException">If Currency code length more than 40 characters</exception>
        public static string XrplCurrencyValidCode(this string CurrencyCode)
        {
            var cur_code = CurrencyCode.Trim();
            if (cur_code.Length <= 3)
                return cur_code;

            if (cur_code.IsHexCurrencyCode())
                return cur_code;

            cur_code = cur_code.ToHex();
            if (cur_code.Length > 40)
                throw new ArgumentException($"CurrencyCode can be 40 character maximum\nCode: {cur_code}", nameof(CurrencyCode));

            cur_code += new string('0', 40 - cur_code.Length);

            return cur_code;
        }

Offers error

Qualitymust be double in the Offers
image

or it will be error
image

And if Offers called without Limit - it will Invalid_parameter
image

find me please in telegram @Platonenkov, I wath to help

Update README

Go through the README and update changes for release of v2.

Rename Repository and clean namespaces

We need to rename the repository in v2. I'm open to suggestions. Currently the repo/solution name is XRPL.C. This isn't correct for C# so the namespace becomes xrpl_c. I then renamed the namespace to Xrpl. Its very messy.

Discussion:

The other repos are xrpl.js, xrpl-py, XRPLSwift, and XRPL.C

So maybe XrplC without the period or XrplCSharp?

Tasks:

  • Rename Repository
  • Clean Namespaces
  • Clean cproj file

Refactor Client

The client is currently 1 file, in JS its 3 or 4 files. Subscriptions also needs to be refactored into its respective place to match xrpl.js

MissingMethodException

I'm trying to sign a transaction but the EncodeForSigning method can't be found (I can see it in the object explorer)

System.MissingMethodException
HResult=0x80131513
Message=Method not found: 'System.String Xrpl.BinaryCodec.XrplBinaryCodec.EncodeForSigning(System.Collections.Generic.Dictionary2<System.String,System.Object>)'. Source=Xrpl StackTrace: at Xrpl.Wallet.XrplWallet.ComputeSignature(Dictionary2 transaction, String privateKey, String signAs)
at Xrpl.Wallet.XrplWallet.Sign(Dictionary`2 transaction, Boolean multisign, String signingFor)
at Xrpl.Sugar.SubmitSugar.d__2.MoveNext()
at Xrpl.Sugar.SubmitSugar.d__0.MoveNext()

Any advice of how to solve?
Or anybody else having this issue?

JsonSerializationException

Newtonsoft.Json.JsonSerializationException: "Error converting value "Ticket" to type 'xrpl_c.Xrpl.Client.Model.Enums.LedgerEntryType'. Path 'transactions[61].meta.AffectedNodes[4].DeletedNode.LedgerEntryType', line 12005, position 41."

image

            var account = "rKpHiZ2y4MnvAqK2PeFeLC9k1NydJYy9TZ";
            var server = "wss://xrplcluster.com/";

time to time I have this message from server Error.txt.txt

urls starting with "http[s]" not accepted (and seems are not validated)

Hi

I was testing the client and noticed after some trials that server urls will work only with "wss", not http/https, seems the code that validates them will return true no matter the string is passed to the client constructor, am I understanding wrong ? or is expected the wss url validation be performed by the dev ?


        public bool IsValidWss(string server)
        {
            return true;
        }

I used "http" instead of "wss" because I was actually reading an example from the python library, but later noticed that detail on the .NET sample, got me confused because the client was not throwing any error/result

Thank you, didnt know a .NET libreary for the XRPL was already available, I'm just poking around with it.

send non-XRP coin (Question)

help figure it out, in the test network I send the coin FOO rPdDuRCGHLkMM7jSzo93CAjtniYiLEjBnL
and I get an error
image

json
image
can't understand

Format Documentation Index

The documentation needs to be formatted so that the main repos are hi-lighted. With the classes, enum, errors, extensions nested under the main category.

  • Address Codec
  • Binary Codec
  • Keypairs
  • Xrpl

Client doesn't connect

I cloned this library to use in conjunction with a very simple .NET 6 console app to start experimenting with the ledger, but the websocket implementation doesn't work for me. Maybe I'm doing something wrong?

Specifically, I am injecting the IXrplClient class into my NetworkService class wrapper using standard DI via constructor. Then I call the connect method in the class' GetAccountInfo method, all good. And then I follow the connection flow through IXrplClient => connection => WebSocketClient.cs. The code fails inside the ConnectAsync method of WebSocketClient.cs.

I debugged into the decompiled ClientWebSocket class to the ConnectAsync method and it seems the code freezes in this method:
public Task ConnectAsync(Uri uri, CancellationToken cancellationToken) { if (uri == (Uri) null) throw new ArgumentNullException(nameof (uri)); if (!uri.IsAbsoluteUri) throw new ArgumentException(SR.net_uri_NotAbsolute, nameof (uri)); if (uri.Scheme != "ws" && uri.Scheme != "wss") throw new ArgumentException(SR.net_WebSockets_Scheme, nameof (uri)); switch ((ClientWebSocket.InternalState) Interlocked.CompareExchange(ref this._state, 1, 0)) { case ClientWebSocket.InternalState.Created: this.Options.SetToReadOnly(); return this.ConnectAsyncCore(uri, cancellationToken); case ClientWebSocket.InternalState.Disposed: throw new ObjectDisposedException(this.GetType().FullName); default: throw new InvalidOperationException(SR.net_WebSockets_AlreadyStarted); } }

The method freezes when we hit the switch statement, nothing happens, and eventually (after about 30 seconds or so) we get a NotConnectedException thrown.

I'm pretty sure I've got everything configured correctly, I register the client in my Program.cs like so:
services.AddSingleton<IXrplClient>(provider => { var uri = "wss://s.altnet.rippletest.net:51233"; return new XrplClient(uri); });

Not sure what I'm doing wrong here, any feedback would be appreciated.

CurrencyCode long name

CurrencyCode with a name greater than 3 characters is passed in hex format, but after conversion, you still need to remove empty characters

as sample:
784249424C780000000000000000000000000000 = xBiblx

delete trustline Question

Help me please, how to delete trustline?
I found this note:

To remove a trust line, reset it to its default state. (0 limit, 0 balance, and no non-default settings.)

what is non-default settings ?

now I use this request:

 var accountInfo = await Client.AccountInfo(AccountSender);

            ITrustSetTransaction trustSet = new TrustSetTransaction()
            {
                Account = AccountSender,
                Flags = TrustSetFlags.tfSetNoRipple,
                TransactionType = TransactionType.TrustSet,
                LimitAmount = new Currency { Value = "0", Issuer = Issuer, CurrencyCode = CurrencyCode },
                Sequence = accountInfo.AccountData.Sequence,
            };

But it not work

Meta is not returned in the TransactionCommonResponse

If I create a new token using Submit result = await xls20client.SubmitTransactionBlob(request); the meta data isnt included in the result.

result.Transaction.Meta is null. There are also other fields that are coming in as null.

  • Parse the Tx response correctly and include ALL the data.
  • Write a function that gets the NFT token ID
def get_token_id(meta: dict) -> str:
    return meta['AffectedNodes'][-1]['ModifiedNode']['FinalFields']['NonFungibleTokens'][-1]['NonFungibleToken']['TokenID']

Refactor Binary

  • #65
  • Binary Codec - The binary codec does not match xrpl.js therefore the testing is not complete. Must rewrite the Binary Codec to match EXACTLY what xrpl.js/py has.

Transaction Validation

The transactions in the js/py library include a validation function.

See here for example

We need to add this validation to every transaction.

  1. Write the validation file for the transaction
  2. Connect the validation function to the transaction validation. Main Validation is here
  • Find or Create the base transaction validation function. JS Ex: here
  • Add all validation functions to the transactions in Xrpl.Models.Transactions
  • Add the individual tx validation function to the main transaction validation.
  • Update the transaction validation to match the validation in js. (Little refactor as there are 2 functions that js does that we are missing)

JS

Transaction Validation Main Function:

https://github.com/XRPLF/xrpl.js/blob/984a58e642a4cde09aee320efe195d4e651b7733/packages/xrpl/src/models/transactions/transaction.ts#L99

TrustSet Validation Function:

https://github.com/XRPLF/xrpl.js/blob/main/packages/xrpl/src/models/transactions/trustSet.ts#L127

Sync with XRPLF

** All xrpl libraries need to be E2E synergy.

Client: https://github.com/XRPLF/xrpl.js
Address + Binary Codec: https://github.com/XRPLF/xrpl-py

  • Solution
    -- Address Codec
    -- Binary Codec
    -- Keypairs
    -- Xrpl
    -- -- Client
    -- -- Wallet
    -- -- Sugar
    -- -- Models
    -- -- Utils

  • Docs: All I did was change from xrpl-py to xrpl.c and the new documentation needs to be generated. This will likely case a few files to be moved around to find their place. README, CONTRIBUTING needs to be finished.

  • Test: There are 69 tests. They need to be refactored into integration and unit tests. See XRPLF libraries.

  • Unity & Metaverse: They only use LTS and being so I could not use net5.0. Unity current version is v4.7. xrpl.c is current version netstandard2.0. Do we add a different. release?

  • CI/CD: Generate API key and setup pipeline?

Add ParseNFTID code

Since the NFTID is scrambled, I'd like to add the code that already exists for the JS and Python libraries for parsing the serial of an nft

Missing Functionality

There is missing functionality in the XrplCSharp Library. All the files are created with a link to the JS repo that needs to be ported from.

  • Sugars - There are a few sugars that xrpl.js implements but XrplCSharp has not
  • Utils - Functions like NFTID and Payment Channel helpers.

Hex memo decode method

decoding Memo messages goes with incorrect encoding.

your basic method:
image

after adaptation:
image

        /// <summary> Memo string With smiles </summary>
        public static string MemoHexWithSmyles(string hex)
        {
            var buffer = new byte[hex.Length / 2];
            for (int i = 0; i < hex.Length; i += 2)
            {
                string hexdec = hex.Substring(i, 2);
                buffer[i / 2] = byte.Parse(hexdec, NumberStyles.HexNumber);
            }
            return Encoding.UTF8.GetString(buffer);//we could even have passed this encoding in for greater flexibility.
        }

Transaction hash as a sample
8A51DDDD11CA13F2A370EDDB1B3B66DAB195B42FD1ABA6B613A08729C07ECB5F

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.