diff --git a/.dart_tool/extension_discovery/vs_code.json b/.dart_tool/extension_discovery/vs_code.json index 6fbc25c..37a8299 100644 --- a/.dart_tool/extension_discovery/vs_code.json +++ b/.dart_tool/extension_discovery/vs_code.json @@ -1 +1 @@ -{"version":2,"entries":[{"package":"blockchain_utils","rootUri":"../../bitcoin/blockchain_utils/","packageUri":"lib/"},{"package":"xrpl_dart","rootUri":"../","packageUri":"lib/"}]} \ No newline at end of file +{"version":2,"entries":[{"package":"xrpl_dart","rootUri":"../","packageUri":"lib/"}]} \ No newline at end of file diff --git a/.dart_tool/pub/bin/test/test.dart-3.3.3.snapshot b/.dart_tool/pub/bin/test/test.dart-3.3.3.snapshot new file mode 100644 index 0000000..4679f5a Binary files /dev/null and b/.dart_tool/pub/bin/test/test.dart-3.3.3.snapshot differ diff --git a/.dart_tool/test/incremental_kernel.Ly9AZGFydD0yLjE1 b/.dart_tool/test/incremental_kernel.Ly9AZGFydD0yLjE1 index cad9a18..ef1a93b 100644 Binary files a/.dart_tool/test/incremental_kernel.Ly9AZGFydD0yLjE1 and b/.dart_tool/test/incremental_kernel.Ly9AZGFydD0yLjE1 differ diff --git a/example/lib/examples/amm/amm_bid.dart b/example/lib/examples/amm/amm_bid.dart index 15c01b6..2842b0f 100644 --- a/example/lib/examples/amm/amm_bid.dart +++ b/example/lib/examples/amm/amm_bid.dart @@ -38,7 +38,7 @@ Future _ammBitWithAuthAccount(QuickWallet wallet, XRPCurrencies assets, {CurrencyAmount? bidMin, CurrencyAmount? bidMax}) async { final transaction = AMMBid( account: wallet.address, - signingPubKey: wallet.pubHex, + signer: XRPLSignature.signer(wallet.pubHex), asset: assets, asset2: assets2, memos: [exampleMemo], @@ -64,7 +64,7 @@ Future _ammBid( QuickWallet wallet, XRPCurrencies assets, XRPCurrencies assets2) async { final transaction = AMMBid( account: wallet.address, - signingPubKey: wallet.pubHex, + signer: XRPLSignature.signer(wallet.pubHex), asset: assets, asset2: assets2, memos: [exampleMemo]); diff --git a/example/lib/examples/amm/amm_create.dart b/example/lib/examples/amm/amm_create.dart index 3fd8e03..c80dfb8 100644 --- a/example/lib/examples/amm/amm_create.dart +++ b/example/lib/examples/amm/amm_create.dart @@ -16,7 +16,7 @@ void ammCreate() async { Future accountSet(QuickWallet wallet) async { final transaction = AccountSet( account: wallet.address, - signingPubKey: wallet.pubHex, + signer: XRPLSignature.signer(wallet.pubHex), setFlag: AccountSetAsfFlag.asfDefaultRipple, memos: [exampleMemo]); await XRPHelper.autoFill(wallet.rpc, transaction); @@ -37,7 +37,7 @@ Future accountSet(QuickWallet wallet) async { Future trustSet(QuickWallet wallet, String issuer) async { final transaction = TrustSet( account: wallet.address, - signingPubKey: wallet.pubHex, + signer: XRPLSignature.signer(wallet.pubHex), flags: TrustSetFlag.tfClearNoRipple.value, limitAmount: IssuedCurrencyAmount(value: "1000", currency: "USD", issuer: issuer), @@ -61,7 +61,7 @@ Future payment( QuickWallet wallet, String issuer, String destionation) async { final transaction = Payment( account: wallet.address, - signingPubKey: wallet.pubHex, + signer: XRPLSignature.signer(wallet.pubHex), flags: TrustSetFlag.tfClearNoRipple.value, destination: destionation, amount: CurrencyAmount.issue( @@ -86,7 +86,7 @@ Future _ammCreate(QuickWallet wallet, String issuer, {String currencyCode = "USD"}) async { final transaction = AMMCreate( account: wallet.address, - signingPubKey: wallet.pubHex, + signer: XRPLSignature.signer(wallet.pubHex), tradingFee: 12, amount: CurrencyAmount.xrp(BigInt.from(250)), amount2: CurrencyAmount.issue(IssuedCurrencyAmount( diff --git a/example/lib/examples/amm/amm_vote.dart b/example/lib/examples/amm/amm_vote.dart index 739583a..5ba7d3b 100644 --- a/example/lib/examples/amm/amm_vote.dart +++ b/example/lib/examples/amm/amm_vote.dart @@ -21,7 +21,7 @@ Future _ammVote(QuickWallet wallet, XRPCurrencies assets, XRPCurrencies assets2, int tradingFee) async { final transaction = AMMVote( account: wallet.address, - signingPubKey: wallet.pubHex, + signer: XRPLSignature.signer(wallet.pubHex), tradingFee: tradingFee, asset: assets, asset2: assets2, diff --git a/example/lib/examples/check/check_example.dart b/example/lib/examples/check/check_example.dart index 25bb1fb..2774fef 100644 --- a/example/lib/examples/check/check_example.dart +++ b/example/lib/examples/check/check_example.dart @@ -33,7 +33,7 @@ Future checkCreate( sendMax: sendMax, destination: destination, account: account.address, - signingPubKey: account.pubHex, + signer: XRPLSignature.signer(account.pubHex), memos: [exampleMemo], ); print("autfil trnsction"); @@ -64,7 +64,7 @@ Future cancelCheck(QuickWallet account) async { final transaction = CheckCancel( account: account.address, - signingPubKey: account.pubHex, + signer: XRPLSignature.signer(account.pubHex), checkId: checkIndex, memos: [exampleMemo], ); @@ -100,7 +100,7 @@ Future chechCash(QuickWallet destination, final String checkIndex = checkInfo["account_objects"][0]["index"]; final transction = CheckCash( account: destination.address, - signingPubKey: destination.pubHex, + signer: XRPLSignature.signer(destination.pubHex), amount: amount, checkId: checkIndex, memos: [exampleMemo], diff --git a/example/lib/examples/delete_account/delete_account_example.dart b/example/lib/examples/delete_account/delete_account_example.dart index 956de3a..32994c1 100644 --- a/example/lib/examples/delete_account/delete_account_example.dart +++ b/example/lib/examples/delete_account/delete_account_example.dart @@ -14,10 +14,11 @@ void deleteAccountExample() async { Future deleteAccount(QuickWallet account, String destionation) async { final transaction = AccountDelete( - account: account.address, - memos: [exampleMemo], - destination: destionation, - signingPubKey: account.pubHex); + account: account.address, + memos: [exampleMemo], + destination: destionation, + signer: XRPLSignature.signer(account.pubHex), + ); await XRPHelper.autoFill(account.rpc, transaction); final blob = transaction.toBlob(); diff --git a/example/lib/examples/deposit_pre_auth/deposit_pre_auth_example.dart b/example/lib/examples/deposit_pre_auth/deposit_pre_auth_example.dart index 8c430f4..75c4906 100644 --- a/example/lib/examples/deposit_pre_auth/deposit_pre_auth_example.dart +++ b/example/lib/examples/deposit_pre_auth/deposit_pre_auth_example.dart @@ -14,10 +14,11 @@ void depositePreAuth() async { Future authorize(QuickWallet account, String autorize) async { final transaction = DepositPreauth( - account: account.address, - authorize: autorize, - memos: [exampleMemo], - signingPubKey: account.pubHex); + account: account.address, + authorize: autorize, + memos: [exampleMemo], + signer: XRPLSignature.signer(account.pubHex), + ); await XRPHelper.autoFill(account.rpc, transaction); final blob = transaction.toBlob(); @@ -42,10 +43,11 @@ Future authorize(QuickWallet account, String autorize) async { Future unauthorize(QuickWallet account, String autorize) async { final transaction = DepositPreauth( - account: account.address, - unauthorize: autorize, - memos: [exampleMemo], - signingPubKey: account.pubHex); + account: account.address, + unauthorize: autorize, + memos: [exampleMemo], + signer: XRPLSignature.signer(account.pubHex), + ); await XRPHelper.autoFill(account.rpc, transaction); final blob = transaction.toBlob(); diff --git a/example/lib/examples/did/did_delete.dart b/example/lib/examples/did/did_delete.dart index f071ea6..d186f5e 100644 --- a/example/lib/examples/did/did_delete.dart +++ b/example/lib/examples/did/did_delete.dart @@ -8,7 +8,7 @@ void didDelete() async { final transaction = DIDDelete( account: masterWallet.address, - signingPubKey: masterWallet.pubHex, + signer: XRPLSignature.signer(masterWallet.pubHex), memos: [exampleMemo]); await XRPHelper.autoFill(masterWallet.rpc, transaction); final blob = transaction.toBlob(); diff --git a/example/lib/examples/did/did_set.dart b/example/lib/examples/did/did_set.dart index d73fbff..63b7412 100644 --- a/example/lib/examples/did/did_set.dart +++ b/example/lib/examples/did/did_set.dart @@ -9,7 +9,7 @@ void didset() async { final transaction = DIDSet( account: masterWallet.address, - signingPubKey: masterWallet.pubHex, + signer: XRPLSignature.signer(masterWallet.pubHex), didDocument: validField, data: validField, uri: validField, diff --git a/example/lib/examples/escrow/escrow.dart b/example/lib/examples/escrow/escrow.dart index 5419194..197bf80 100644 --- a/example/lib/examples/escrow/escrow.dart +++ b/example/lib/examples/escrow/escrow.dart @@ -30,7 +30,7 @@ Future escrowCreate(QuickWallet owner, String destination, finishAfterTime: finishAfterOneHours, amount: XRPHelper.xrpDecimalToDrop("1200"), condition: condition, - signingPubKey: owner.pubHex, + signer: XRPLSignature.signer(owner.pubHex), memos: [exampleMemo], ); print("autfil trnsction"); @@ -64,7 +64,7 @@ Future finisScrow(QuickWallet destination, String owner, account: destination.address, condition: condition, fulfillment: fulfillment, - signingPubKey: destination.pubHex, + signer: XRPLSignature.signer(destination.pubHex), owner: owner, memos: [exampleMemo], ); @@ -97,7 +97,7 @@ Future cancelScrow(QuickWallet owner) async { owner: owner.address, offerSequence: 2500937, // sequance of create escrow transaction account: owner.address, - signingPubKey: owner.pubHex, + signer: XRPLSignature.signer(owner.pubHex), memos: [exampleMemo], ); print("autfil trnsction"); diff --git a/example/lib/examples/multisig/multisig.dart b/example/lib/examples/multisig/multisig.dart index 82e86a1..a6da529 100644 --- a/example/lib/examples/multisig/multisig.dart +++ b/example/lib/examples/multisig/multisig.dart @@ -85,7 +85,7 @@ Future createOrUpdateMultiSIgAccount( signerEntries: signers, account: masterWallet.address, signerQuorum: threshold, - signingPubKey: masterWallet.pubHex, + signer: XRPLSignature.signer(masterWallet.pubHex), memos: [exampleMemo]); print("autofill trnsction"); await XRPHelper.autoFill(masterWallet.rpc, transaction); @@ -112,7 +112,7 @@ Future createOrUpdateMultiSIgAccount( Future disableMaster(QuickWallet masterWallet) async { final transaction = AccountSet( account: masterWallet.address, - signingPubKey: masterWallet.pubHex, + signer: XRPLSignature.signer(masterWallet.pubHex), setFlag: AccountSetAsfFlag.asfDisableMaster, memos: [exampleMemo]); await XRPHelper.autoFill(masterWallet.rpc, transaction); @@ -139,19 +139,24 @@ Future disableMaster(QuickWallet masterWallet) async { Future sendXRPLUsingMultiSig(QuickWallet masaterWallet, String destination, List signersList, int signerQuorum) async { final transaction = Payment( - destination: destination, - multiSigSigners: signersList.map((e) => e.address).toList(), - account: masaterWallet.address, - memos: [exampleMemo], - amount: CurrencyAmount.xrp(XRPHelper.xrpDecimalToDrop("50")), - signingPubKey: ''); // do not set signingPubKey for multisig transaction + destination: destination, + multisigSigners: signersList + .map((e) => + XRPLSigners.singer(account: e.address, signingPubKey: e.pubHex)) + .toList(), + account: masaterWallet.address, + memos: [exampleMemo], + amount: CurrencyAmount.xrp(XRPHelper.xrpDecimalToDrop("50")), + ); // do not set signingPubKey for multisig transaction await XRPHelper.autoFill(masaterWallet.rpc, transaction); final List signerSignatures = []; for (final i in signersList) { final blob = transaction.toMultisigBlob(i.address); final sig = i.privateKey.sign(blob); signerSignatures.add(XRPLSigners( - account: i.address, signingPubKey: i.pubHex, txnSignature: sig)); + account: i.address, + signingPubKey: i.pubHex, + txnSignature: sig.signature)); } transaction.setMultiSigSignature(signerSignatures); @@ -172,9 +177,11 @@ Future enableMaster( QuickWallet masterWallet, List signersList) async { final transaction = AccountSet( account: masterWallet.address, - signingPubKey: "", clearFlag: AccountSetAsfFlag.asfDisableMaster, - multiSigSigners: signersList.map((e) => e.address).toList(), + multisigSigners: signersList + .map((e) => + XRPLSigners.singer(account: e.address, signingPubKey: e.pubHex)) + .toList(), memos: [exampleMemo]); print("autofill trnsction"); await XRPHelper.autoFill(masterWallet.rpc, transaction); @@ -183,7 +190,9 @@ Future enableMaster( final blob = transaction.toMultisigBlob(i.address); final sig = i.privateKey.sign(blob); signerSignatures.add(XRPLSigners( - account: i.address, signingPubKey: i.pubHex, txnSignature: sig)); + account: i.address, + signingPubKey: i.pubHex, + txnSignature: sig.signature)); } transaction.setMultiSigSignature(signerSignatures); diff --git a/example/lib/examples/nft/nft.dart b/example/lib/examples/nft/nft.dart index de768eb..8c1ba9b 100644 --- a/example/lib/examples/nft/nft.dart +++ b/example/lib/examples/nft/nft.dart @@ -65,7 +65,7 @@ Future mintToken(QuickWallet wallet) async { uri: BytesUtils.toHexString( StringUtils.encode("https://github.com/mrtnetwork/xrpl_dart")), account: wallet.address, - signingPubKey: wallet.pubHex, + signer: XRPLSignature.signer(wallet.pubHex), memos: [exampleMemo], nftokenTaxon: 1); print("autfil trnsction"); @@ -103,7 +103,7 @@ Future burnToken(QuickWallet wallet) async { final transaction = NFTokenBurn( nfTokenId: tokenId, account: wallet.address, - signingPubKey: wallet.pubHex, + signer: XRPLSignature.signer(wallet.pubHex), memos: [exampleMemo], ); print("autfil trnsction"); @@ -141,7 +141,7 @@ Future createOffgerForNftWithToken( flags: NftTokenCreateOfferFlag.tfSellNftoken.value, nftokenId: tokenId, account: wallet.address, - signingPubKey: wallet.pubHex, + signer: XRPLSignature.signer(wallet.pubHex), memos: [exampleMemo], ); print("autfil trnsction"); @@ -170,7 +170,7 @@ Future nftTokenAcceptOffer(QuickWallet buyer, String offerID) async { final offer = NFTokenAcceptOffer( nfTokenSellOffer: offerID, account: buyer.address, - signingPubKey: buyer.pubHex, + signer: XRPLSignature.signer(buyer.pubHex), memos: [exampleMemo], ); print("autfil trnsction"); @@ -200,7 +200,7 @@ Future nfTokenCancelOffer( final offer = NFTokenCancelOffer( nftokenOffers: offerIdsToCancel, account: minter.address, - signingPubKey: minter.pubHex, + signer: XRPLSignature.signer(minter.pubHex), memos: [exampleMemo], ); print("autfil trnsction"); diff --git a/example/lib/examples/offer/offer_example.dart b/example/lib/examples/offer/offer_example.dart index 3732ba2..6c5087c 100644 --- a/example/lib/examples/offer/offer_example.dart +++ b/example/lib/examples/offer/offer_example.dart @@ -13,16 +13,17 @@ void offerExamples() async { Future createOffer(QuickWallet account, String issueAddress) async { final trustLine = OfferCreate( - account: account.address, - takerGets: CurrencyAmount.xrp( - XRPHelper.xrpDecimalToDrop("25"), - ), - takerPays: CurrencyAmount.issue( - IssuedCurrencyAmount( - value: "10.2", currency: "MRT", issuer: issueAddress), - ), - memos: [exampleMemo], - signingPubKey: account.pubHex); + account: account.address, + takerGets: CurrencyAmount.xrp( + XRPHelper.xrpDecimalToDrop("25"), + ), + takerPays: CurrencyAmount.issue( + IssuedCurrencyAmount( + value: "10.2", currency: "MRT", issuer: issueAddress), + ), + memos: [exampleMemo], + signer: XRPLSignature.signer(account.pubHex), + ); await XRPHelper.autoFill(account.rpc, trustLine); final blob = trustLine.toBlob(); @@ -53,7 +54,7 @@ Future offerCancel(QuickWallet account) async { final transaction = OfferCancel( account: account.address, offerSequence: offerSequence, - signingPubKey: account.pubHex, + signer: XRPLSignature.signer(account.pubHex), memos: [exampleMemo], ); await XRPHelper.autoFill(account.rpc, transaction); diff --git a/example/lib/examples/payment/payment.dart b/example/lib/examples/payment/payment.dart index dc8c054..2819e18 100644 --- a/example/lib/examples/payment/payment.dart +++ b/example/lib/examples/payment/payment.dart @@ -18,7 +18,7 @@ Future simplePaymentEdward() async { amount: CurrencyAmount.xrp(XRPHelper.xrpDecimalToDrop("125.75")), destination: destination.address, account: account.address, - signingPubKey: account.pubHex, + signer: XRPLSignature.signer(account.pubHex), memos: [exampleMemo]); await XRPHelper.autoFill(account.rpc, transaction); final blob = transaction.toBlob(); @@ -50,7 +50,7 @@ Future simplePaymentSecp256() async { amount: CurrencyAmount.xrp(XRPHelper.xrpDecimalToDrop("125.75")), destination: destination.address, account: account.address, - signingPubKey: account.pubHex, + signer: XRPLSignature.signer(account.pubHex), memos: [exampleMemo]); await XRPHelper.autoFill(account.rpc, transaction); final blob = transaction.toBlob(); @@ -83,7 +83,7 @@ Future exampleWithWebScoket() async { amount: CurrencyAmount.xrp(XRPHelper.xrpDecimalToDrop("125.75")), destination: destination.address, account: account.address, - signingPubKey: account.pubHex, + signer: XRPLSignature.signer(account.pubHex), memos: [exampleMemo]); final socketRpc = await XRPLRpc.devNet((httpUri, websocketUri) async { return await RPCWebSocketService.connect(websocketUri); diff --git a/example/lib/examples/quick_wallet/quick_wallet.dart b/example/lib/examples/quick_wallet/quick_wallet.dart index 8722ead..cc1d734 100644 --- a/example/lib/examples/quick_wallet/quick_wallet.dart +++ b/example/lib/examples/quick_wallet/quick_wallet.dart @@ -23,7 +23,7 @@ class QuickWallet { "wallet created $address\n${privateKey.toHex()}\n$pubHex\n===================================="); } factory QuickWallet.create(int index, - {int account = 2, + {int account = 0, XRPLRpc? rpc, XRPKeyAlgorithm algorithm = XRPKeyAlgorithm.secp256k1}) { final entropy = Bip39SeedGenerator(Mnemonic.fromString( @@ -46,8 +46,8 @@ class QuickWallet { String get xAddress => publicKey.toAddress().toXAddress(forTestnet: true); String get pubHex => publicKey.toHex(); final XRPLRpc rpc; - Future fucent() async { - final resp = await rpc.getFucent(address); + Future fucent({String? addr}) async { + final resp = await rpc.getFucent(addr ?? address); print(resp); } } diff --git a/example/lib/examples/regular_key/example_regular_key.dart b/example/lib/examples/regular_key/example_regular_key.dart index 34b171e..87f0529 100644 --- a/example/lib/examples/regular_key/example_regular_key.dart +++ b/example/lib/examples/regular_key/example_regular_key.dart @@ -32,7 +32,7 @@ Future setupOrUpdateReqularKey( QuickWallet masterWallet, String? reqularWalletAddress) async { final transaction = SetRegularKey( account: masterWallet.address, - signingPubKey: masterWallet.pubHex, + signer: XRPLSignature.signer(masterWallet.pubHex), regularKey: reqularWalletAddress, memos: [exampleMemo]); print("autfil trnsction"); @@ -60,7 +60,7 @@ Future setupOrUpdateReqularKey( Future disableMaster(QuickWallet masterWallet) async { final transaction = AccountSet( account: masterWallet.address, - signingPubKey: masterWallet.pubHex, + signer: XRPLSignature.signer(masterWallet.pubHex), setFlag: AccountSetAsfFlag.asfDisableMaster, memos: [exampleMemo]); await XRPHelper.autoFill(masterWallet.rpc, transaction); @@ -90,7 +90,7 @@ Future sendXrpWithRegularKey( amount: CurrencyAmount.xrp(XRPHelper.xrpDecimalToDrop("170.009")), destination: destination, account: wallet.address, - signingPubKey: reqularWallet.pubHex, + signer: XRPLSignature.signer(reqularWallet.pubHex), memos: [exampleMemo]); await XRPHelper.autoFill(wallet.rpc, transaction); final blob = transaction.toBlob(); @@ -118,7 +118,7 @@ Future enableMasterFromRegularKey( QuickWallet masterWallet, QuickWallet regularWallet) async { final transaction = AccountSet( account: masterWallet.address, - signingPubKey: regularWallet.pubHex, + signer: XRPLSignature.signer(regularWallet.pubHex), clearFlag: AccountSetAsfFlag.asfDisableMaster, memos: [exampleMemo]); await XRPHelper.autoFill(masterWallet.rpc, transaction); diff --git a/example/lib/examples/ticket/ticket_example.dart b/example/lib/examples/ticket/ticket_example.dart index 3651fc1..8add58d 100644 --- a/example/lib/examples/ticket/ticket_example.dart +++ b/example/lib/examples/ticket/ticket_example.dart @@ -17,7 +17,7 @@ Future createTicket(QuickWallet account) async { final ticket = TicketCreate( ticketCount: 2, account: account.address, - signingPubKey: account.pubHex, + signer: XRPLSignature.signer(account.pubHex), memos: [exampleMemo]); print("autfill trnsction"); await XRPHelper.autoFill(account.rpc, ticket); @@ -51,7 +51,7 @@ Future sendXRPUsingTicket(QuickWallet account, String destination) async { amount: CurrencyAmount.xrp(XRPHelper.xrpDecimalToDrop("1")), destination: destination, account: account.address, - signingPubKey: account.pubHex, + signer: XRPLSignature.signer(account.pubHex), /// set ticket sequence ticketSequance: ticketSequence, diff --git a/example/lib/examples/token_issue_transfer/issue.dart b/example/lib/examples/token_issue_transfer/issue.dart index 3a734a5..cf4f26a 100644 --- a/example/lib/examples/token_issue_transfer/issue.dart +++ b/example/lib/examples/token_issue_transfer/issue.dart @@ -28,7 +28,7 @@ void tokenIssueAndTransfer() async { Future configureAccount(QuickWallet hotWallet) async { final accountSet = AccountSet( account: hotWallet.address, - signingPubKey: hotWallet.pubHex, + signer: XRPLSignature.signer(hotWallet.pubHex), memos: [exampleMemo], setFlag: AccountSetAsfFlag.asfRequireAuth); print("autfil trnsction"); @@ -59,7 +59,7 @@ Future configureAccount(QuickWallet hotWallet) async { Future configureIssue(QuickWallet coldWallet) async { final accountSet = AccountSet( account: coldWallet.address, - signingPubKey: coldWallet.pubHex, + signer: XRPLSignature.signer(coldWallet.pubHex), memos: [exampleMemo], setFlag: AccountSetAsfFlag.asfDefaultRipple, domain: BytesUtils.toHexString( @@ -92,7 +92,7 @@ Future configureIssue(QuickWallet coldWallet) async { Future createTrustSet(QuickWallet account, String issueAddress) async { final trustLine = TrustSet( account: account.address, - signingPubKey: account.pubHex, + signer: XRPLSignature.signer(account.pubHex), limitAmount: IssuedCurrencyAmount( value: "10000000000", currency: "MRT", issuer: issueAddress), memos: [exampleMemo], @@ -124,7 +124,7 @@ Future sendToken( final sendToken = Payment( destination: destination, account: account.address, - signingPubKey: account.pubHex, + signer: XRPLSignature.signer(account.pubHex), memos: [exampleMemo], amount: CurrencyAmount.issue(IssuedCurrencyAmount( value: "80.585677899", currency: "MRT", issuer: issueAddress)), diff --git a/example/lib/examples/with_destination_source_tag/tag_example.dart b/example/lib/examples/with_destination_source_tag/tag_example.dart index 409dad8..33a2d6b 100644 --- a/example/lib/examples/with_destination_source_tag/tag_example.dart +++ b/example/lib/examples/with_destination_source_tag/tag_example.dart @@ -17,10 +17,11 @@ void tagExamples() async { Future setupRequiredDestinationTag(QuickWallet account) async { final transaction = AccountSet( - setFlag: AccountSetAsfFlag.asfRequireDest, - account: account.address, - memos: [exampleMemo], - signingPubKey: account.pubHex); + setFlag: AccountSetAsfFlag.asfRequireDest, + account: account.address, + memos: [exampleMemo], + signer: XRPLSignature.signer(account.pubHex), + ); await XRPHelper.autoFill(account.rpc, transaction); final blob = transaction.toBlob(); // return; @@ -53,7 +54,7 @@ Future sendPaymentToDestinationRequiredTag( destination: destinationXAddress, destinationTag: tag, account: account.address, - signingPubKey: account.pubHex, + signer: XRPLSignature.signer(account.pubHex), memos: [exampleMemo]); await XRPHelper.autoFill(account.rpc, transaction); final blob = transaction.toBlob(); @@ -84,7 +85,7 @@ Future sendFromSourceTag( sourceTag: tag, account: XRPAddress(account.address).toXAddress(forTestnet: true, tag: tag), - signingPubKey: account.pubHex, + signer: XRPLSignature.signer(account.pubHex), memos: [exampleMemo]); await XRPHelper.autoFill(account.rpc, transaction); final blob = transaction.toBlob(); diff --git a/example/lib/examples/xchain/add_claim_attestation.dart b/example/lib/examples/xchain/add_claim_attestation.dart index 765fdf7..43d3753 100644 --- a/example/lib/examples/xchain/add_claim_attestation.dart +++ b/example/lib/examples/xchain/add_claim_attestation.dart @@ -22,7 +22,7 @@ void xChainAddClaimAttestation() async { Future createBridge(QuickWallet account, XChainBridge bridge) async { final transaction = XChainCreateBridge( - signingPubKey: account.pubHex, + signer: XRPLSignature.signer(account.pubHex), memos: [exampleMemo], account: account.address, xchainBridge: bridge, @@ -48,7 +48,7 @@ Future createClaimId(QuickWallet account, XChainBridge bridge) async { final otherChainSourceWallet = QuickWallet.create(105, account: 100); final transaction = XChainCreateClaimId( - signingPubKey: account.pubHex, + signer: XRPLSignature.signer(account.pubHex), memos: [exampleMemo], account: account.address, xchainBridge: bridge, @@ -72,7 +72,7 @@ Future createClaimId(QuickWallet account, XChainBridge bridge) async { Future wintessSignerList( QuickWallet account, QuickWallet witnessWallet) async { final transaction = SignerListSet( - signingPubKey: account.pubHex, + signer: XRPLSignature.signer(account.pubHex), memos: [exampleMemo], account: account.address, signerEntries: [ @@ -104,7 +104,7 @@ Future addClaimAttestation() async { issuingChainIssue: XRP(), lockingChainIssue: XRP()); final transaction = XChainCreateBridge( - signingPubKey: doorWallet.pubHex, + signer: XRPLSignature.signer(doorWallet.pubHex), account: doorWallet.address, xchainBridge: bridge, memos: [exampleMemo], @@ -128,8 +128,8 @@ Future addClaimAttestation() async { xchainBridge: bridge, xchainClaimId: 1, destination: desctinationWallet.address, - signingPubKey: witnessWallet.pubHex, - signature: sign, + signer: XRPLSignature.signer(witnessWallet.pubHex), + signature: sign.signature!, otherChainSource: otherChainSourceWallet.address, publicKey: witnessWallet.pubHex, wasLockingChainSend: false, diff --git a/example/lib/examples/xchain/add_create_account_attestation.dart b/example/lib/examples/xchain/add_create_account_attestation.dart index b8dd8c4..fd1a653 100644 --- a/example/lib/examples/xchain/add_create_account_attestation.dart +++ b/example/lib/examples/xchain/add_create_account_attestation.dart @@ -23,7 +23,7 @@ void xChainAddAccountCreateAttestation() async { Future createBridge(QuickWallet account, XChainBridge bridge) async { final transaction = XChainCreateBridge( - signingPubKey: account.pubHex, + signer: XRPLSignature.signer(account.pubHex), memos: [exampleMemo], account: account.address, xchainBridge: bridge, @@ -48,7 +48,7 @@ Future createBridge(QuickWallet account, XChainBridge bridge) async { Future createClaimId(QuickWallet account, XChainBridge bridge) async { final otherChainSourceWallet = QuickWallet.create(105); final transaction = XChainCreateClaimId( - signingPubKey: account.pubHex, + signer: XRPLSignature.signer(account.pubHex), memos: [exampleMemo], account: account.address, xchainBridge: bridge, @@ -72,7 +72,7 @@ Future createClaimId(QuickWallet account, XChainBridge bridge) async { Future wintessSignerList( QuickWallet account, QuickWallet witnessWallet) async { final transaction = SignerListSet( - signingPubKey: account.pubHex, + signer: XRPLSignature.signer(account.pubHex), memos: [exampleMemo], account: account.address, signerEntries: [ @@ -104,7 +104,7 @@ Future addAccountCreateAttestation() async { issuingChainIssue: XRP(), lockingChainIssue: XRP()); final transaction = XChainCreateBridge( - signingPubKey: doorWallet.pubHex, + signer: XRPLSignature.signer(doorWallet.pubHex), account: doorWallet.address, xchainBridge: bridge, signatureReward: BigInt.from(200), @@ -136,8 +136,8 @@ Future addAccountCreateAttestation() async { signatureReward: BigInt.from(200), xChainAccountCreateCount: bridgeCount, destination: desctinationWallet.address, - signingPubKey: witnessWallet.pubHex, - signature: sign, + signer: XRPLSignature.signer(witnessWallet.pubHex), + signature: sign.signature!, otherChainSource: otherChainSourceWallet.address, publicKey: witnessWallet.pubHex, wasLockingChainSend: false, diff --git a/example/lib/examples/xchain/create_claim_id.dart b/example/lib/examples/xchain/create_claim_id.dart index c224253..f6a97b2 100644 --- a/example/lib/examples/xchain/create_claim_id.dart +++ b/example/lib/examples/xchain/create_claim_id.dart @@ -16,7 +16,7 @@ void xChainCreateClaimId() async { signatureReward: BigInt.from(2000), account: wallet1.address, otherChainSource: wallet2.address, - signingPubKey: wallet1.pubHex, + signer: XRPLSignature.signer(wallet1.pubHex), memos: [exampleMemo], ); diff --git a/example/lib/examples/xchain/create_commit.dart b/example/lib/examples/xchain/create_commit.dart index a074238..322e6c3 100644 --- a/example/lib/examples/xchain/create_commit.dart +++ b/example/lib/examples/xchain/create_commit.dart @@ -17,7 +17,7 @@ void xChainAccountCreateCommit() async { lockingChainIssue: XRP()); final transaction = XChainAccountCreateCommit( account: masterWallet.address, - signingPubKey: masterWallet.pubHex, + signer: XRPLSignature.signer(masterWallet.pubHex), xchainBridge: bridge, destination: desctinationWallet.address, amount: XRPHelper.xrpDecimalToDrop("10"), diff --git a/example/lib/examples/xchain/xchain_commit.dart b/example/lib/examples/xchain/xchain_commit.dart index 584ddec..c54f7a4 100644 --- a/example/lib/examples/xchain/xchain_commit.dart +++ b/example/lib/examples/xchain/xchain_commit.dart @@ -13,7 +13,7 @@ void xChainCommit() async { lockingChainDoor: wallet1.address, lockingChainIssue: XRP()), account: wallet2.address, - signingPubKey: wallet2.pubHex, + signer: XRPLSignature.signer(wallet2.pubHex), amount: XRPHelper.xrpDecimalToDrop("1"), memos: [exampleMemo], xchainClaimId: 1); diff --git a/example/lib/examples/xchain/xchain_create_bridge.dart b/example/lib/examples/xchain/xchain_create_bridge.dart index b49e07d..92abc3e 100644 --- a/example/lib/examples/xchain/xchain_create_bridge.dart +++ b/example/lib/examples/xchain/xchain_create_bridge.dart @@ -10,7 +10,7 @@ void xChainBridge() async { account: wallet.address, signatureReward: BigInt.from(2000), minAccountCreateAmount: XRPHelper.xrpDecimalToDrop("10"), - signingPubKey: wallet.pubHex, + signer: XRPLSignature.signer(wallet.pubHex), memos: [exampleMemo], xchainBridge: XChainBridge( issuingChainDoor: "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", diff --git a/example/lib/examples/xchain/xchain_modify_bridge.dart b/example/lib/examples/xchain/xchain_modify_bridge.dart index 51dd2b6..61a052f 100644 --- a/example/lib/examples/xchain/xchain_modify_bridge.dart +++ b/example/lib/examples/xchain/xchain_modify_bridge.dart @@ -14,7 +14,7 @@ void xChainModifyBridge() async { lockingChainIssue: XRP()), signatureReward: BigInt.from(400), account: wallet.address, - signingPubKey: wallet.pubHex, + signer: XRPLSignature.signer(wallet.pubHex), minAccountCreateAmount: XRPHelper.xrpDecimalToDrop("10"), memos: [exampleMemo], ); diff --git a/lib/src/crypto/crypto.dart b/lib/src/crypto/crypto.dart new file mode 100644 index 0000000..161bc36 --- /dev/null +++ b/lib/src/crypto/crypto.dart @@ -0,0 +1,3 @@ +export 'keypair/xrpl_private_key.dart'; +export 'keypair/xrpl_public_key.dart'; +export 'signature/signature.dart'; diff --git a/lib/src/keypair/xrpl_private_key.dart b/lib/src/crypto/keypair/xrpl_private_key.dart similarity index 90% rename from lib/src/keypair/xrpl_private_key.dart rename to lib/src/crypto/keypair/xrpl_private_key.dart index 9800fb2..479be23 100644 --- a/lib/src/keypair/xrpl_private_key.dart +++ b/lib/src/crypto/keypair/xrpl_private_key.dart @@ -1,5 +1,6 @@ import 'package:blockchain_utils/blockchain_utils.dart'; import 'package:xrpl_dart/src/xrpl/exception/exceptions.dart'; +import '../signature/signature.dart'; import 'xrpl_public_key.dart'; /// Enum representing different XRP key algorithms. @@ -28,6 +29,9 @@ class XrpKeyConst { static const List ed255PrivateKeyPrefix = [0xed]; static const List secpPrivateKey = [0x00]; static const int privateKeyWithPrefix = 33; + static const List _secp256k1SeedMidBytes = [0, 0, 0, 0]; + static const String _ed25519KeyHexPrefix = "ED"; + static const String _secp2561KeyHexPrefix = "00"; } class XrpSeedUtils { @@ -54,7 +58,8 @@ class XrpSeedUtils { final newPubPoint = Curves.generatorSecp256k1 * root; // Calculate the intermediate value using the new public point. - final BigInt mid = _getSecret(newPubPoint.toBytes(), isMid: true); + final BigInt mid = _getSecret(newPubPoint.toBytes(), + seedMidBytes: XrpKeyConst._secp256k1SeedMidBytes); // Calculate the final key pair value by combining the root and intermediate values. final BigInt finalPair = (root + mid) % order; @@ -67,7 +72,8 @@ class XrpSeedUtils { /// /// This method takes the given data as input and iteratively calculates a secret value. /// It then returns the calculated secret as a BigInt. - static BigInt _getSecret(List data, {bool isMid = false}) { + static BigInt _getSecret(List data, + {List seedMidBytes = const []}) { const int sqSize = 4; final BigInt sqMax = BigInt.from(256) << (sqSize * 8); final BigInt bigMask8 = BigInt.from(mask8); @@ -78,22 +84,17 @@ class XrpSeedUtils { for (int i = 0; i < sqSize; i++) { root[i] = ((rawRoot >> (8 * (sqSize - 1 - i))) & bigMask8).toInt(); } - List combine; - if (isMid) { - combine = List.from([ - ...data, - ...[0, 0, 0, 0], - ...root - ]); - } else { - combine = [...data, ...root]; - } + final List combine = + List.from([...data, ...seedMidBytes, ...root]); final hash = QuickCrypto.sha512Hash(combine).sublist(0, 32); if (Secp256k1PrivateKeyEcdsa.isValidBytes(hash)) { return BigintUtils.fromBytes(hash); } } - throw ArgumentError("error"); + + /// does not happened + throw const XRPLAddressCodecException( + "cannot dervice secrent key from provided value."); } /// Prefix used for seed values in key pair derivation. @@ -204,9 +205,11 @@ class XRPPrivateKey { /// Factory constructor for generating a random XRP private key. /// [algorithm] specifies the cryptographic algorithm, with ED25519 being the default. factory XRPPrivateKey.random( - {XRPKeyAlgorithm algorithm = XRPKeyAlgorithm.ed25519}) { + {XRPKeyAlgorithm algorithm = XRPKeyAlgorithm.ed25519, + GenerateRandom? randomGenerator}) { /// Generate 16 random bytes as entropy - final rand = QuickCrypto.generateRandom(16); + final rand = + QuickCrypto.generateRandom(XrpSeedUtils.seedLength, randomGenerator); /// Create an XRP private key from the generated entropy return XRPPrivateKey.fromEntropy(BytesUtils.toHexString(rand), @@ -281,8 +284,8 @@ class XRPPrivateKey { return XRPKeyAlgorithm.ed25519; } } - throw ArgumentError( - "cannot find key algorithm please check algorithm argrument"); + throw const XRPLAddressCodecException( + "cannot find key algorithm. incorrect key length."); } /// Converts the given [keyBytes] to an instance of IPrivateKey based on the provided XRP key [algorithm]. @@ -303,7 +306,7 @@ class XRPPrivateKey { final toPrive = IPrivateKey.fromBytes(keyBytes, algorithm.curveType); return toPrive; } catch (e) { - throw ArgumentError("Invalid private key"); + throw XRPLAddressCodecException("Invalid private key"); } } @@ -313,10 +316,11 @@ class XRPPrivateKey { /// Signs the given [message] using the private key and returns the signature as a hexadecimal string. /// /// [message] is the message to be signed. - String sign(String message) { + XRPLSignature sign(String message) { final signer = XrpSigner.fromKeyBytes(toBytes(), algorithm.curveType); - final sign = signer.sign(BytesUtils.fromHexString(message)); - return BytesUtils.toHexString(sign); + final signature = signer.sign(BytesUtils.fromHexString(message)); + return XRPLSignature.sign( + getPublic().toHex(), BytesUtils.toHexString(signature)); } /// Returns the private key as a bytes. @@ -326,13 +330,16 @@ class XRPPrivateKey { /// Returns the private key as a hexadecimal string with the appropriate prefix based on the algorithm. String toHex() { - String toString = BytesUtils.toHexString(toBytes(), lowerCase: false); + return _keyPrefixInHex + + BytesUtils.toHexString(toBytes(), lowerCase: false); + } + String get _keyPrefixInHex { switch (algorithm) { case XRPKeyAlgorithm.ed25519: - return "ED$toString"; + return XrpKeyConst._ed25519KeyHexPrefix; default: - return "00$toString"; + return XrpKeyConst._secp2561KeyHexPrefix; } } diff --git a/lib/src/keypair/xrpl_public_key.dart b/lib/src/crypto/keypair/xrpl_public_key.dart similarity index 93% rename from lib/src/keypair/xrpl_public_key.dart rename to lib/src/crypto/keypair/xrpl_public_key.dart index 532793a..cfae0c0 100644 --- a/lib/src/keypair/xrpl_public_key.dart +++ b/lib/src/crypto/keypair/xrpl_public_key.dart @@ -1,6 +1,7 @@ import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; import 'package:blockchain_utils/blockchain_utils.dart'; import 'package:xrpl_dart/src/xrpl/address/xrpl.dart'; +import 'package:xrpl_dart/src/xrpl/exception/exceptions.dart'; import 'xrpl_private_key.dart'; @@ -36,7 +37,7 @@ class XRPPublicKey { } } - throw ArgumentError( + throw XRPLAddressCodecException( "invalid public key. public key length must be ${RippleKeyConst.publicKeyLength} bytes"); } @@ -49,7 +50,7 @@ class XRPPublicKey { } return IPublicKey.fromBytes(keyBytes, algorithm.curveType); } catch (e) { - throw ArgumentError("invalid public key"); + throw XRPLAddressCodecException("invalid public key"); } } @@ -71,7 +72,7 @@ class XRPPublicKey { /// Returns the public key as a list of bytes based on the specified [mode]. /// /// This method converts the public key to a list of bytes based on the provided [mode], - /// which defaults to [PubKeyMode.compressed] if not specified. It performs different + /// which defaults to [PubKeyModes.compressed] if not specified. It performs different /// operations based on the algorithm's curve type and the specified mode, and returns /// the resulting bytes representing the public key. /// diff --git a/lib/src/crypto/signature/signature.dart b/lib/src/crypto/signature/signature.dart new file mode 100644 index 0000000..a4d98dd --- /dev/null +++ b/lib/src/crypto/signature/signature.dart @@ -0,0 +1,29 @@ +class XRPLSignature { + XRPLSignature._({required this.signature, required this.signingPubKey}); + factory XRPLSignature.signer(String signingPubKey) { + return XRPLSignature._(signature: null, signingPubKey: signingPubKey); + } + factory XRPLSignature.sign(String signingPubKey, String txnSignature) { + return XRPLSignature._( + signature: txnSignature.isEmpty ? null : txnSignature, + signingPubKey: signingPubKey); + } + static XRPLSignature? fromJson(Map json) { + final String? signingPubKey = json["signing_pub_key"]; + final String txnSignature = json["txn_signature"] ?? ""; + if (signingPubKey?.isEmpty ?? true) { + return null; + } + return XRPLSignature._( + signature: (txnSignature.isEmpty ? null : txnSignature), + signingPubKey: signingPubKey!); + } + + /// [signature] The signature that this Signer provided for this transaction. + final String? signature; + + /// [signingPubKey] The public key that should be used to verify this Signer's signature. + final String signingPubKey; + + bool get isReady => signature != null; +} diff --git a/lib/src/number/number_parser.dart b/lib/src/number/number_parser.dart deleted file mode 100644 index aebc00c..0000000 --- a/lib/src/number/number_parser.dart +++ /dev/null @@ -1,33 +0,0 @@ -import 'dart:core'; - -/// Parse a dynamic value into an integer if possible, or return null if not. -int? parseInt(dynamic value) { - if (value is String) { - try { - return int.parse(value); - } catch (_) { - /// Parsing failed, return null. - return null; - } - } else if (value is int) { - return value; - } - return null; -} - -/// Parse a dynamic value into a BigInt if possible, or return null if not. -BigInt? parseBigInt(dynamic value) { - if (value is String) { - try { - return BigInt.parse(value); - } catch (_) { - /// Parsing failed, return null. - return null; - } - } else if (value is BigInt) { - return value; - } else if (value is int) { - return BigInt.from(value); - } - return null; -} diff --git a/lib/src/rpc/on_chain_models/account_info.dart b/lib/src/rpc/on_chain_models/account_info.dart index 275af68..1313a44 100644 --- a/lib/src/rpc/on_chain_models/account_info.dart +++ b/lib/src/rpc/on_chain_models/account_info.dart @@ -1,4 +1,4 @@ -import 'package:xrpl_dart/src/number/number_parser.dart'; +import 'package:blockchain_utils/numbers/int_utils.dart'; class AccountInfo { final AccountData accountData; @@ -19,7 +19,7 @@ class AccountInfo { return AccountInfo( accountData: AccountData.fromJson(json['account_data']), accountFlags: AccountFlags.fromJson(json['account_flags']), - ledgerCurrentIndex: parseInt(json['ledger_current_index']), + ledgerCurrentIndex: IntUtils.tryParse(json['ledger_current_index']), status: json['status'], validated: json['validated'], ); @@ -55,12 +55,12 @@ class AccountData { return AccountData( account: json['Account'], balance: json['Balance'], - flags: parseInt(json['Flags'])!, + flags: IntUtils.tryParse(json['Flags'])!, ledgerEntryType: json['LedgerEntryType'], - ownerCount: parseInt(json['OwnerCount'])!, + ownerCount: IntUtils.tryParse(json['OwnerCount'])!, previousTxnID: json['PreviousTxnID'], - previousTxnLgrSeq: parseInt(json['PreviousTxnLgrSeq'])!, - sequence: parseInt(json['Sequence'])!, + previousTxnLgrSeq: IntUtils.tryParse(json['PreviousTxnLgrSeq'])!, + sequence: IntUtils.tryParse(json['Sequence'])!, index: json['index'], regularKey: json["RegularKey"]); } diff --git a/lib/src/rpc/on_chain_models/ledger.dart b/lib/src/rpc/on_chain_models/ledger.dart index 4e865ee..66381f9 100644 --- a/lib/src/rpc/on_chain_models/ledger.dart +++ b/lib/src/rpc/on_chain_models/ledger.dart @@ -1,6 +1,4 @@ -// ignore_for_file: constant_identifier_names - -import 'package:xrpl_dart/src/number/number_parser.dart'; +import 'package:blockchain_utils/numbers/numbers.dart'; import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; import 'on_chain_transaction.dart'; @@ -163,17 +161,19 @@ class LedgerData { factory LedgerData.fromJson(Map json) { return LedgerData( accountHash: json['ledger']['account_hash'], - closeFlags: parseInt(json['ledger']['close_flags'])!, - closeTime: parseInt(json['ledger']['close_time'])!, + closeFlags: IntUtils.tryParse(json['ledger']['close_flags'])!, + closeTime: IntUtils.tryParse(json['ledger']['close_time'])!, closeTimeHuman: json['ledger']['close_time_human'], - closeTimeResolution: parseInt(json['ledger']['close_time_resolution'])!, + closeTimeResolution: + IntUtils.tryParse(json['ledger']['close_time_resolution'])!, closed: json['ledger']['closed'], ledgerHash: json['ledger']['ledger_hash'], - ledgerIndex: parseInt(json['ledger']['ledger_index'])!, - parentCloseTime: parseInt(json['ledger']['parent_close_time'])!, + ledgerIndex: IntUtils.tryParse(json['ledger']['ledger_index'])!, + parentCloseTime: + IntUtils.tryParse(json['ledger']['parent_close_time'])!, parentHash: json['ledger']['parent_hash'], - seqNum: parseInt(json['ledger']['seqNum']), - totalCoins: parseBigInt(json['ledger']['total_coins'])!, + seqNum: IntUtils.tryParse(json['ledger']['seqNum']), + totalCoins: BigintUtils.tryParse(json['ledger']['total_coins'])!, transactionHash: json['ledger']['transaction_hash'], transactions: (json['ledger']["transactions"] as List?) ?.map((e) => TransactionData.fromJson(e)) diff --git a/lib/src/rpc/on_chain_models/ledger_info.dart b/lib/src/rpc/on_chain_models/ledger_info.dart index 8acd959..4f9246f 100644 --- a/lib/src/rpc/on_chain_models/ledger_info.dart +++ b/lib/src/rpc/on_chain_models/ledger_info.dart @@ -1,6 +1,5 @@ import 'dart:math' as math; - -import 'package:xrpl_dart/src/number/number_parser.dart'; +import 'package:blockchain_utils/numbers/numbers.dart'; enum XrplFeeType { open, minimum, dynamic } @@ -76,13 +75,13 @@ class LedgerInfo { factory LedgerInfo.fromJson(Map json) { return LedgerInfo( - currentLedgerSize: parseInt(json['current_ledger_size'])!, - currentQueueSize: parseInt(json['current_queue_size'])!, + currentLedgerSize: IntUtils.tryParse(json['current_ledger_size'])!, + currentQueueSize: IntUtils.tryParse(json['current_queue_size'])!, drops: Drops.fromJson(json['drops'] ?? {}), - expectedLedgerSize: parseInt(json['expected_ledger_size'])!, - ledgerCurrentIndex: parseInt(json['ledger_current_index'])!, + expectedLedgerSize: IntUtils.tryParse(json['expected_ledger_size'])!, + ledgerCurrentIndex: IntUtils.tryParse(json['ledger_current_index'])!, levels: Levels.fromJson(json['levels'] ?? {}), - maxQueueSize: parseInt(json['max_queue_size'])!, + maxQueueSize: IntUtils.tryParse(json['max_queue_size'])!, status: json['status'] ?? 'unknown', ); } @@ -103,10 +102,10 @@ class Drops { factory Drops.fromJson(Map json) { return Drops( - baseFee: parseInt(json['base_fee'])!, - medianFee: parseInt(json['median_fee'])!, - minimumFee: parseInt(json['minimum_fee'])!, - openLedgerFee: parseInt(json['open_ledger_fee'])!, + baseFee: IntUtils.tryParse(json['base_fee'])!, + medianFee: IntUtils.tryParse(json['median_fee'])!, + minimumFee: IntUtils.tryParse(json['minimum_fee'])!, + openLedgerFee: IntUtils.tryParse(json['open_ledger_fee'])!, ); } } @@ -126,10 +125,10 @@ class Levels { factory Levels.fromJson(Map json) { return Levels( - medianLevel: parseInt(json['median_level'])!, - minimumLevel: parseInt(json['minimum_level'])!, - openLedgerLevel: parseInt(json['open_ledger_level'])!, - referenceLevel: parseInt(json['reference_level'])!, + medianLevel: IntUtils.tryParse(json['median_level'])!, + minimumLevel: IntUtils.tryParse(json['minimum_level'])!, + openLedgerLevel: IntUtils.tryParse(json['open_ledger_level'])!, + referenceLevel: IntUtils.tryParse(json['reference_level'])!, ); } } diff --git a/lib/src/rpc/on_chain_models/on_chain_transaction.dart b/lib/src/rpc/on_chain_models/on_chain_transaction.dart index d44b06b..dd5f95d 100644 --- a/lib/src/rpc/on_chain_models/on_chain_transaction.dart +++ b/lib/src/rpc/on_chain_models/on_chain_transaction.dart @@ -1,4 +1,4 @@ -import 'package:xrpl_dart/src/number/number_parser.dart'; +import 'package:blockchain_utils/numbers/numbers.dart'; class TransactionData { final String account; @@ -28,10 +28,10 @@ class TransactionData { factory TransactionData.fromJson(Map json) { return TransactionData( account: json['Account'], - fee: parseInt(json['Fee'])!, - flags: parseInt(json['Flags'])!, - offerSequence: parseInt(json['OfferSequence']), - sequence: parseInt(json['Sequence'])!, + fee: IntUtils.tryParse(json['Fee'])!, + flags: IntUtils.tryParse(json['Flags'])!, + offerSequence: IntUtils.tryParse(json['OfferSequence']), + sequence: IntUtils.tryParse(json['Sequence'])!, signingPubKey: json['SigningPubKey'], transactionType: json['TransactionType'], txnSignature: json['TxnSignature'], diff --git a/lib/src/rpc/on_chain_models/server_info.dart b/lib/src/rpc/on_chain_models/server_info.dart index 4a84c9c..478f0e5 100644 --- a/lib/src/rpc/on_chain_models/server_info.dart +++ b/lib/src/rpc/on_chain_models/server_info.dart @@ -1,4 +1,4 @@ -import 'package:xrpl_dart/src/number/number_parser.dart'; +import 'package:blockchain_utils/numbers/numbers.dart'; class ServerInfo { final Info info; @@ -67,23 +67,26 @@ class Info { buildVersion: json['build_version'], completeLedgers: json['complete_ledgers'], hostId: json['hostid'], - initialSyncDurationUs: parseInt(json['initial_sync_duration_us'])!, - ioLatencyMs: parseInt(json['io_latency_ms'])!, - jqTransOverflow: parseInt(json['jq_trans_overflow'])!, + initialSyncDurationUs: + IntUtils.tryParse(json['initial_sync_duration_us'])!, + ioLatencyMs: IntUtils.tryParse(json['io_latency_ms'])!, + jqTransOverflow: IntUtils.tryParse(json['jq_trans_overflow'])!, lastClose: LastClose.fromJson(json['last_close']), - loadFactor: parseInt(json['load_factor'])!, - networkId: parseInt(json['network_id']), - peerDisconnects: parseInt(json['peer_disconnects'])!, - peerDisconnectsResources: parseInt(json['peer_disconnects_resources'])!, - peers: parseInt(json['peers'])!, + loadFactor: IntUtils.tryParse(json['load_factor'])!, + networkId: IntUtils.tryParse(json['network_id']), + peerDisconnects: IntUtils.tryParse(json['peer_disconnects'])!, + peerDisconnectsResources: + IntUtils.tryParse(json['peer_disconnects_resources'])!, + peers: IntUtils.tryParse(json['peers'])!, pubkeyNode: json['pubkey_node'], serverState: json['server_state'], - serverStateDurationUs: parseInt(json['server_state_duration_us'])!, + serverStateDurationUs: + IntUtils.tryParse(json['server_state_duration_us'])!, stateAccounting: StateAccounting.fromJson(json['state_accounting']), time: json['time'], - uptime: parseInt(json['uptime'])!, + uptime: IntUtils.tryParse(json['uptime'])!, validatedLedger: ValidatedLedger.fromJson(json['validated_ledger']), - validationQuorum: parseInt(json['validation_quorum'])!, + validationQuorum: IntUtils.tryParse(json['validation_quorum'])!, ); } } @@ -99,8 +102,8 @@ class LastClose { factory LastClose.fromJson(Map json) { return LastClose( - convergeTimeS: parseInt(json['converge_time_s']), - proposers: parseInt(json['proposers']), + convergeTimeS: IntUtils.tryParse(json['converge_time_s']), + proposers: IntUtils.tryParse(json['proposers']), ); } } @@ -142,8 +145,8 @@ class AccountingDuration { factory AccountingDuration.fromJson(Map json) { return AccountingDuration( - durationUs: parseInt(json['duration_us'])!, - transitions: parseInt(json['transitions'])!, + durationUs: IntUtils.tryParse(json['duration_us'])!, + transitions: IntUtils.tryParse(json['transitions'])!, ); } } @@ -167,12 +170,12 @@ class ValidatedLedger { factory ValidatedLedger.fromJson(Map json) { return ValidatedLedger( - age: parseInt(json['age'])!, + age: IntUtils.tryParse(json['age'])!, baseFeeXrp: json['base_fee_xrp'], hash: json['hash'], - reserveBaseXrp: parseInt(json['reserve_base_xrp'])!, - reserveIncXrp: parseInt(json['reserve_inc_xrp'])!, - seq: parseInt(json['seq'])!, + reserveBaseXrp: IntUtils.tryParse(json['reserve_base_xrp'])!, + reserveIncXrp: IntUtils.tryParse(json['reserve_inc_xrp'])!, + seq: IntUtils.tryParse(json['seq'])!, ); } } diff --git a/lib/src/rpc/on_chain_models/server_state.dart b/lib/src/rpc/on_chain_models/server_state.dart index be191ef..d2fa4b8 100644 --- a/lib/src/rpc/on_chain_models/server_state.dart +++ b/lib/src/rpc/on_chain_models/server_state.dart @@ -1,4 +1,4 @@ -import 'package:xrpl_dart/src/number/number_parser.dart'; +import 'package:blockchain_utils/numbers/numbers.dart'; class XRPLedgerState { final XRPLedgerStateDetails state; @@ -73,28 +73,31 @@ class XRPLedgerStateDetails { return XRPLedgerStateDetails( buildVersion: json['build_version'], completeLedgers: json['complete_ledgers'], - initialSyncDurationUs: parseInt(json['initial_sync_duration_us']) ?? 0, - ioLatencyMs: parseInt(json['io_latency_ms']) ?? 0, - jqTransOverflow: parseInt(json['jq_trans_overflow']) ?? 0, + initialSyncDurationUs: + IntUtils.tryParse(json['initial_sync_duration_us']) ?? 0, + ioLatencyMs: IntUtils.tryParse(json['io_latency_ms']) ?? 0, + jqTransOverflow: IntUtils.tryParse(json['jq_trans_overflow']) ?? 0, lastClose: XRPLastClose.fromJson(json['last_close']), - loadBase: parseInt(json['load_base']) ?? 0, - loadFactor: parseInt(json['load_factor']) ?? 0, + loadBase: IntUtils.tryParse(json['load_base']) ?? 0, + loadFactor: IntUtils.tryParse(json['load_factor']) ?? 0, loadFactorFeeEscalation: - parseInt(json['load_factor_fee_escalation']) ?? 0, - loadFactorFeeQueue: parseInt(json['load_factor_fee_queue']) ?? 0, - loadFactorFeeReference: parseInt(json['load_factor_fee_reference']) ?? 0, - loadFactorServer: parseInt(json['load_factor_server']) ?? 0, - peerDisconnects: parseInt(json['peer_disconnects']) ?? 0, + IntUtils.tryParse(json['load_factor_fee_escalation']) ?? 0, + loadFactorFeeQueue: IntUtils.tryParse(json['load_factor_fee_queue']) ?? 0, + loadFactorFeeReference: + IntUtils.tryParse(json['load_factor_fee_reference']) ?? 0, + loadFactorServer: IntUtils.tryParse(json['load_factor_server']) ?? 0, + peerDisconnects: IntUtils.tryParse(json['peer_disconnects']) ?? 0, peerDisconnectsResources: - parseInt(json['peer_disconnects_resources']) ?? 0, + IntUtils.tryParse(json['peer_disconnects_resources']) ?? 0, peers: json['peers'], pubkeyNode: json['pubkey_node'], serverState: json['server_state'], - serverStateDurationUs: parseInt(json['server_state_duration_us']) ?? 0, + serverStateDurationUs: + IntUtils.tryParse(json['server_state_duration_us']) ?? 0, stateAccounting: XRPLedgerStateAccounting.fromJson(json['state_accounting']), time: json['time'], - uptime: parseInt(json['uptime']) ?? 0, + uptime: IntUtils.tryParse(json['uptime']) ?? 0, validatedLedger: XRPLedgerValidatedLedger.fromJson(json['validated_ledger']), validationQuorum: json['validation_quorum'], @@ -113,8 +116,8 @@ class XRPLastClose { factory XRPLastClose.fromJson(Map json) { return XRPLastClose( - convergeTime: parseInt(json['converge_time']) ?? 0, - proposers: parseInt(json['proposers']) ?? 0, + convergeTime: IntUtils.tryParse(json['converge_time']) ?? 0, + proposers: IntUtils.tryParse(json['proposers']) ?? 0, ); } } @@ -157,8 +160,8 @@ class XRPLedgerStateAccountingDuration { factory XRPLedgerStateAccountingDuration.fromJson(Map json) { return XRPLedgerStateAccountingDuration( - durationUs: parseInt(json['duration_us']) ?? 0, - transitions: parseInt(json['transitions']) ?? 0, + durationUs: IntUtils.tryParse(json['duration_us']) ?? 0, + transitions: IntUtils.tryParse(json['transitions']) ?? 0, ); } } @@ -182,8 +185,8 @@ class XRPLedgerValidatedLedger { factory XRPLedgerValidatedLedger.fromJson(Map json) { return XRPLedgerValidatedLedger( - baseFee: parseInt(json['base_fee']) ?? 0, - closeTime: parseInt(json['close_time']) ?? 0, + baseFee: IntUtils.tryParse(json['base_fee']) ?? 0, + closeTime: IntUtils.tryParse(json['close_time']) ?? 0, hash: json['hash'], reserveBase: json['reserve_base'], reserveInc: json['reserve_inc'], diff --git a/lib/src/rpc/on_chain_models/transaction_result.dart b/lib/src/rpc/on_chain_models/transaction_result.dart index bd0f436..ef25ee8 100644 --- a/lib/src/rpc/on_chain_models/transaction_result.dart +++ b/lib/src/rpc/on_chain_models/transaction_result.dart @@ -1,4 +1,4 @@ -import 'package:xrpl_dart/src/number/number_parser.dart'; +import 'package:blockchain_utils/numbers/numbers.dart'; class OnChainXRPLMemo { final String? memoData; @@ -57,12 +57,12 @@ class XRPLTxJson { []; return XRPLTxJson( account: json['Account'] ?? '', - fee: parseBigInt(json['Fee']) ?? BigInt.zero, - flags: parseInt(json['Flags']) ?? 0, - lastLedgerSequence: parseInt(json['LastLedgerSequence']) ?? 0, + fee: BigintUtils.tryParse(json['Fee']) ?? BigInt.zero, + flags: IntUtils.tryParse(json['Flags']) ?? 0, + lastLedgerSequence: IntUtils.tryParse(json['LastLedgerSequence']) ?? 0, memos: memosList, - nFTokenTaxon: parseInt(json['NFTokenTaxon']) ?? 0, - sequence: parseInt(json['Sequence']) ?? 0, + nFTokenTaxon: IntUtils.tryParse(json['NFTokenTaxon']) ?? 0, + sequence: IntUtils.tryParse(json['Sequence']) ?? 0, signingPubKey: json['SigningPubKey'] ?? '', transactionType: json['TransactionType'] ?? '', txnSignature: json['TxnSignature'] ?? '', @@ -112,20 +112,22 @@ class XRPLTransactionResult { return XRPLTransactionResult( accepted: json['accepted'] ?? false, accountSequenceAvailable: - parseInt(json['account_sequence_available']) ?? 0, - accountSequenceNext: parseInt(json['account_sequence_next']) ?? 0, + IntUtils.tryParse(json['account_sequence_available']) ?? 0, + accountSequenceNext: + IntUtils.tryParse(json['account_sequence_next']) ?? 0, applied: json['applied'] ?? false, broadcast: json['broadcast'] ?? false, engineResult: json['engine_result'] ?? '', - engineResultCode: parseInt(json['engine_result_code']) ?? 0, + engineResultCode: IntUtils.tryParse(json['engine_result_code']) ?? 0, engineResultMessage: json['engine_result_message'] ?? '', kept: json['kept'] ?? false, - openLedgerCost: parseInt(json['open_ledger_cost']) ?? 0, + openLedgerCost: IntUtils.tryParse(json['open_ledger_cost']) ?? 0, queued: json['queued'] ?? false, status: json['status'] ?? '', txBlob: json['tx_blob'] ?? '', txJson: XRPLTxJson.fromJson(json['tx_json'] ?? {}), - validatedLedgerIndex: parseInt(json['validated_ledger_index']) ?? 0, + validatedLedgerIndex: + IntUtils.tryParse(json['validated_ledger_index']) ?? 0, ); } } diff --git a/lib/src/utility/fulfillment/ans1_raw_encoder.dart b/lib/src/utility/fulfillment/ans1/ans1_raw_encoder.dart similarity index 88% rename from lib/src/utility/fulfillment/ans1_raw_encoder.dart rename to lib/src/utility/fulfillment/ans1/ans1_raw_encoder.dart index b20201d..13bf92a 100644 --- a/lib/src/utility/fulfillment/ans1_raw_encoder.dart +++ b/lib/src/utility/fulfillment/ans1/ans1_raw_encoder.dart @@ -22,20 +22,22 @@ import 'package:blockchain_utils/blockchain_utils.dart'; +import 'asn1_codec_exception.dart'; + class ASN1RawEncoder { /// Encode an ASN.1 raw value static List encode(ANS1RawOptions raw) { - List buf = encodeIdentifier(raw); + List buf = _encodeIdentifier(raw); // Add length information and raw data if (!raw.indefinite) { int length = raw.content.length; - buf.addAll(encodeLength(length)); + buf.addAll(_encodeLength(length)); buf.addAll(raw.content); } else { // Indefinite length uses 0x80, data..., 0x00, 0x00 if (!raw.constructed) { - throw Exception( + throw ASN1CodecException( 'indefinite length is only allowed for constructed types'); } buf.add(0x80); @@ -46,10 +48,30 @@ class ASN1RawEncoder { return buf; } + static List encodeIntegerValue(int value) { + if (value == 0) { + return [0]; + } + List encoded = []; + + // Determine the number of bytes needed to represent the value + int byteCount = (value.bitLength + 7) ~/ 8; + + // Encode value + for (int i = byteCount - 1; i >= 0; i--) { + encoded.add((value >> (8 * i)) & mask8); + } + // If the first bit of the first byte is 1 (negative number), prepend a zero byte + if ((encoded[0] & 0x80) != 0) { + encoded.insert(0, 0); + } + return encoded; + } + /// Encode the identifier of an ASN.1 raw value - static List encodeIdentifier(ANS1RawOptions node) { + static List _encodeIdentifier(ANS1RawOptions node) { if (node.classValue > 0x03) { - throw Exception('invalid class value: ${node.classValue}'); + throw ASN1CodecException('invalid class value: ${node.classValue}'); } List identifier = List.from([0x00], growable: true); @@ -67,14 +89,14 @@ class ASN1RawEncoder { identifier[0] += (0x1f & node.tag); } else { identifier[0] += 0x1f; - identifier.addAll(encodeMultiByteTag(node.tag)); + identifier.addAll(_encodeMultiByteTag(node.tag)); } return identifier; } /// Encode a multi-byte tag - static List encodeMultiByteTag(int tag) { + static List _encodeMultiByteTag(int tag) { int bufLen = ((32 - 1) ~/ 7) + 1; // Assuming a 32-bit integer List buf = List.filled(bufLen, 0); @@ -89,11 +111,11 @@ class ASN1RawEncoder { } /// Discard leading zero values - return removeLeadingBytes(buf, 0x80); + return _removeLeadingBytes(buf, 0x80); } /// Encode the length of an ASN.1 raw value - static List encodeLength(int length) { + static List _encodeLength(int length) { if (length < 0x80) { return [length]; } @@ -108,7 +130,7 @@ class ASN1RawEncoder { } // Ignore leading zeros - buf = removeLeadingBytes(buf, 0x00); + buf = _removeLeadingBytes(buf, 0x00); // Add leading byte with the number of following bytes buf.insert(0, 0x80 + buf.length); @@ -116,33 +138,13 @@ class ASN1RawEncoder { } /// Remove leading bytes from a list - static List removeLeadingBytes(List buf, int target) { + static List _removeLeadingBytes(List buf, int target) { int start = 0; while (start < buf.length - 1 && buf[start] == target) { start++; } return buf.sublist(start); } - - static List encodeIntegerValue(int value) { - if (value == 0) { - return [0]; - } - List encoded = []; - - // Determine the number of bytes needed to represent the value - int byteCount = (value.bitLength + 7) ~/ 8; - - // Encode value - for (int i = byteCount - 1; i >= 0; i--) { - encoded.add((value >> (8 * i)) & mask8); - } - // If the first bit of the first byte is 1 (negative number), prepend a zero byte - if ((encoded[0] & 0x80) != 0) { - encoded.insert(0, 0); - } - return encoded; - } } /// Placeholder for the ANS1RawOptions class - adjust according to your actual implementation diff --git a/lib/src/utility/fulfillment/ans1/asn1_codec_exception.dart b/lib/src/utility/fulfillment/ans1/asn1_codec_exception.dart new file mode 100644 index 0000000..ccd0442 --- /dev/null +++ b/lib/src/utility/fulfillment/ans1/asn1_codec_exception.dart @@ -0,0 +1,7 @@ +import 'package:blockchain_utils/exception/exceptions.dart'; + +class ASN1CodecException implements BlockchainUtilsException { + @override + final String message; + const ASN1CodecException(this.message); +} diff --git a/lib/src/utility/fulfillment/fulfillment.dart b/lib/src/utility/fulfillment/fulfillment.dart new file mode 100644 index 0000000..c693d35 --- /dev/null +++ b/lib/src/utility/fulfillment/fulfillment.dart @@ -0,0 +1,3 @@ +export 'ans1/ans1_raw_encoder.dart'; +export 'ans1/asn1_codec_exception.dart'; +export 'pre_image/pre_image_sha256.dart'; diff --git a/lib/src/utility/fulfillment/pre_image_sha256.dart b/lib/src/utility/fulfillment/pre_image/pre_image_sha256.dart similarity index 95% rename from lib/src/utility/fulfillment/pre_image_sha256.dart rename to lib/src/utility/fulfillment/pre_image/pre_image_sha256.dart index d1b9270..a69d48c 100644 --- a/lib/src/utility/fulfillment/pre_image_sha256.dart +++ b/lib/src/utility/fulfillment/pre_image/pre_image_sha256.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/blockchain_utils.dart'; -import 'ans1_raw_encoder.dart'; +import '../ans1/ans1_raw_encoder.dart'; /// Represents a fulfillment with SHA-256 preimage in Dart. /// [Crypto-Conditions Fulfillment](https://github.com/rfcs/crypto-conditions/blob/master/src/asn1/CryptoConditions.asn) @@ -9,7 +9,7 @@ import 'ans1_raw_encoder.dart'; /// This class encapsulates the data related to a fulfillment with a SHA-256 preimage, /// including the fulfillment byte array and the corresponding condition byte array. /// -/// It provides a factory method, [generate], to create an instance of [FulfillmentPreimageSha256] +/// It provides a factory method, [FulfillmentPreimageSha256.generate], to create an instance of [FulfillmentPreimageSha256] /// based on a given preimage. The generation process involves creating ASN.1-encoded options /// for fingerprint, constant, and condition, which are then used to construct the encoded /// fulfillment and condition byte arrays. diff --git a/lib/src/utility/helper.dart b/lib/src/utility/helper.dart index 2ca8b97..9271aeb 100644 --- a/lib/src/utility/helper.dart +++ b/lib/src/utility/helper.dart @@ -50,11 +50,11 @@ class XRPHelper { } /// This asynchronous function calculates transaction fees for an XRPL transaction. - static Future calculateFees( - XRPLRpc client, XRPTransaction transaction) async { + static Future calculateFees(XRPLRpc client, XRPTransaction transaction, + {XrplFeeType feeType = XrplFeeType.open}) async { /// Fetch the net fee from the XRPL server. final int netFee = - (await client.request(RPCFee())).getFeeType(type: XrplFeeType.open); + (await client.request(RPCFee())).getFeeType(type: feeType); /// Initialize the base fee with the net fee. int baseFee = netFee; @@ -65,23 +65,23 @@ class XRPHelper { transaction as EscrowFinish; if (transaction.fulfillment != null) { /// Calculate the length of the fulfillment in bytes. - int fulfillmentBytesLength = transaction.fulfillment!.codeUnits.length; + final int fulfillmentBytesLength = + transaction.fulfillment!.codeUnits.length; /// Adjust the base fee based on the fulfillment length. baseFee = (netFee * (33 + (fulfillmentBytesLength / 16)).ceil()).ceil(); } - } - /// Check if the transaction type is AMM_CREATE or ACCOUNT_DELETE. - if (transaction.transactionType == XRPLTransactionType.ammCreate || + /// Check if the transaction type is AMM_CREATE or ACCOUNT_DELETE. + } else if (transaction.transactionType == XRPLTransactionType.ammCreate || transaction.transactionType == XRPLTransactionType.accountDelete) { /// Fetch the reserve fee and set it as the base fee. baseFee = await fetchReserveFee(client); } /// Adjust the base fee if the transaction involves multi-signers. - if (transaction.multiSigSigners.isNotEmpty) { - baseFee += netFee * (1 + transaction.multiSigSigners.length); + if (transaction.isMultisig) { + baseFee += netFee * (1 + transaction.multisigSigners.length); } /// Set the calculated base fee in the transaction. @@ -177,7 +177,7 @@ class XRPHelper { List affectedNodes = meta['AffectedNodes']; List createdNodes = affectedNodes.where((node) { return isCreatedNode(node) && - node['CreatedNode']['LedgerEntryType'] == 'XChainOwnedClaimID'; + node['CreatedNode']?['LedgerEntryType'] == 'XChainOwnedClaimID'; }).toList(); if (createdNodes.isEmpty) { @@ -208,4 +208,13 @@ class XRPHelper { final result = binary.STObject.fromValue(value, false).toBytes(); return BytesUtils.toHexString(result, lowerCase: false); } + + int createFlag(List flags) { + if (flags.isEmpty) return 0; + int accumulator = 0; + for (int i in flags) { + accumulator |= i; + } + return accumulator; + } } diff --git a/lib/src/utility/utility.dart b/lib/src/utility/utility.dart index f8d9bfa..5140dcc 100644 --- a/lib/src/utility/utility.dart +++ b/lib/src/utility/utility.dart @@ -1,2 +1,2 @@ +export 'fulfillment/fulfillment.dart'; export 'helper.dart'; -export 'fulfillment/pre_image_sha256.dart'; diff --git a/lib/src/xrpl/address/xrpl.dart b/lib/src/xrpl/address/xrpl.dart index 3249299..44e87f3 100644 --- a/lib/src/xrpl/address/xrpl.dart +++ b/lib/src/xrpl/address/xrpl.dart @@ -1,11 +1,12 @@ import 'package:blockchain_utils/bip/coin_conf/coins_conf.dart'; import 'package:blockchain_utils/blockchain_utils.dart'; -import 'package:xrpl_dart/src/keypair/xrpl_private_key.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; +import 'package:xrpl_dart/src/xrpl/exception/exceptions.dart'; class XRPAddress { final String address; final int? tag; - XRPAddress._(this.address, this.tag); + const XRPAddress._(this.address, this.tag); /// Creates an XRPAddress from a byte representation. factory XRPAddress.fromPublicKeyBytes( @@ -34,12 +35,15 @@ class XRPAddress { } /// Creates an XRP address from a base58-encoded string. - factory XRPAddress(String address) { + factory XRPAddress(String address, {bool allowXAddress = false}) { try { + if (allowXAddress && XRPAddressUtils.isXAddress(address)) { + return XRPAddress.fromXAddress(address); + } XrpAddrDecoder().decodeAddr(address); return XRPAddress._(address, null); } catch (e) { - throw ArgumentError("Invalid ripple address"); + throw XRPLAddressCodecException("Invalid ripple address"); } } diff --git a/lib/src/xrpl/bytes/binery_serializer/binary_parser.dart b/lib/src/xrpl/bytes/binery_serializer/binary_parser.dart index 9cf0fec..dbe8e5f 100644 --- a/lib/src/xrpl/bytes/binery_serializer/binary_parser.dart +++ b/lib/src/xrpl/bytes/binery_serializer/binary_parser.dart @@ -1,45 +1,42 @@ -/* -Copyright (c) 2021, XRP Ledger Foundation - -Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE -INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE -FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING -OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - - Note: This code has been adapted from its original Python version to Dart. -*/ -/* - The 3-Clause BSD License - - Copyright (c) 2023 Mohsen Haydari (MRTNETWORK) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, this - list of conditions, and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, this - list of conditions, and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. Neither the name of the [organization] nor the names of its contributors may be - used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +// Copyright (c) 2021, XRP Ledger Foundation + +// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE +// INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE +// FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING +// OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +// Note: This code has been adapted from its original Python version to Dart. + +// The 3-Clause BSD License + +// Copyright (c) 2023 Mohsen Haydari (MRTNETWORK) +// All rights reserved. + +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: + +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions, and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, this +// list of conditions, and the following disclaimer in the documentation and/or +// other materials provided with the distribution. +// 3. Neither the name of the [organization] nor the names of its contributors may be +// used to endorse or promote products derived from this software without +// specific prior written permission. + +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +// OF THE POSSIBILITY OF SUCH DAMAGE. import 'package:blockchain_utils/blockchain_utils.dart'; import 'package:xrpl_dart/src/xrpl/bytes/definations/definations.dart'; diff --git a/lib/src/xrpl/bytes/binery_serializer/binary_serializer.dart b/lib/src/xrpl/bytes/binery_serializer/binary_serializer.dart index f371020..1335aec 100644 --- a/lib/src/xrpl/bytes/binery_serializer/binary_serializer.dart +++ b/lib/src/xrpl/bytes/binery_serializer/binary_serializer.dart @@ -43,6 +43,7 @@ OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import 'package:blockchain_utils/binary/binary.dart'; import 'package:xrpl_dart/src/xrpl/bytes/definations/field.dart'; +import 'package:xrpl_dart/src/xrpl/exception/exceptions.dart'; /// Constants for binary serializer class _BinerySerializerConst { @@ -120,7 +121,7 @@ class BinarySerializer { return [byte1, byte2, byte3]; } - throw Exception( + throw XRPLBinaryCodecException( 'VariableLength field must be <= ${_BinerySerializerConst._maxLengthValue} bytes long'); } } diff --git a/lib/src/xrpl/bytes/definations/defination_types.dart b/lib/src/xrpl/bytes/definations/defination_types.dart index 5253a57..b6a15f2 100644 --- a/lib/src/xrpl/bytes/definations/defination_types.dart +++ b/lib/src/xrpl/bytes/definations/defination_types.dart @@ -1,45 +1,42 @@ -/* -Copyright (c) 2021, XRP Ledger Foundation +// Copyright (c) 2021, XRP Ledger Foundation -Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. +// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE -INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE -FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING -OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - - Note: This code has been adapted from its original Python version to Dart. -*/ -/* - The 3-Clause BSD License - - Copyright (c) 2023 Mohsen Haydari (MRTNETWORK) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, this - list of conditions, and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, this - list of conditions, and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. Neither the name of the [organization] nor the names of its contributors may be - used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE +// INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE +// FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING +// OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +// Note: This code has been adapted from its original Python version to Dart. + +// The 3-Clause BSD License + +// Copyright (c) 2023 Mohsen Haydari (MRTNETWORK) +// All rights reserved. + +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: + +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions, and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, this +// list of conditions, and the following disclaimer in the documentation and/or +// other materials provided with the distribution. +// 3. Neither the name of the [organization] nor the names of its contributors may be +// used to endorse or promote products derived from this software without +// specific prior written permission. + +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +// OF THE POSSIBILITY OF SUCH DAMAGE. part of 'package:xrpl_dart/src/xrpl/bytes/definations/definations.dart'; diff --git a/lib/src/xrpl/bytes/definations/definations.dart b/lib/src/xrpl/bytes/definations/definations.dart index 879d9a7..3dedffc 100644 --- a/lib/src/xrpl/bytes/definations/definations.dart +++ b/lib/src/xrpl/bytes/definations/definations.dart @@ -4,38 +4,44 @@ part 'defination_types.dart'; /// Class containing XRPL definitions and mapping methods class XRPLDefinitions { - static Map get fexx => _definationsFields; + static const String _fieldKey = "FIELDS"; + static const String _transactionTypesKey = "TRANSACTION_TYPES"; + static const String _transactionResultKey = "TRANSACTION_RESULTS"; + static const String _ledgerEnteryTypesKey = "LEDGER_ENTRY_TYPES"; + static const String _typesKey = "TYPES"; + static const String _typeKey = "type"; + static const String _nthKey = "nth"; /// Map transaction type codes to strings static Map get _transactionTypeCodeToStrMap => Map.fromEntries( - (_definationsFields["TRANSACTION_TYPES"] as Map) + (_definationsFields[_transactionTypesKey] as Map) .entries .map((entry) => MapEntry(entry.value, entry.key))); /// Map transaction result codes to strings static Map get _transactionResultsCodeToStrMap => - Map.fromEntries(_definationsFields["TRANSACTION_RESULTS"] + Map.fromEntries(_definationsFields[_transactionResultKey] .entries .map((entry) => MapEntry(entry.value, entry.key))); /// Map ledger entry types codes to strings static Map get _ledgerEntryTypesCodeToStrMap => - Map.fromEntries(_definationsFields["LEDGER_ENTRY_TYPES"] + Map.fromEntries(_definationsFields[_ledgerEnteryTypesKey] .entries .map((entry) => MapEntry(entry.value, entry.key))); /// Map field types by field name - static Map get _typeOrdinalMap => _definationsFields["TYPES"]; + static Map get _typeOrdinalMap => _definationsFields[_typesKey]; /// Get field type by field name static String getFieldTypeByName(String fieldName) { - return _definationsFields["FIELDS"][fieldName]["type"]; + return _definationsFields[_fieldKey][fieldName][_typeKey]; } /// Get the field type ID by field name static int getFieldTypeId(String fieldName) { String fieldType = getFieldTypeByName(fieldName); - int? fieldTypeId = _typeOrdinalMap[fieldType]; + final int? fieldTypeId = _typeOrdinalMap[fieldType]; if (fieldTypeId == null) { throw const XRPLBinaryCodecException( "Field type codes in definitions.json must be ints."); @@ -45,7 +51,7 @@ class XRPLDefinitions { /// Get the field code by field name static int getFieldCode(String fieldName) { - return _definationsFields["FIELDS"][fieldName]["nth"]; + return _definationsFields[_fieldKey][fieldName][_nthKey]; } /// Get field header from field name @@ -57,19 +63,19 @@ class XRPLDefinitions { static String getFieldNameFromHeader(FieldHeader fieldHeader) { final findType = _typeOrdinalMap.keys.firstWhere( (element) => _typeOrdinalMap[element] == fieldHeader.typeCode); - for (final i in (_definationsFields["FIELDS"] as Map).entries) { - if (i.value["nth"] == fieldHeader.fieldCode && - i.value["type"] == findType) { + for (final i in (_definationsFields[_fieldKey] as Map).entries) { + if (i.value[_nthKey] == fieldHeader.fieldCode && + i.value[_typeKey] == findType) { return i.key; } } - throw StateError("Cannot find fild name"); + throw const XRPLBinaryCodecException("fild does not exist."); } /// Get field instance by field name static FieldInstance getFieldInstance(String fieldName) { FieldInfo info = - FieldInfo.fromJson(_definationsFields["FIELDS"][fieldName]); + FieldInfo.fromJson(_definationsFields[_fieldKey][fieldName]); FieldHeader fieldHeader = getFieldHeaderFromName(fieldName); return FieldInstance(info, fieldName, fieldHeader); @@ -77,7 +83,7 @@ class XRPLDefinitions { /// Get transaction type code by transaction type name static int getTransactionTypeCode(String transactionType) { - return _definationsFields["TRANSACTION_TYPES"][transactionType] as int; + return _definationsFields[_transactionTypesKey][transactionType] as int; } /// Get transaction type name by transaction type code @@ -87,7 +93,7 @@ class XRPLDefinitions { /// Get transaction result code by transaction result type name static int getTransactionResultCode(String transactionResultType) { - return _definationsFields["TRANSACTION_RESULTS"][transactionResultType] + return _definationsFields[_transactionResultKey][transactionResultType] as int; } @@ -98,7 +104,7 @@ class XRPLDefinitions { /// Get ledger entry type code by ledger entry type name static int getLedgerEntryTypeCode(String ledgerEntryType) { - return _definationsFields["LEDGER_ENTRY_TYPES"][ledgerEntryType] as int; + return _definationsFields[_ledgerEnteryTypesKey][ledgerEntryType] as int; } /// Get ledger entry type name by ledger entry type code diff --git a/lib/src/xrpl/bytes/definations/field.dart b/lib/src/xrpl/bytes/definations/field.dart index c22cc2c..c1cb6df 100644 --- a/lib/src/xrpl/bytes/definations/field.dart +++ b/lib/src/xrpl/bytes/definations/field.dart @@ -33,12 +33,12 @@ class FieldInfo { /// Represents the header of a field class FieldHeader { /// Constructor to initialize directly with type and field codes - FieldHeader(this.typeCode, this.fieldCode); + const FieldHeader(this.typeCode, this.fieldCode); /// Constructor to initialize from a JSON map - FieldHeader.fromJson(Map json) - : typeCode = json["type"], - fieldCode = json["nth"]; + factory FieldHeader.fromJson(Map json) { + return FieldHeader(json["type"], json["nth"]); + } /// The type code of the field final int typeCode; diff --git a/lib/src/xrpl/bytes/serializer.dart b/lib/src/xrpl/bytes/serializer.dart index 1c8e365..02d16fd 100644 --- a/lib/src/xrpl/bytes/serializer.dart +++ b/lib/src/xrpl/bytes/serializer.dart @@ -71,17 +71,12 @@ part 'types/xchain_bridge.dart'; /// An abstract class representing a serialized XRPL object. abstract class SerializedType { - late final List _buffer; + final List _buffer; /// Constructs a SerializedType object with an optional buffer. /// If buffer is not provided, an empty bytes is used. - SerializedType([List? buffer]) { - if (buffer != null) { - _buffer = List.unmodifiable(BytesUtils.toBytes(buffer)); - return; - } - _buffer = List.empty(); - } + SerializedType(List buffer) + : _buffer = BytesUtils.toBytes(buffer, unmodifiable: true); /// Converts the serialized object to a bytes. List toBytes() { diff --git a/lib/src/xrpl/bytes/types/account_id.dart b/lib/src/xrpl/bytes/types/account_id.dart index 922b4de..8f53a25 100644 --- a/lib/src/xrpl/bytes/types/account_id.dart +++ b/lib/src/xrpl/bytes/types/account_id.dart @@ -1,45 +1,41 @@ -/* -Copyright (c) 2021, XRP Ledger Foundation +// Copyright (c) 2021, XRP Ledger Foundation -Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. +// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE -INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE -FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING -OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - - Note: This code has been adapted from its original Python version to Dart. -*/ -/* - The 3-Clause BSD License - - Copyright (c) 2023 Mohsen Haydari (MRTNETWORK) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, this - list of conditions, and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, this - list of conditions, and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. Neither the name of the [organization] nor the names of its contributors may be - used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE +// INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE +// FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING +// OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +// Note: This code has been adapted from its original Python version to Dart. +// The 3-Clause BSD License + +// Copyright (c) 2023 Mohsen Haydari (MRTNETWORK) +// All rights reserved. + +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: + +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions, and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, this +// list of conditions, and the following disclaimer in the documentation and/or +// other materials provided with the distribution. +// 3. Neither the name of the [organization] nor the names of its contributors may be +// used to endorse or promote products derived from this software without +// specific prior written permission. + +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +// OF THE POSSIBILITY OF SUCH DAMAGE. part of 'package:xrpl_dart/src/xrpl/bytes/serializer.dart'; /// Utility class for Account ID operations @@ -56,28 +52,27 @@ class _AccountIdUils { class AccountID extends Hash160 { @override factory AccountID.fromParser(BinaryParser parser, [int? lengthHint]) { - final numBytes = lengthHint ?? 20; + final numBytes = lengthHint ?? Hash160.lengthBytes; final bytes = parser.read(numBytes); - return AccountID(bytes); + return AccountID(buffer: bytes); } /// Constructor for AccountID - AccountID([List? buffer]) - : super(buffer ?? List.filled(Hash160.lengthBytes, 0)); + AccountID({required List buffer}) : super(buffer); @override factory AccountID.fromValue(dynamic value) { if (value == null || value is! String || value.isEmpty) { - return AccountID(); + return AccountID(buffer: List.filled(Hash160.lengthBytes, 0)); } /// Hex-encoded case if (_AccountIdUils.isHash160(value)) { - return AccountID(BytesUtils.fromHexString(value)); + return AccountID(buffer: BytesUtils.fromHexString(value)); } try { final addrHash = XRPAddressUtils.decodeAddress(value); - return AccountID(addrHash); + return AccountID(buffer: addrHash); } catch (e) { throw XRPLBinaryCodecException( "Invalid value to construct an AccountID: expected valid classic address " diff --git a/lib/src/xrpl/bytes/types/blob.dart b/lib/src/xrpl/bytes/types/blob.dart index 1e3a854..eb8b01d 100644 --- a/lib/src/xrpl/bytes/types/blob.dart +++ b/lib/src/xrpl/bytes/types/blob.dart @@ -1,7 +1,7 @@ part of 'package:xrpl_dart/src/xrpl/bytes/serializer.dart'; class Blob extends SerializedType { - Blob([List? buffer]) : super(buffer); + Blob(List buffer) : super(buffer); @override factory Blob.fromParser(BinaryParser parser, [int? lengthHint]) { diff --git a/lib/src/xrpl/bytes/types/hash.dart b/lib/src/xrpl/bytes/types/hash.dart index 00cb862..00c99d9 100644 --- a/lib/src/xrpl/bytes/types/hash.dart +++ b/lib/src/xrpl/bytes/types/hash.dart @@ -1,7 +1,7 @@ part of 'package:xrpl_dart/src/xrpl/bytes/serializer.dart'; abstract class Hash extends SerializedType { - Hash([List? buffer]) : super(buffer) { + Hash(List buffer) : super(buffer) { if (_buffer.length != getLength()) { throw XRPLBinaryCodecException( "Invalid hash length ${_buffer.length}. ${getLength()}"); diff --git a/lib/src/xrpl/bytes/types/issue.dart b/lib/src/xrpl/bytes/types/issue.dart index a6da436..0f5686e 100644 --- a/lib/src/xrpl/bytes/types/issue.dart +++ b/lib/src/xrpl/bytes/types/issue.dart @@ -1,7 +1,7 @@ part of 'package:xrpl_dart/src/xrpl/bytes/serializer.dart'; class Issue extends SerializedType { - Issue([List? buffer]) : super(buffer); + Issue(List buffer) : super(buffer); @override factory Issue.fromValue(Map value) { diff --git a/lib/src/xrpl/bytes/types/path.dart b/lib/src/xrpl/bytes/types/path.dart index 4c5899d..c44fb9c 100644 --- a/lib/src/xrpl/bytes/types/path.dart +++ b/lib/src/xrpl/bytes/types/path.dart @@ -30,7 +30,7 @@ class _PathUtils { } class PathStep extends SerializedType { - PathStep([List? buffer]) : super(buffer); + PathStep(List buffer) : super(buffer); @override factory PathStep.fromValue(Map value) { @@ -103,7 +103,7 @@ class PathStep extends SerializedType { } class Path extends SerializedType { - Path([List? buffer]) : super(buffer); + Path(List buffer) : super(buffer); @override factory Path.fromValue(List value) { @@ -148,7 +148,7 @@ class Path extends SerializedType { } class PathSet extends SerializedType { - PathSet([List? buffer]) : super(buffer); + PathSet(List buffer) : super(buffer); @override factory PathSet.fromValue(List value) { diff --git a/lib/src/xrpl/bytes/types/st_array.dart b/lib/src/xrpl/bytes/types/st_array.dart index 32b17d9..3cc6801 100644 --- a/lib/src/xrpl/bytes/types/st_array.dart +++ b/lib/src/xrpl/bytes/types/st_array.dart @@ -7,7 +7,7 @@ class _StArrayConst { } class STArray extends SerializedType { - STArray([List? buffer]) : super(buffer); + STArray(List buffer) : super(buffer); @override factory STArray.fromParser(BinaryParser parser, [int? lengthHint]) { diff --git a/lib/src/xrpl/bytes/types/st_object.dart b/lib/src/xrpl/bytes/types/st_object.dart index a019472..5c24213 100644 --- a/lib/src/xrpl/bytes/types/st_object.dart +++ b/lib/src/xrpl/bytes/types/st_object.dart @@ -57,7 +57,7 @@ class _StObjectUtils { } class STObject extends SerializedType { - STObject([List? buffer]) : super(buffer); + STObject(List buffer) : super(buffer); factory STObject.fromParser(BinaryParser parser, [int? lengthHint]) { final serializer = BinarySerializer(); diff --git a/lib/src/xrpl/bytes/types/uint.dart b/lib/src/xrpl/bytes/types/uint.dart index 418d133..279b783 100644 --- a/lib/src/xrpl/bytes/types/uint.dart +++ b/lib/src/xrpl/bytes/types/uint.dart @@ -1,7 +1,7 @@ part of 'package:xrpl_dart/src/xrpl/bytes/serializer.dart'; abstract class UInt extends SerializedType { - UInt([List? buffer]) : super(buffer); + UInt(List buffer) : super(buffer); int get value { return int.parse(BytesUtils.toHexString(_buffer), radix: 16); diff --git a/lib/src/xrpl/bytes/types/vector256.dart b/lib/src/xrpl/bytes/types/vector256.dart index fdc1dd6..f338ced 100644 --- a/lib/src/xrpl/bytes/types/vector256.dart +++ b/lib/src/xrpl/bytes/types/vector256.dart @@ -2,7 +2,7 @@ part of 'package:xrpl_dart/src/xrpl/bytes/serializer.dart'; class Vector256 extends SerializedType { static const int lengthInBytes = 32; - Vector256([List? buffer]) : super(buffer); + Vector256(List buffer) : super(buffer); @override factory Vector256.fromValue(List value) { diff --git a/lib/src/xrpl/bytes/types/xchain_bridge.dart b/lib/src/xrpl/bytes/types/xchain_bridge.dart index 277ad62..fe92ae1 100644 --- a/lib/src/xrpl/bytes/types/xchain_bridge.dart +++ b/lib/src/xrpl/bytes/types/xchain_bridge.dart @@ -32,7 +32,7 @@ class _XChainBridgeConst { } class XChainBridge extends SerializedType { - XChainBridge([List? buffer]) : super(buffer); + XChainBridge(List buffer) : super(buffer); @override factory XChainBridge.fromValue(Map value) { if (iterableIsEqual(value.keys, _XChainBridgeConst.keys)) { diff --git a/lib/src/xrpl/exception/exceptions.dart b/lib/src/xrpl/exception/exceptions.dart index d82aa97..ef5c211 100644 --- a/lib/src/xrpl/exception/exceptions.dart +++ b/lib/src/xrpl/exception/exceptions.dart @@ -12,7 +12,7 @@ class XRPLBinaryCodecException implements BlockchainUtilsException { String toString() => message; } -/// Exception thrown when an error occurs during XRPL address encoding or decoding. +/// Exception thrown when an error occurs during XRPL address, keypair, encoding or decoding. class XRPLAddressCodecException implements BlockchainUtilsException { @override final String message; @@ -22,3 +22,12 @@ class XRPLAddressCodecException implements BlockchainUtilsException { @override String toString() => message; } + +class XRPLTransactionException implements BlockchainUtilsException { + @override + final String message; + + const XRPLTransactionException(this.message); + @override + String toString() => message; +} diff --git a/lib/src/xrpl/models/account/account_delete.dart b/lib/src/xrpl/models/account/account_delete.dart index 9d6e19b..857445d 100644 --- a/lib/src/xrpl/models/account/account_delete.dart +++ b/lib/src/xrpl/models/account/account_delete.dart @@ -1,3 +1,4 @@ +import 'package:xrpl_dart/src/crypto/crypto.dart'; import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; /// Represents an AccountDelete transaction @@ -14,30 +15,28 @@ class AccountDelete extends XRPTransaction { /// [destination] account where funds should be sent. final String? destinationTag; - AccountDelete( - {required String account, - required this.destination, - this.destinationTag, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + AccountDelete({ + required String account, + required this.destination, + this.destinationTag, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, - multiSigSigners: multiSigSigners, - signers: signers, + multisigSigners: multisigSigners, flags: flags, lastLedgerSequence: lastLedgerSequence, memos: memos, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, + signer: signer, sequence: sequence, sourceTag: sourceTag, transactionType: XRPLTransactionType.accountDelete); diff --git a/lib/src/xrpl/models/account/account_set.dart b/lib/src/xrpl/models/account/account_set.dart index 29f19ff..734882d 100644 --- a/lib/src/xrpl/models/account/account_set.dart +++ b/lib/src/xrpl/models/account/account_set.dart @@ -1,3 +1,4 @@ +import 'package:xrpl_dart/src/crypto/crypto.dart'; import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; class AccountSetConst { @@ -192,38 +193,36 @@ class AccountSet extends XRPTransaction { /// also set the AccountSetAsfFlag.ASF_AUTHORIZED_NFTOKEN_MINTER flag. final String? nftTokenMinter; - AccountSet( - {required String account, - this.clearFlag, - this.domain, - this.emailHash, - this.messageKey, - this.setFlag, - this.transferRate, - this.tickSize, - this.nftTokenMinter, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + AccountSet({ + required String account, + this.clearFlag, + this.domain, + this.emailHash, + this.messageKey, + this.setFlag, + this.transferRate, + this.tickSize, + this.nftTokenMinter, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.accountSet); AccountSet.fromJson(Map json) : domain = json["domain"], diff --git a/lib/src/xrpl/models/account/set_reqular_key.dart b/lib/src/xrpl/models/account/set_reqular_key.dart index fbf7a04..681d1d6 100644 --- a/lib/src/xrpl/models/account/set_reqular_key.dart +++ b/lib/src/xrpl/models/account/set_reqular_key.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Represents a [SetRegularKey](https://xrpl.org/setregularkey.html) /// transaction, which assigns, changes, or removes a secondary "regular" key pair @@ -9,31 +10,29 @@ class SetRegularKey extends XRPTransaction { /// account. Must not match the account's master key pair. final String? regularKey; - SetRegularKey( - {this.regularKey, - required String account, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + SetRegularKey({ + this.regularKey, + required String account, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.setRegularKey); /// Converts the object to a JSON representation. diff --git a/lib/src/xrpl/models/account/signers.dart b/lib/src/xrpl/models/account/signers.dart index 3111cb9..3d29f5b 100644 --- a/lib/src/xrpl/models/account/signers.dart +++ b/lib/src/xrpl/models/account/signers.dart @@ -8,12 +8,14 @@ class XRPLSigners extends XRPLBase { {required this.account, required this.txnSignature, required this.signingPubKey}); + XRPLSigners.singer({required this.account, required this.signingPubKey}) + : txnSignature = ""; /// [account] The address of the Signer. This can be a funded account in the XRP Ledger or an unfunded address. final String account; /// [txnSignature] The signature that this Signer provided for this transaction. - final String txnSignature; + final String? txnSignature; /// [signingPubKey] The public key that should be used to verify this Signer's signature. final String signingPubKey; @@ -33,4 +35,6 @@ class XRPLSigners extends XRPLBase { } }; } + + bool get isReady => txnSignature != null; } diff --git a/lib/src/xrpl/models/amm/amm_bid.dart b/lib/src/xrpl/models/amm/amm_bid.dart index 2f56658..9a6886d 100644 --- a/lib/src/xrpl/models/amm/amm_bid.dart +++ b/lib/src/xrpl/models/amm/amm_bid.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Bid on an Automated Market Maker's (AMM's) auction slot. /// If you win, you can trade against the AMM at a discounted fee until you are outbid @@ -57,35 +58,33 @@ class AMMBid extends XRPTransaction { .toList(), super.json(json); - AMMBid( - {required this.asset, - required this.asset2, - this.bidMax, - this.bidMin, - required String account, - this.authAccounts, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + AMMBid({ + required this.asset, + required this.asset2, + this.bidMax, + this.bidMin, + required String account, + this.authAccounts, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.ammBid); @override String? get validate { diff --git a/lib/src/xrpl/models/amm/amm_create.dart b/lib/src/xrpl/models/amm/amm_create.dart index 6f87899..380ff83 100644 --- a/lib/src/xrpl/models/amm/amm_create.dart +++ b/lib/src/xrpl/models/amm/amm_create.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Create a new Automated Market Maker (AMM) instance for trading a pair of /// assets (fungible tokens or XRP). @@ -31,33 +32,31 @@ class AMMCreate extends XRPTransaction { /// The minimum value is 0. final int tradingFee; - AMMCreate( - {required String account, - required this.amount, - required this.amount2, - required this.tradingFee, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + AMMCreate({ + required String account, + required this.amount, + required this.amount2, + required this.tradingFee, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.ammCreate); AMMCreate.fromJson(Map json) : amount = CurrencyAmount.fromJson(json["amount"]), diff --git a/lib/src/xrpl/models/amm/amm_delete.dart b/lib/src/xrpl/models/amm/amm_delete.dart index a92b32c..9c4de5f 100644 --- a/lib/src/xrpl/models/amm/amm_delete.dart +++ b/lib/src/xrpl/models/amm/amm_delete.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Delete an empty Automated Market Maker (AMM) instance that could not be fully /// deleted automatically. @@ -18,32 +19,30 @@ class AMMDelete extends XRPTransaction { /// [asset2] The definition for the other asset in the AMM's pool final XRPCurrencies asset2; - AMMDelete( - {required String account, - required this.asset, - required this.asset2, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + AMMDelete({ + required String account, + required this.asset, + required this.asset2, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.ammDelete); AMMDelete.fromJson(Map json) diff --git a/lib/src/xrpl/models/amm/amm_deposit.dart b/lib/src/xrpl/models/amm/amm_deposit.dart index ab90e0a..85b069b 100644 --- a/lib/src/xrpl/models/amm/amm_deposit.dart +++ b/lib/src/xrpl/models/amm/amm_deposit.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Transactions of the AMMDeposit type support additional values in the Flags field. /// This enum represents those options. @@ -67,36 +68,34 @@ class AMMDeposit extends XRPTransaction { /// [lpTokenOut] How many of the AMM's LP Tokens to buy. final IssuedCurrencyAmount? lpTokenOut; - AMMDeposit( - {required String account, - required this.asset, - required this.asset2, - this.amount, - this.amount2, - this.ePrice, - this.lpTokenOut, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + AMMDeposit({ + required String account, + required this.asset, + required this.asset2, + this.amount, + this.amount2, + this.ePrice, + this.lpTokenOut, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.ammDeposit); AMMDeposit.fromJson(Map json) diff --git a/lib/src/xrpl/models/amm/amm_vote.dart b/lib/src/xrpl/models/amm/amm_vote.dart index a38c679..f221f1d 100644 --- a/lib/src/xrpl/models/amm/amm_vote.dart +++ b/lib/src/xrpl/models/amm/amm_vote.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Vote on the trading fee for an Automated Market Maker (AMM) instance. /// Up to 8 accounts can vote in proportion to the amount of the AMM's LP Tokens @@ -17,33 +18,31 @@ class AMMVote extends XRPTransaction { /// The maximum value is 1000, indicating a 1% fee. This field is required. final int tradingFee; - AMMVote( - {required String account, - required this.tradingFee, - required this.asset, - required this.asset2, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + AMMVote({ + required String account, + required this.tradingFee, + required this.asset, + required this.asset2, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.ammVote); AMMVote.fromJson(Map json) diff --git a/lib/src/xrpl/models/amm/amm_withdraw.dart b/lib/src/xrpl/models/amm/amm_withdraw.dart index 9443946..79740af 100644 --- a/lib/src/xrpl/models/amm/amm_withdraw.dart +++ b/lib/src/xrpl/models/amm/amm_withdraw.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Transactions of the AMMWithdraw type support additional values in the Flags field. /// This enum represents those options. @@ -63,36 +64,34 @@ class AMMWithdraw extends XRPTransaction { /// to withdraw. /// /// [lpTokenIn] How many of the AMM's LP Tokens to redeem. - AMMWithdraw( - {required String account, - required this.asset, - required this.asset2, - this.amount, - this.amount2, - this.ePrice, - this.lpTokenIn, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + AMMWithdraw({ + required String account, + required this.asset, + required this.asset2, + this.amount, + this.amount2, + this.ePrice, + this.lpTokenIn, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.ammWithdraw); final XRPCurrencies asset; final XRPCurrencies asset2; diff --git a/lib/src/xrpl/models/base/base.dart b/lib/src/xrpl/models/base/base.dart index 17adab3..e3197bd 100644 --- a/lib/src/xrpl/models/base/base.dart +++ b/lib/src/xrpl/models/base/base.dart @@ -6,12 +6,4 @@ abstract class XRPLBase { /// Converts the object to a JSON representation. Map toJson(); String? get validate => null; - - /// Adds a key-value pair to a JSON map if the value is not null. - /// If the value is null, no key-value pair is added. - static void addWhenNotNull( - Map json, String key, dynamic value) { - if (value == null) return; - json[key] = value; - } } diff --git a/lib/src/xrpl/models/base/transaction.dart b/lib/src/xrpl/models/base/transaction.dart index 06a8e9e..f2b4d2c 100644 --- a/lib/src/xrpl/models/base/transaction.dart +++ b/lib/src/xrpl/models/base/transaction.dart @@ -1,14 +1,15 @@ import 'package:blockchain_utils/blockchain_utils.dart'; -import 'package:xrpl_dart/src/number/number_parser.dart'; import 'package:xrpl_dart/src/xrpl/address/xrpl.dart'; import 'package:xrpl_dart/src/xrpl/bytes/binery_serializer/binary_parser.dart'; import 'package:xrpl_dart/src/xrpl/bytes/serializer.dart'; +import 'package:xrpl_dart/src/xrpl/exception/exceptions.dart'; import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; class _TransactionUtils { static const String _transactionHashPrefix = "54584E00"; - static const String _transactionSignaturePrefix = "53545800"; - static const String _transactionMultisigPrefix = "534D5400"; + static const List _transactionSignaturePrefix = [0x53, 0x54, 0x58, 0x00]; + static const List _transactionMultisigPrefix = [0x53, 0x4D, 0x54, 0x00]; static const int hashStringLength = 64; static final _camelToSnakeCaseRegex = RegExp(r'(?:^[^A-Z]+|[A-Z]+(?![^A-Z])|[A-Z][^A-Z]*)'); @@ -98,158 +99,199 @@ class _TransactionUtils { /// transaction types [https://xrpl.org/transaction-common-fields.html](https://xrpl.org/transaction-common-fields.html). class XRPTransaction extends XRPLBase { /// [account] The address of the sender of the transaction. - /// [transactionType] (Auto-fillable) The amount of XRP to destroy as a cost to send this - /// transaction. See Transaction Cost - /// [for details](https://xrpl.org/transaction-cost.html). + final String account; + + BigInt? get fee => _fee; + BigInt? _fee; + /// [sequence] The sequence number of the transaction. Must match the /// sending account's next unused sequence number + int? get sequence => _sequence; + int? _sequence; + /// [accountTxId] A hash value identifying a previous transaction from the same sender - /// [flags] A List of flags, or a bitwise map of flags, modifying this transaction's behavior + final String? accountTxId; + + /// [flags] + final int flags; + int? _lastLedgerSequence; + /// [lastLedgerSequence] The highest ledger index this transaction can appear in + int? get lastLedgerSequence => _lastLedgerSequence; + /// [memos] Additional arbitrary information attached to this transaction - /// [signers] Signing data authorizing a multi-signed transaction. Added during multi-signing + final List memos; + + /// [multisigSigners] Signing data authorizing a multi-signed transaction. Added during multi-signing + List _multisigSigners; + List get multisigSigners => _multisigSigners; + bool get isMultisig => multisigSigners.isNotEmpty; + + /// [signer] Signing data authorizing a signle-signed transaction. + XRPLSignature? get signer => _signer; + XRPLSignature? _signer; + /// [sourceTag] The public key authorizing a single-signed transaction. Automatically added during signing + final int? sourceTag; + /// [ticketSequance] The sequence number of the ticket to use in place of a Sequence number. - /// If this is provided, sequence must be 0. Cannot be used with account_txn_id. - /// [txnSignature] The cryptographic signature from the sender that authorizes this transaction + final int? ticketSequance; + + int? _networkId; + /// [networkId] The network id of the transaction. + int? get networkId => _networkId; + + /// [transactionType] (Auto-fillable) The amount of XRP to destroy as a cost to send this + /// transaction. See Transaction Cost + /// [for details](https://xrpl.org/transaction-cost.html). + final XRPLTransactionType transactionType; + XRPTransaction( {required this.account, - this.multiSigSigners = const [], - this.fee, - this.sequence, + BigInt? fee, + int? sequence, this.accountTxId, - this.flags = 0, - this.lastLedgerSequence, - this.memos = const [], - this.signers, + int? flags, + int? lastLedgerSequence, + List? memos = const [], + List? multisigSigners, + XRPLSignature? signer, this.sourceTag, - this.signingPubKey = "", this.ticketSequance, - this.txnSignature, - this.networkId, - required this.transactionType}); - @override - String? get validate { - if (flags == null) return super.validate; - if (flags is! int && - flags is! FlagsInterface && - flags is! List && - flags is! List) { - return "flags must be int, List, FlagsInterface or List"; + int? networkId, + required this.transactionType}) + : flags = flags ?? 0, + _multisigSigners = + List.unmodifiable(multisigSigners ?? []), + _signer = signer, + _fee = fee, + _sequence = sequence, + _lastLedgerSequence = lastLedgerSequence, + _networkId = networkId, + memos = List.unmodifiable(memos ?? []) { + if (_multisigSigners.isNotEmpty && _signer != null) { + throw XRPLTransactionException( + "Utilize multisigSigners for multisig transactions, or signer for single-signature transactions."); } - return super.validate; + } + XRPTransaction copyWith({ + String? account, + BigInt? fee, + int? sequence, + String? accountTxId, + int? flags, + int? lastLedgerSequence, + List? memos, + List? multisigSigners, + XRPLSignature? signer, + int? sourceTag, + int? ticketSequance, + int? networkId, + XRPLTransactionType? transactionType, + }) { + return XRPTransaction( + account: account ?? this.account, + fee: fee ?? this.fee, + sequence: sequence ?? this.sequence, + accountTxId: accountTxId ?? this.accountTxId, + flags: flags ?? this.flags, + lastLedgerSequence: lastLedgerSequence ?? this.lastLedgerSequence, + memos: memos ?? this.memos, + multisigSigners: multisigSigners ?? this.multisigSigners, + signer: signer ?? this.signer, + sourceTag: sourceTag ?? this.sourceTag, + ticketSequance: ticketSequance ?? this.ticketSequance, + networkId: networkId ?? this.networkId, + transactionType: transactionType ?? this.transactionType, + ); } - final String account; - BigInt? fee; - int? sequence; - final String? accountTxId; - final dynamic flags; - int? lastLedgerSequence; - List? memos; - List? signers; - final int? sourceTag; - String signingPubKey; - final int? ticketSequance; - String? txnSignature; - int? networkId; - final XRPLTransactionType transactionType; - List multiSigSigners; void setNetworkId(int? network) { - networkId = network; + _networkId = network; } void setSequence(int? newSequance) { - sequence = newSequance; + _sequence = newSequance; } void setLastLedgerSequence(int? newSequance) { - lastLedgerSequence = newSequance; + _lastLedgerSequence = newSequance; } void setFee(BigInt? newFee) { - fee = newFee; + _fee = newFee; } - void setSignature(String? sig) { - txnSignature = sig; + void setSignature(XRPLSignature? signature) { + if (isMultisig) { + throw XRPLTransactionException( + "use setMultiSigSignature method for multi-signature transactions"); + } + _signer = signature; } void setMultiSigSignature(List sigs) { - signers = sigs + if (_signer != null) { + throw XRPLTransactionException( + "Please avoid setting setMultiSigSignature for non-multi-sig transactions"); + } + _multisigSigners = List.unmodifiable(sigs ..sort((a, b) { final addressA = XRPAddress(a.account).toBytes(); final addressB = XRPAddress(b.account).toBytes(); return BytesUtils.compareBytes(addressA, addressB); - }); + })); } XRPTransaction.json(Map json) : account = json["account"], - multiSigSigners = const [], flags = json["flags"], - signingPubKey = json["signing_pub_key"], - lastLedgerSequence = json["last_ledger_sequence"], - sequence = json["sequence"], - txnSignature = json["txn_signature"], - fee = parseBigInt(json["fee"]), + _lastLedgerSequence = json["last_ledger_sequence"], + _sequence = json["sequence"], + _signer = XRPLSignature.fromJson(json), + _fee = BigintUtils.tryParse(json["fee"]), transactionType = XRPLTransactionType.fromValue(json["transaction_type"]), - networkId = json["network_id"], + _networkId = json["network_id"], ticketSequance = json["ticket_sequence"], sourceTag = json["source_tag"], accountTxId = json["account_txn_id"], - memos = - (json["memos"] as List?)?.map((e) => XRPLMemo.fromJson(e)).toList(), - signers = (json["signers"] as List?) - ?.map((e) => XRPLSigners.fromJson(e)) - .toList(); - int _getFlags() { - if (flags == null) return 0; - if (flags is int) return flags; - if (flags is FlagsInterface) return (flags as FlagsInterface).id; - return _getFlagFromList(flags); - } - - int _getFlagFromList(List f) { - final f = (flags as List).map((e) { - if (e is int) return e; - if (e is FlagsInterface) return e.id; - throw ArgumentError( - "flags must be int, List, FlagsInterface or List"); - }); - if (f.isEmpty) return 0; - int accumulator = 0; - for (int i in f) { - accumulator |= i; - } - return accumulator; - } + memos = List.unmodifiable((json["memos"] as List?) + ?.map((e) => XRPLMemo.fromJson(e)) + .toList() ?? + []), + _multisigSigners = List.unmodifiable( + (json["signers"] as List?) + ?.map((e) => XRPLSigners.fromJson(e)) + .toList() ?? + []); /// Converts the object to a JSON representation. @override Map toJson() { Map json = { "account": account, - "flags": _getFlags(), - "signing_pub_key": signingPubKey, + "flags": flags, + "signing_pub_key": signer?.signingPubKey ?? "", "last_ledger_sequence": lastLedgerSequence, "sequence": sequence, - "txn_signature": txnSignature, + "txn_signature": signer?.signature, "fee": fee?.toString(), "transaction_type": transactionType.value, "network_id": networkId, "ticket_sequence": ticketSequance, "source_tag": sourceTag, "account_txn_id": accountTxId, - "signers": (signers?.isEmpty ?? true) - ? null - : signers!.map((e) => e.toJson()).toList(), - "memos": (memos?.isEmpty ?? true) - ? null - : memos!.map((e) => e.toJson()).toList() + "signers": null, + "memos": (memos.isEmpty) ? null : memos.map((e) => e.toJson()).toList() }; + if (_multisigSigners.isNotEmpty) { + final allReady = multisigSigners.every((element) => element.isReady); + if (allReady) { + json["signers"] = _multisigSigners.map((e) => e.toJson()).toList(); + } + } return json; } @@ -257,34 +299,31 @@ class XRPTransaction extends XRPLBase { Map toXrpl() { final isValid = validate; if (isValid != null) { - throw ArgumentError(isValid); + throw XRPLTransactionException(isValid); } - final toJs = toJson(); - toJs.removeWhere((key, value) => value == null); + final toJs = toJson()..removeWhere((key, value) => value == null); return _TransactionUtils._transactionJsonToBinaryCodecForm(toJs); } String toBlob({bool forSigning = true}) { if (forSigning) { - if (signingPubKey.isEmpty && multiSigSigners.isEmpty) { - throw ArgumentError( - "Invalid public key. Set the signing public key (signingPubKey) or provide multi-signature signers (multiSigSigners) for multi-signature transactions."); + if (isMultisig) { + throw XRPLTransactionException( + "use toMultisigBlob for multisign transaction."); } if (ticketSequance != null && sequence != 0) { - throw ArgumentError( + throw XRPLTransactionException( "Set the sequence to 0 when using the ticketSequence"); } if (fee == null) { - throw ArgumentError("invalid transaction fee"); + throw XRPLTransactionException("invalid transaction fee"); } } final result = STObject.fromValue(toXrpl(), forSigning).toBytes(); if (forSigning) { - return BytesUtils.toHexString([ - ...BytesUtils.fromHexString( - _TransactionUtils._transactionSignaturePrefix), - ...result - ], lowerCase: false); + return BytesUtils.toHexString( + [..._TransactionUtils._transactionSignaturePrefix, ...result], + lowerCase: false); } return BytesUtils.toHexString(result, lowerCase: false); } @@ -293,15 +332,18 @@ class XRPTransaction extends XRPLBase { final result = STObject.fromValue(toXrpl(), true).toBytes(); final accountIdBytes = AccountID.fromValue(address).toBytes(); return BytesUtils.toHexString([ - ...BytesUtils.fromHexString(_TransactionUtils._transactionMultisigPrefix), + ..._TransactionUtils._transactionMultisigPrefix, ...result, ...accountIdBytes ], lowerCase: false); } String getHash() { - if (txnSignature == null && (signers?.isEmpty ?? true)) { - throw ArgumentError("Cannot get the hash from an unsigned Transaction."); + if (!(signer?.isReady ?? false) && + (_multisigSigners.isEmpty || + _multisigSigners.any((element) => !element.isReady))) { + throw XRPLTransactionException( + "Cannot get the hash from an unsigned Transaction."); } final encodeStr = "${_TransactionUtils._transactionHashPrefix}${toBlob(forSigning: false)}"; @@ -313,16 +355,16 @@ class XRPTransaction extends XRPLBase { } bool isSigned() { - if (signers != null) { - for (final signer in signers!) { - if ((signer.signingPubKey.isEmpty) || (signer.txnSignature.isEmpty)) { + if (_multisigSigners.isNotEmpty) { + for (final signer in _multisigSigners) { + if (!signer.isReady) { return false; } } return true; } - return (signingPubKey.isNotEmpty) && (txnSignature?.isNotEmpty ?? false); + return signer?.isReady ?? false; } factory XRPTransaction.fromBlob(String hexBlob) { @@ -424,6 +466,7 @@ XRPTransaction _findTransactionObject(Map json) { case XRPLTransactionType.xChainAddClaimAttestation: return XChainAddClaimAttestation.fromJson(json); default: - throw ArgumentError("Invalid Transaction ${json["transaction_type"]}"); + throw XRPLTransactionException( + "Invalid Transaction ${json["transaction_type"]}"); } } diff --git a/lib/src/xrpl/models/check/check_cancel.dart b/lib/src/xrpl/models/check/check_cancel.dart index d733a8e..99653b6 100644 --- a/lib/src/xrpl/models/check/check_cancel.dart +++ b/lib/src/xrpl/models/check/check_cancel.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Represents a CheckCancel [https://xrpl.org/checkcancel.html](https://xrpl.org/checkcancel.html) transaction, /// which cancels an unredeemed Check, removing it from the ledger @@ -9,31 +10,29 @@ class CheckCancel extends XRPTransaction { /// [checkId] The ID of the Check ledger object. to cash, as a 64-character final String checkId; - CheckCancel( - {required String account, - required this.checkId, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + CheckCancel({ + required String account, + required this.checkId, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.checkCancel); /// Converts the object to a JSON representation. diff --git a/lib/src/xrpl/models/check/check_cash.dart b/lib/src/xrpl/models/check/check_cash.dart index a68edd1..748c04d 100644 --- a/lib/src/xrpl/models/check/check_cash.dart +++ b/lib/src/xrpl/models/check/check_cash.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Represents a CheckCash transaction [https://xrpl.org/checkcash.html](https://xrpl.org/checkcash.html), /// which redeems a Check object to receive up to the amount authorized by the @@ -19,33 +20,31 @@ class CheckCash extends XRPTransaction { /// CheckCreate transaction. You must provide either this field or Amount. final CurrencyAmount? deliverMin; - CheckCash( - {required String account, - required this.checkId, - this.amount, - this.deliverMin, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + CheckCash({ + required String account, + required this.checkId, + this.amount, + this.deliverMin, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.checkCash); @override diff --git a/lib/src/xrpl/models/check/check_create.dart b/lib/src/xrpl/models/check/check_create.dart index 9ab8625..241e7eb 100644 --- a/lib/src/xrpl/models/check/check_create.dart +++ b/lib/src/xrpl/models/check/check_create.dart @@ -1,5 +1,6 @@ import 'package:xrpl_dart/src/utility/helper.dart'; import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Represents a CheckCreate [https://xrpl.org/checkcreate.html](https://xrpl.org/checkcreate.html) transaction, /// which creates a Check object. A Check object is a deferred payment @@ -26,35 +27,33 @@ class CheckCreate extends XRPTransaction { /// this Check. final String? invoiceId; - CheckCreate( - {required String account, - required this.destination, - required this.sendMax, - this.destinationTag, - DateTime? expirationTime, - this.invoiceId, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + CheckCreate({ + required String account, + required this.destination, + required this.sendMax, + this.destinationTag, + DateTime? expirationTime, + this.invoiceId, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.checkCreate) { if (expirationTime != null) { expiration = XRPHelper.datetimeToRippleTime(expirationTime); diff --git a/lib/src/xrpl/models/clawback/clawback.dart b/lib/src/xrpl/models/clawback/clawback.dart index 5dea285..8dd07f9 100644 --- a/lib/src/xrpl/models/clawback/clawback.dart +++ b/lib/src/xrpl/models/clawback/clawback.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// The clawback transaction claws back issued funds from token holders. class Clawback extends XRPTransaction { @@ -6,31 +7,29 @@ class Clawback extends XRPTransaction { /// address, from whom the tokens will be clawed back. final IssuedCurrencyAmount amount; - Clawback( - {required String account, - required this.amount, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + Clawback({ + required String account, + required this.amount, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.clawback); @override diff --git a/lib/src/xrpl/models/currencies/currencies.dart b/lib/src/xrpl/models/currencies/currencies.dart index 60bbb78..e2073f1 100644 --- a/lib/src/xrpl/models/currencies/currencies.dart +++ b/lib/src/xrpl/models/currencies/currencies.dart @@ -1,5 +1,4 @@ import 'package:blockchain_utils/blockchain_utils.dart'; -import 'package:xrpl_dart/src/number/number_parser.dart'; import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; /// An abstract class representing different currencies in the XRP Ledger. @@ -176,7 +175,7 @@ class CurrencyAmount { return CurrencyAmount._( null, IssuedCurrencyAmount.fromJson(json as Map)); } - return CurrencyAmount._(parseBigInt(json)!, null); + return CurrencyAmount._(BigintUtils.tryParse(json)!, null); } /// Creates an instance of CurrencyAmount with XRP value. diff --git a/lib/src/xrpl/models/deposit_preauth/deposit_preauth.dart b/lib/src/xrpl/models/deposit_preauth/deposit_preauth.dart index 5e18a87..0ee159e 100644 --- a/lib/src/xrpl/models/deposit_preauth/deposit_preauth.dart +++ b/lib/src/xrpl/models/deposit_preauth/deposit_preauth.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Represents a [DepositPreauth](https://xrpl.org/depositpreauth.html) /// transaction, which gives another account pre-approval to deliver payments to @@ -13,32 +14,30 @@ class DepositPreauth extends XRPTransaction { /// authorize but not both. final String? unauthorize; - DepositPreauth( - {required String account, - this.authorize, - this.unauthorize, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + DepositPreauth({ + required String account, + this.authorize, + this.unauthorize, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.depositPreauth); /// Converts the object to a JSON representation. diff --git a/lib/src/xrpl/models/did/did_delete.dart b/lib/src/xrpl/models/did/did_delete.dart index e8d0439..dd4189d 100644 --- a/lib/src/xrpl/models/did/did_delete.dart +++ b/lib/src/xrpl/models/did/did_delete.dart @@ -1,33 +1,32 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Represents a DIDDelete transaction. class DIDDelete extends XRPTransaction { DIDDelete.fromJson(Map json) : super.json(json); - DIDDelete( - {required String account, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + DIDDelete({ + required String account, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.didDelete); @override diff --git a/lib/src/xrpl/models/did/did_set.dart b/lib/src/xrpl/models/did/did_set.dart index 9bfd5f0..e22fdee 100644 --- a/lib/src/xrpl/models/did/did_set.dart +++ b/lib/src/xrpl/models/did/did_set.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Represents a DIDSet transaction. class DIDSet extends XRPTransaction { @@ -10,33 +11,31 @@ class DIDSet extends XRPTransaction { final String? didDocument; final String? data; final String? uri; - DIDSet( - {required String account, - this.data, - this.uri, - this.didDocument, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + DIDSet({ + required String account, + this.data, + this.uri, + this.didDocument, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.didSet); @override diff --git a/lib/src/xrpl/models/escrow_create/escrow_cancel.dart b/lib/src/xrpl/models/escrow_create/escrow_cancel.dart index 22e964a..a87e8af 100644 --- a/lib/src/xrpl/models/escrow_create/escrow_cancel.dart +++ b/lib/src/xrpl/models/escrow_create/escrow_cancel.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Represents an [EscrowCancel](https://xrpl.org/escrowcancel.html) /// transaction, which returns escrowed XRP to the sender after the Escrow has @@ -10,32 +11,30 @@ class EscrowCancel extends XRPTransaction { /// [offerSequence] Transaction sequence (or Ticket number) of the EscrowCreate transaction that created the Escrow. final int offerSequence; - EscrowCancel( - {required String account, - required this.owner, - required this.offerSequence, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + EscrowCancel({ + required String account, + required this.owner, + required this.offerSequence, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.escrowCancel); /// Converts the object to a JSON representation. diff --git a/lib/src/xrpl/models/escrow_create/escrow_create.dart b/lib/src/xrpl/models/escrow_create/escrow_create.dart index 51fb73f..911a48c 100644 --- a/lib/src/xrpl/models/escrow_create/escrow_create.dart +++ b/lib/src/xrpl/models/escrow_create/escrow_create.dart @@ -1,6 +1,7 @@ -import 'package:xrpl_dart/src/number/number_parser.dart'; +import 'package:blockchain_utils/numbers/numbers.dart'; import 'package:xrpl_dart/src/utility/helper.dart'; import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Represents an [EscrowCreate](https://xrpl.org/escrowcreate.html) /// transaction, which locks up XRP until a specific time or condition is met. @@ -43,7 +44,7 @@ class EscrowCreate extends XRPTransaction { } EscrowCreate.fromJson(Map json) - : amount = parseBigInt(json["amount"])!, + : amount = BigintUtils.tryParse(json["amount"])!, destination = json["destination"], destinationTag = json["destination_tag"], cancelAfter = json["cancel_after"], @@ -51,36 +52,34 @@ class EscrowCreate extends XRPTransaction { condition = json["condition"], super.json(json); - EscrowCreate( - {required String account, - required this.amount, - required this.destination, - DateTime? cancelAfterTime, - DateTime? finishAfterTime, - this.condition, - this.destinationTag, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + EscrowCreate({ + required String account, + required this.amount, + required this.destination, + DateTime? cancelAfterTime, + DateTime? finishAfterTime, + this.condition, + this.destinationTag, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.escrowCreate) { if (cancelAfterTime != null) { cancelAfter = XRPHelper.datetimeToRippleTime(cancelAfterTime); diff --git a/lib/src/xrpl/models/escrow_create/escrow_finish.dart b/lib/src/xrpl/models/escrow_create/escrow_finish.dart index 2e8e080..afe2886 100644 --- a/lib/src/xrpl/models/escrow_create/escrow_finish.dart +++ b/lib/src/xrpl/models/escrow_create/escrow_finish.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Represents an [EscrowFinish](https://xrpl.org/escrowfinish.html) /// transaction, delivers XRP from a held payment to the recipient. @@ -17,34 +18,32 @@ class EscrowFinish extends XRPTransaction { /// of the Escrow, if any, as hexadecimal. final String? fulfillment; - EscrowFinish( - {required String account, - required this.owner, - required this.offerSequence, - this.condition, - this.fulfillment, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + EscrowFinish({ + required String account, + required this.owner, + required this.offerSequence, + this.condition, + this.fulfillment, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.escrowFinish); @override diff --git a/lib/src/xrpl/models/memo/memo.dart b/lib/src/xrpl/models/memo/memo.dart index cc696e4..bf6f245 100644 --- a/lib/src/xrpl/models/memo/memo.dart +++ b/lib/src/xrpl/models/memo/memo.dart @@ -24,11 +24,12 @@ class XRPLMemo extends XRPLBase { /// Converts the object to a JSON representation. @override Map toJson() { - final Map json = {}; - XRPLBase.addWhenNotNull(json, "memo_data", memoData); - XRPLBase.addWhenNotNull(json, "memo_format", memoFormat); - XRPLBase.addWhenNotNull(json, "memo_type", memoType); - return {"memo": json}; + final Map json = { + "memo_data": memoData, + "memo_format": memoFormat, + "memo_type": memoType + }; + return {"memo": json..removeWhere((key, value) => value == null)}; } @override diff --git a/lib/src/xrpl/models/nft/nft_accept_offer.dart b/lib/src/xrpl/models/nft/nft_accept_offer.dart index fb1dfd0..6e69951 100644 --- a/lib/src/xrpl/models/nft/nft_accept_offer.dart +++ b/lib/src/xrpl/models/nft/nft_accept_offer.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// The NFTokenOfferAccept transaction is used to accept offers /// to buy or sell an NFToken. It can either: @@ -46,33 +47,31 @@ class NFTokenAcceptOffer extends XRPTransaction { /// and NFTokenSellOffer must both specify the same TokenID; that is, /// both must be for the same NFToken. final CurrencyAmount? nfTokenBrokerFee; - NFTokenAcceptOffer( - {required String account, - this.nfTokenBrokerFee, - this.nfTokenBuyOffer, - this.nfTokenSellOffer, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + NFTokenAcceptOffer({ + required String account, + this.nfTokenBrokerFee, + this.nfTokenBuyOffer, + this.nfTokenSellOffer, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.nftokenAcceptOffer); @override diff --git a/lib/src/xrpl/models/nft/nft_token_burn.dart b/lib/src/xrpl/models/nft/nft_token_burn.dart index fc73a00..5f90a55 100644 --- a/lib/src/xrpl/models/nft/nft_token_burn.dart +++ b/lib/src/xrpl/models/nft/nft_token_burn.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// The NFTokenBurn transaction is used to remove an NFToken object from the /// NFTokenPage in which it is being held, effectively removing the token from @@ -22,27 +23,25 @@ class NFTokenBurn extends XRPTransaction { required this.nfTokenId, this.owner, List? memos = const [], - String signingPubKey = "", + XRPLSignature? signer, int? ticketSequance, BigInt? fee, int? lastLedgerSequence, int? sequence, - List? signers, - dynamic flags, + List? multisigSigners, + int? flags, int? sourceTag, - List multiSigSigners = const [], }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.nftokenBurn); /// Converts the object to a JSON representation. diff --git a/lib/src/xrpl/models/nft/nft_token_cancel_offer.dart b/lib/src/xrpl/models/nft/nft_token_cancel_offer.dart index 19f8057..f32be5d 100644 --- a/lib/src/xrpl/models/nft/nft_token_cancel_offer.dart +++ b/lib/src/xrpl/models/nft/nft_token_cancel_offer.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// The NFTokenCancelOffer transaction deletes existing NFTokenOffer objects. /// It is useful if you want to free up space on your account to lower your @@ -17,31 +18,29 @@ class NFTokenCancelOffer extends XRPTransaction { /// object that is not an NFTokenOffer object. It is not an /// error if an entry in this list points to an object that /// does not exist. This field is required. - NFTokenCancelOffer( - {required this.nftokenOffers, - required String account, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + NFTokenCancelOffer({ + required this.nftokenOffers, + required String account, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.nftokenCancelOffer); @override diff --git a/lib/src/xrpl/models/nft/nft_token_mint.dart b/lib/src/xrpl/models/nft/nft_token_mint.dart index cb7c7eb..14c60f3 100644 --- a/lib/src/xrpl/models/nft/nft_token_mint.dart +++ b/lib/src/xrpl/models/nft/nft_token_mint.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; class NFTTokenConst { static const int maxUriLength = 512; @@ -88,34 +89,32 @@ class NFTokenMint extends XRPTransaction { /// This field must be hex-encoded. You can use xrpl.utils.str_to_hex to /// convert a UTF-8 string to hex. final String? uri; - NFTokenMint( - {required this.nftokenTaxon, - required String account, - this.issuer, - this.transferFee, - this.uri, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + NFTokenMint({ + required this.nftokenTaxon, + required String account, + this.issuer, + this.transferFee, + this.uri, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.nftokenMint); @override diff --git a/lib/src/xrpl/models/nft/ntf_token_offer.dart b/lib/src/xrpl/models/nft/ntf_token_offer.dart index b587642..9ab59ff 100644 --- a/lib/src/xrpl/models/nft/ntf_token_offer.dart +++ b/lib/src/xrpl/models/nft/ntf_token_offer.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Transaction Flags for an NFTokenCreateOffer Transaction. class NftTokenCreateOfferFlag implements FlagsInterface { @@ -57,35 +58,33 @@ class NFTokenCreateOffer extends XRPTransaction { /// accepted by the specified account. Attempts by other /// accounts to accept this offer MUST fail. final String? destination; - NFTokenCreateOffer( - {required this.nftokenId, - required this.amount, - required String account, - this.owner, - this.expiration, - this.destination, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + NFTokenCreateOffer({ + required this.nftokenId, + required this.amount, + required String account, + this.owner, + this.expiration, + this.destination, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.nftokenCreateOffer); @override String? get validate { diff --git a/lib/src/xrpl/models/offer/offer_cancel.dart b/lib/src/xrpl/models/offer/offer_cancel.dart index d253259..fbade6f 100644 --- a/lib/src/xrpl/models/offer/offer_cancel.dart +++ b/lib/src/xrpl/models/offer/offer_cancel.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// import 'package:xrpl_dart/src/xrpl/utilities.dart'; /// Represents an [OfferCancel](https://xrpl.org/offercancel.html) transaction, @@ -10,31 +11,29 @@ class OfferCancel extends XRPTransaction { /// specified does not exist. final int offerSequence; - OfferCancel( - {required String account, - required this.offerSequence, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + OfferCancel({ + required String account, + required this.offerSequence, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.offerCancel); /// Converts the object to a JSON representation. diff --git a/lib/src/xrpl/models/offer/offer_create.dart b/lib/src/xrpl/models/offer/offer_create.dart index d7a2f50..d88f10a 100644 --- a/lib/src/xrpl/models/offer/offer_create.dart +++ b/lib/src/xrpl/models/offer/offer_create.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Transactions of the OfferCreate type support additional values in the Flags field. /// This enum represents those options. @@ -61,34 +62,32 @@ class OfferCreate extends XRPTransaction { /// [offerSequence] The Sequence number (or Ticket number) of a previous OfferCreate to cancel when placing this Offer final int? offerSequence; - OfferCreate( - {required String account, - required this.takerGets, - required this.takerPays, - this.expiration, - this.offerSequence, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + OfferCreate({ + required String account, + required this.takerGets, + required this.takerPays, + this.expiration, + this.offerSequence, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.offerCreate); /// Converts the object to a JSON representation. diff --git a/lib/src/xrpl/models/path/path.dart b/lib/src/xrpl/models/path/path.dart index 7e4f56e..8d802ae 100644 --- a/lib/src/xrpl/models/path/path.dart +++ b/lib/src/xrpl/models/path/path.dart @@ -18,13 +18,13 @@ class PathStep extends XRPLBase { /// Converts the object to a JSON representation. @override Map toJson() { - final Map json = {}; - XRPLBase.addWhenNotNull(json, "account", account); - XRPLBase.addWhenNotNull(json, "currency", currency); - XRPLBase.addWhenNotNull(json, "issuer", issuer); - XRPLBase.addWhenNotNull(json, "type", type); - XRPLBase.addWhenNotNull(json, "type_hex", typeHex); - return json; + return { + if (account != null) "account": account, + if (currency != null) "currency": currency, + if (issuer != null) "issuer": issuer, + if (type != null) "type": type, + if (typeHex != null) "type_hex": typeHex + }; } PathStep.fromJson(Map json) diff --git a/lib/src/xrpl/models/payment/payment.dart b/lib/src/xrpl/models/payment/payment.dart index d20e68a..152c88f 100644 --- a/lib/src/xrpl/models/payment/payment.dart +++ b/lib/src/xrpl/models/payment/payment.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Transactions of the Payment type support additional values in the Flags field. /// This enum represents those options. @@ -68,37 +69,35 @@ class Payment extends XRPTransaction { /// [deliverMin] Minimum amount of destination currency this transaction should deliver final String? deliverMin; - Payment( - {required this.amount, - required this.destination, - required String account, - this.destinationTag, - this.invoiceId, - this.paths, - this.sendMax, - this.deliverMin, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + Payment({ + required this.amount, + required this.destination, + required String account, + this.destinationTag, + this.invoiceId, + this.paths, + this.sendMax, + this.deliverMin, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.payment); Payment.fromJson(Map json) diff --git a/lib/src/xrpl/models/payment/trust_set.dart b/lib/src/xrpl/models/payment/trust_set.dart index f10f5b4..b23de7c 100644 --- a/lib/src/xrpl/models/payment/trust_set.dart +++ b/lib/src/xrpl/models/payment/trust_set.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Transactions of the TrustSet type support additional values in the Flags field. /// This enum represents those options. @@ -50,33 +51,31 @@ class TrustSetFlag implements FlagsInterface { /// Creates or modifies a trust line linking two accounts. /// See [TrustSet](https://xrpl.org/trustset.html) class TrustSet extends XRPTransaction { - TrustSet( - {required String account, - required this.limitAmount, - this.qualityIn, - this.qualityOut, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + TrustSet({ + required String account, + required this.limitAmount, + this.qualityIn, + this.qualityOut, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.trustSet); final IssuedCurrencyAmount limitAmount; final int? qualityIn; diff --git a/lib/src/xrpl/models/payment_channel/payment_channel_claim.dart b/lib/src/xrpl/models/payment_channel/payment_channel_claim.dart index 16d0ec6..d189209 100644 --- a/lib/src/xrpl/models/payment_channel/payment_channel_claim.dart +++ b/lib/src/xrpl/models/payment_channel/payment_channel_claim.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/blockchain_utils.dart'; -import 'package:xrpl_dart/src/number/number_parser.dart'; import 'package:xrpl_dart/src/xrpl/bytes/serializer.dart'; import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; class PaymentChannelClaimFlag implements FlagsInterface { // Renew the payment channel. @@ -58,35 +58,33 @@ class PaymentChannelClaim extends XRPTransaction { /// Required if signature is provided. final String? publicKey; - PaymentChannelClaim( - {required String account, - required this.channel, - this.balance, - this.amount, - this.signature, - this.publicKey, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + PaymentChannelClaim({ + required String account, + required this.channel, + this.balance, + this.amount, + this.signature, + this.publicKey, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.paymentChannelClaim); /// Converts the object to a JSON representation. @@ -103,8 +101,8 @@ class PaymentChannelClaim extends XRPTransaction { } PaymentChannelClaim.fromJson(Map json) - : amount = parseBigInt(json["amount"]), - balance = parseBigInt(json["balance"]), + : amount = BigintUtils.tryParse(json["amount"]), + balance = BigintUtils.tryParse(json["balance"]), channel = json["channel"], publicKey = json["public_key"], signature = json["signature"], diff --git a/lib/src/xrpl/models/payment_channel/payment_channel_create.dart b/lib/src/xrpl/models/payment_channel/payment_channel_create.dart index a64fd04..38bd725 100644 --- a/lib/src/xrpl/models/payment_channel/payment_channel_create.dart +++ b/lib/src/xrpl/models/payment_channel/payment_channel_create.dart @@ -1,6 +1,7 @@ -import 'package:xrpl_dart/src/number/number_parser.dart'; +import 'package:blockchain_utils/numbers/numbers.dart'; import 'package:xrpl_dart/src/utility/helper.dart'; import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Represents a [PaymentChannelCreate](https://xrpl.org/paymentchannelcreate.html) /// transaction, which creates a [payment channel](https://xrpl.org/payment-channels.html) and funds it with @@ -29,36 +30,34 @@ class PaymentChannelCreate extends XRPTransaction { late final int? cancelAfter; final int? destinationTag; - PaymentChannelCreate( - {required String account, - required this.amount, - required this.destination, - required this.settleDelay, - required this.publicKey, - DateTime? cancelAfterTime, - this.destinationTag, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + PaymentChannelCreate({ + required String account, + required this.amount, + required this.destination, + required this.settleDelay, + required this.publicKey, + DateTime? cancelAfterTime, + this.destinationTag, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.paymentChannelCreate) { if (cancelAfterTime != null) { cancelAfter = XRPHelper.datetimeToRippleTime(cancelAfterTime); @@ -82,7 +81,7 @@ class PaymentChannelCreate extends XRPTransaction { } PaymentChannelCreate.fromJson(Map json) - : amount = parseBigInt(json["amount"])!, + : amount = BigintUtils.tryParse(json["amount"])!, cancelAfter = json["cancel_after"], destination = json["destination"], destinationTag = json["destination_tag"], diff --git a/lib/src/xrpl/models/payment_channel/payment_channel_fund.dart b/lib/src/xrpl/models/payment_channel/payment_channel_fund.dart index f3d768d..2e22aed 100644 --- a/lib/src/xrpl/models/payment_channel/payment_channel_fund.dart +++ b/lib/src/xrpl/models/payment_channel/payment_channel_fund.dart @@ -1,6 +1,7 @@ -import 'package:xrpl_dart/src/number/number_parser.dart'; +import 'package:blockchain_utils/numbers/numbers.dart'; import 'package:xrpl_dart/src/utility/helper.dart'; import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Represents a [PaymentChannelFund](https://xrpl.org/paymentchannelfund.html) /// transaction, adds additional XRP to an open [payment channel](https://xrpl.org/payment-channels.html) @@ -20,33 +21,31 @@ class PaymentChannelFund extends XRPTransaction { /// This is separate from the immutable cancel_after time. late final int? expiration; - PaymentChannelFund( - {required String account, - required this.channel, - required this.amount, - DateTime? expirationTime, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + PaymentChannelFund({ + required String account, + required this.channel, + required this.amount, + DateTime? expirationTime, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.paymentChannelFund) { if (expirationTime != null) { expiration = XRPHelper.datetimeToRippleTime(expirationTime); @@ -68,7 +67,7 @@ class PaymentChannelFund extends XRPTransaction { PaymentChannelFund.fromJson(Map json) : channel = json["channel"], - amount = parseBigInt(json["amount"])!, + amount = BigintUtils.tryParse(json["amount"])!, expiration = json["expiration"], super.json(json); } diff --git a/lib/src/xrpl/models/signer_list/signer_list.dart b/lib/src/xrpl/models/signer_list/signer_list.dart index 2221995..69c9f6a 100644 --- a/lib/src/xrpl/models/signer_list/signer_list.dart +++ b/lib/src/xrpl/models/signer_list/signer_list.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Represents one entry in a list of multi-signers authorized to an account. class SignerEntry extends XRPLBase { @@ -20,12 +21,13 @@ class SignerEntry extends XRPLBase { /// Converts the object to a JSON representation. @override Map toJson() { - final Map json = { - "account": account, - "signer_weight": signerWeight, + return { + "signer_entry": { + "account": account, + "signer_weight": signerWeight, + if (walletLocator != null) "wallet_locator": walletLocator + } }; - XRPLBase.addWhenNotNull(json, "wallet_locator", walletLocator); - return {"signer_entry": json}; } } @@ -38,32 +40,30 @@ class SignerListSet extends XRPTransaction { final int signerQuorum; final List? signerEntries; - SignerListSet( - {required String account, - required this.signerQuorum, - this.signerEntries, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + SignerListSet({ + required String account, + required this.signerQuorum, + this.signerEntries, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.signerListSet); /// Converts the object to a JSON representation. diff --git a/lib/src/xrpl/models/ticket/ticket_create.dart b/lib/src/xrpl/models/ticket/ticket_create.dart index 86f152a..25035de 100644 --- a/lib/src/xrpl/models/ticket/ticket_create.dart +++ b/lib/src/xrpl/models/ticket/ticket_create.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// A TicketCreate transaction sets aside one or more [sequence numbers](https://xrpl.org/basic-data-types.html#account-sequence) /// as [Tickets](https://xrpl.org/tickets.html). @@ -8,31 +9,29 @@ class TicketCreate extends XRPTransaction { /// :meta hide-value: final int ticketCount; - TicketCreate( - {required String account, - required this.ticketCount, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + TicketCreate({ + required String account, + required this.ticketCount, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.ticketCreate); /// Converts the object to a JSON representation. diff --git a/lib/src/xrpl/models/xchain/xchain_account_create_commit.dart b/lib/src/xrpl/models/xchain/xchain_account_create_commit.dart index c59cdb7..c121bc6 100644 --- a/lib/src/xrpl/models/xchain/xchain_account_create_commit.dart +++ b/lib/src/xrpl/models/xchain/xchain_account_create_commit.dart @@ -1,5 +1,6 @@ -import 'package:xrpl_dart/src/number/number_parser.dart'; +import 'package:blockchain_utils/numbers/numbers.dart'; import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Represents a XChainAccountCreateCommit transaction on the XRP Ledger. /// The XChainAccountCreateCommit transaction creates a new account on one of @@ -8,9 +9,9 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; class XChainAccountCreateCommit extends XRPTransaction { XChainAccountCreateCommit.fromJson(Map json) : xchainBridge = XChainBridge.fromJson(json["xchain_bridge"]), - amount = parseBigInt(json["amount"])!, + amount = BigintUtils.tryParse(json["amount"])!, destination = json["destination"], - signatureReward = parseBigInt(json["signature_reward"])!, + signatureReward = BigintUtils.tryParse(json["signature_reward"])!, super.json(json); /// The bridge to create accounts for. This field is required. @@ -29,34 +30,32 @@ class XChainAccountCreateCommit extends XRPTransaction { /// field is required. final BigInt signatureReward; - XChainAccountCreateCommit( - {required String account, - required this.xchainBridge, - required this.destination, - required this.amount, - required this.signatureReward, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + XChainAccountCreateCommit({ + required String account, + required this.xchainBridge, + required this.destination, + required this.amount, + required this.signatureReward, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.xChainAccountCreateCommit); @override diff --git a/lib/src/xrpl/models/xchain/xchain_add_account_create_attestation.dart b/lib/src/xrpl/models/xchain/xchain_add_account_create_attestation.dart index 4d6eadc..44d2516 100644 --- a/lib/src/xrpl/models/xchain/xchain_add_account_create_attestation.dart +++ b/lib/src/xrpl/models/xchain/xchain_add_account_create_attestation.dart @@ -1,5 +1,6 @@ -import 'package:xrpl_dart/src/number/number_parser.dart'; +import 'package:blockchain_utils/numbers/numbers.dart'; import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Represents a XChainAddAccountCreateAttestation transaction. /// The XChainAddAccountCreateAttestation transaction provides an attestation @@ -8,7 +9,7 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; class XChainAddAccountCreateAttestation extends XRPTransaction { XChainAddAccountCreateAttestation.fromJson(Map json) : xchainBridge = XChainBridge.fromJson(json["xchain_bridge"]), - amount = parseBigInt(json["amount"])!, + amount = BigintUtils.tryParse(json["amount"])!, destination = json["destination"], signature = json["signature"], publicKey = json["public_key"], @@ -18,7 +19,7 @@ class XChainAddAccountCreateAttestation extends XRPTransaction { wasLockingChainSend = json["was_locking_chain_send"] == 0 ? false : true, xChainAccountCreateCount = json["xchain_account_create_count"], - signatureReward = parseBigInt(json["signature_reward"])!, + signatureReward = BigintUtils.tryParse(json["signature_reward"])!, super.json(json); /// The bridge associated with the attestation. This field is required. @@ -64,41 +65,39 @@ class XChainAddAccountCreateAttestation extends XRPTransaction { /// This field is required. final BigInt signatureReward; - XChainAddAccountCreateAttestation( - {required String account, - required this.xchainBridge, - required this.destination, - required this.signature, - required this.otherChainSource, - required this.publicKey, - required this.wasLockingChainSend, - required this.attestationRewardAccount, - required this.attestationSignerAccount, - required this.amount, - required this.signatureReward, - required this.xChainAccountCreateCount, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + XChainAddAccountCreateAttestation({ + required String account, + required this.xchainBridge, + required this.destination, + required this.signature, + required this.otherChainSource, + required this.publicKey, + required this.wasLockingChainSend, + required this.attestationRewardAccount, + required this.attestationSignerAccount, + required this.amount, + required this.signatureReward, + required this.xChainAccountCreateCount, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.xChainAddAccountCreateAttestation); diff --git a/lib/src/xrpl/models/xchain/xchain_add_claim_attestation.dart b/lib/src/xrpl/models/xchain/xchain_add_claim_attestation.dart index f500309..778af3c 100644 --- a/lib/src/xrpl/models/xchain/xchain_add_claim_attestation.dart +++ b/lib/src/xrpl/models/xchain/xchain_add_claim_attestation.dart @@ -1,5 +1,6 @@ -import 'package:xrpl_dart/src/number/number_parser.dart'; +import 'package:blockchain_utils/numbers/numbers.dart'; import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Represents a XChainAddClaimAttestation transaction. /// The XChainAddClaimAttestation transaction provides proof from a witness @@ -8,7 +9,7 @@ class XChainAddClaimAttestation extends XRPTransaction { XChainAddClaimAttestation.fromJson(Map json) : xchainBridge = XChainBridge.fromJson(json["xchain_bridge"]), xchainClaimId = json["xchain_claim_id"], - amount = parseBigInt(json["amount"])!, + amount = BigintUtils.tryParse(json["amount"])!, destination = json["destination"], signature = json["signature"], publicKey = json["public_key"], @@ -58,40 +59,38 @@ class XChainAddClaimAttestation extends XRPTransaction { /// the XChainCommit transaction). final String? destination; - XChainAddClaimAttestation( - {required String account, - required this.xchainBridge, - required this.xchainClaimId, - required this.destination, - required this.signature, - required this.otherChainSource, - required this.publicKey, - required this.wasLockingChainSend, - required this.attestationRewardAccount, - required this.attestationSignerAccount, - required this.amount, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + XChainAddClaimAttestation({ + required String account, + required this.xchainBridge, + required this.xchainClaimId, + required this.destination, + required this.signature, + required this.otherChainSource, + required this.publicKey, + required this.wasLockingChainSend, + required this.attestationRewardAccount, + required this.attestationSignerAccount, + required this.amount, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.xChainAddClaimAttestation); @override diff --git a/lib/src/xrpl/models/xchain/xchain_claim.dart b/lib/src/xrpl/models/xchain/xchain_claim.dart index 112a239..5fbae8a 100644 --- a/lib/src/xrpl/models/xchain/xchain_claim.dart +++ b/lib/src/xrpl/models/xchain/xchain_claim.dart @@ -1,4 +1,5 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Represents a XChainClaim transaction. /// The XChainClaim transaction completes a cross-chain transfer of value. @@ -35,35 +36,33 @@ class XChainClaim extends XRPTransaction { /// This field is required. final CurrencyAmount amount; - XChainClaim( - {required String account, - required this.xchainBridge, - required this.xchainClaimId, - required this.destination, - this.destinationTag, - required this.amount, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + XChainClaim({ + required String account, + required this.xchainBridge, + required this.xchainClaimId, + required this.destination, + this.destinationTag, + required this.amount, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.xChainClaim); @override diff --git a/lib/src/xrpl/models/xchain/xchain_commit.dart b/lib/src/xrpl/models/xchain/xchain_commit.dart index bd64d7a..99b64ea 100644 --- a/lib/src/xrpl/models/xchain/xchain_commit.dart +++ b/lib/src/xrpl/models/xchain/xchain_commit.dart @@ -1,5 +1,6 @@ -import 'package:xrpl_dart/src/number/number_parser.dart'; +import 'package:blockchain_utils/numbers/numbers.dart'; import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Represents a XChainCommit transaction. /// The XChainCommit transaction is the second step in a cross-chain @@ -10,7 +11,7 @@ class XChainCommit extends XRPTransaction { XChainCommit.fromJson(Map json) : xchainBridge = XChainBridge.fromJson(json["xchain_bridge"]), xchainClaimId = json["xchain_claim_id"], - amount = parseBigInt(json["amount"])!, + amount = BigintUtils.tryParse(json["amount"])!, otherChainDestination = json["other_chain_destination"], super.json(json); @@ -34,34 +35,32 @@ class XChainCommit extends XRPTransaction { /// destination chain will need to submit a XChainClaim transaction to final String? otherChainDestination; - XChainCommit( - {required String account, - required this.xchainBridge, - required this.xchainClaimId, - this.otherChainDestination, - required this.amount, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + XChainCommit({ + required String account, + required this.xchainBridge, + required this.xchainClaimId, + this.otherChainDestination, + required this.amount, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.xChainCommit); @override diff --git a/lib/src/xrpl/models/xchain/xchain_create_bridge.dart b/lib/src/xrpl/models/xchain/xchain_create_bridge.dart index 25e7e72..eb30d66 100644 --- a/lib/src/xrpl/models/xchain/xchain_create_bridge.dart +++ b/lib/src/xrpl/models/xchain/xchain_create_bridge.dart @@ -1,5 +1,6 @@ -import 'package:xrpl_dart/src/number/number_parser.dart'; +import 'package:blockchain_utils/numbers/numbers.dart'; import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; /// Represents a XChainCreateBridge transaction. /// The XChainCreateBridge transaction creates a new Bridge ledger object and @@ -9,8 +10,9 @@ import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; class XChainCreateBridge extends XRPTransaction { XChainCreateBridge.fromJson(Map json) : xchainBridge = XChainBridge.fromJson(json["xchain_bridge"]), - signatureReward = parseBigInt(json["signature_reward"])!, - minAccountCreateAmount = parseBigInt(json["minAccountCreateAmount"]), + signatureReward = BigintUtils.tryParse(json["signature_reward"])!, + minAccountCreateAmount = + BigintUtils.tryParse(json["minAccountCreateAmount"]), super.json(json); /// The bridge (door accounts and assets) to create. This field is required. @@ -25,33 +27,31 @@ class XChainCreateBridge extends XRPTransaction { /// transaction will fail. This field can only be present on XRP-XRP bridges. final BigInt? minAccountCreateAmount; - XChainCreateBridge( - {required String account, - required this.xchainBridge, - required this.signatureReward, - this.minAccountCreateAmount, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + XChainCreateBridge({ + required String account, + required this.xchainBridge, + required this.signatureReward, + this.minAccountCreateAmount, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.xChainCreateBridge); @override diff --git a/lib/src/xrpl/models/xchain/xchain_create_claim_id.dart b/lib/src/xrpl/models/xchain/xchain_create_claim_id.dart index 8324b9b..9da043e 100644 --- a/lib/src/xrpl/models/xchain/xchain_create_claim_id.dart +++ b/lib/src/xrpl/models/xchain/xchain_create_claim_id.dart @@ -1,10 +1,11 @@ -import 'package:xrpl_dart/src/number/number_parser.dart'; +import 'package:blockchain_utils/numbers/numbers.dart'; import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; class XChainCreateClaimId extends XRPTransaction { XChainCreateClaimId.fromJson(Map json) : xchainBridge = XChainBridge.fromJson(json["xchain_bridge"]), - signatureReward = parseBigInt(json["signature_reward"])!, + signatureReward = BigintUtils.tryParse(json["signature_reward"])!, otherChainSource = json["other_chain_source"], super.json(json); @@ -22,33 +23,31 @@ class XChainCreateClaimId extends XRPTransaction { /// required. final String otherChainSource; - XChainCreateClaimId( - {required String account, - required this.xchainBridge, - required this.signatureReward, - required this.otherChainSource, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + XChainCreateClaimId({ + required String account, + required this.xchainBridge, + required this.signatureReward, + required this.otherChainSource, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.xChainCreateClaimId); @override diff --git a/lib/src/xrpl/models/xchain/xchain_modify_bridge.dart b/lib/src/xrpl/models/xchain/xchain_modify_bridge.dart index 7617ce5..3a6113c 100644 --- a/lib/src/xrpl/models/xchain/xchain_modify_bridge.dart +++ b/lib/src/xrpl/models/xchain/xchain_modify_bridge.dart @@ -1,5 +1,6 @@ -import 'package:xrpl_dart/src/number/number_parser.dart'; +import 'package:blockchain_utils/numbers/numbers.dart'; import 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; +import 'package:xrpl_dart/src/crypto/crypto.dart'; class XChainModifyBridgeFlag implements FlagsInterface { // Transactions of the XChainModifyBridge type support additional values in the Flags @@ -30,8 +31,9 @@ class XChainModifyBridgeFlagInterface { class XChainModifyBridge extends XRPTransaction { XChainModifyBridge.fromJson(Map json) : xchainBridge = XChainBridge.fromJson(json["xchain_bridge"]), - signatureReward = parseBigInt(json["signature_reward"]), - minAccountCreateAmount = parseBigInt(json["min_account_create_amount"]), + signatureReward = BigintUtils.tryParse(json["signature_reward"]), + minAccountCreateAmount = + BigintUtils.tryParse(json["min_account_create_amount"]), super.json(json); /// Represents a XChainModifyBridge transaction. @@ -47,33 +49,31 @@ class XChainModifyBridge extends XRPTransaction { final BigInt? minAccountCreateAmount; // XChainModifyBridge({required String account, required super.transactionType}); - XChainModifyBridge( - {required this.xchainBridge, - this.signatureReward, - this.minAccountCreateAmount, - required String account, - List? memos = const [], - String signingPubKey = "", - int? ticketSequance, - BigInt? fee, - int? lastLedgerSequence, - int? sequence, - List? signers, - dynamic flags, - int? sourceTag, - List multiSigSigners = const []}) - : super( + XChainModifyBridge({ + required this.xchainBridge, + this.signatureReward, + this.minAccountCreateAmount, + required String account, + List? memos = const [], + XRPLSignature? signer, + int? ticketSequance, + BigInt? fee, + int? lastLedgerSequence, + int? sequence, + List? multisigSigners, + int? flags, + int? sourceTag, + }) : super( account: account, fee: fee, lastLedgerSequence: lastLedgerSequence, memos: memos, sequence: sequence, - signers: signers, + multisigSigners: multisigSigners, sourceTag: sourceTag, flags: flags, ticketSequance: ticketSequance, - signingPubKey: signingPubKey, - multiSigSigners: multiSigSigners, + signer: signer, transactionType: XRPLTransactionType.xChainModifyBridge, ); diff --git a/lib/xrpl_dart.dart b/lib/xrpl_dart.dart index c443dfe..463c798 100644 --- a/lib/xrpl_dart.dart +++ b/lib/xrpl_dart.dart @@ -58,8 +58,7 @@ OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /// - Utility functions for managing XRPL data structures. library xrpl_dart; -export 'package:xrpl_dart/src/keypair/xrpl_private_key.dart'; -export 'package:xrpl_dart/src/keypair/xrpl_public_key.dart'; +export 'package:xrpl_dart/src/crypto/crypto.dart'; export 'package:xrpl_dart/src/rpc/rpc.dart'; export 'package:xrpl_dart/src/xrpl/models/xrp_transactions.dart'; export 'package:xrpl_dart/src/xrpl/address/xrpl.dart'; diff --git a/test/fullfillment_test/fulfillment_test.dart b/test/fullfillment_test/fulfillment_test.dart index 4a5e1d2..b3de665 100644 --- a/test/fullfillment_test/fulfillment_test.dart +++ b/test/fullfillment_test/fulfillment_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/binary/binary.dart'; import 'package:test/test.dart'; -import 'package:xrpl_dart/xrpl_dart.dart'; +import 'package:xrpl_dart/src/utility/fulfillment/pre_image/pre_image_sha256.dart'; import 'test_vector.dart'; diff --git a/test/keys_test.dart b/test/keys_test.dart index 4f2d13a..942eb07 100644 --- a/test/keys_test.dart +++ b/test/keys_test.dart @@ -1,5 +1,5 @@ import 'package:test/test.dart'; -import 'package:xrpl_dart/src/keypair/xrpl_private_key.dart'; +import 'package:xrpl_dart/xrpl_dart.dart'; void main() async { test("fromEntropy SECP256K1", () { diff --git a/test/sign_test.dart b/test/sign_test.dart index 70f54ab..184b29e 100644 --- a/test/sign_test.dart +++ b/test/sign_test.dart @@ -1,5 +1,5 @@ import 'package:test/test.dart'; -import 'package:xrpl_dart/src/keypair/xrpl_private_key.dart'; +import 'package:xrpl_dart/xrpl_dart.dart'; void main() { test("TEST", () {