Socket
Socket
Sign inDemoInstall

@cosmjs/stargate

Package Overview
Dependencies
Maintainers
2
Versions
93
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@cosmjs/stargate - npm Package Compare versions

Comparing version 0.25.2 to 0.25.3

11

build/fee.d.ts

@@ -8,2 +8,5 @@ import { StdFee } from "@cosmjs/amino";

/**
* A gas price, i.e. the price of a single unit of gas. This is typically a fraction of
* the smallest fee token unit, such as 0.012utoken.
*
* This is the same as GasPrice from @cosmjs/launchpad but those might diverge in the future.

@@ -15,2 +18,10 @@ */

constructor(amount: Decimal, denom: string);
/**
* Parses a gas price formatted as `<amount><denom>`, e.g. `GasPrice.fromString("0.012utoken")`.
*
* The denom must match the Cosmos SDK 0.42 pattern (https://github.com/cosmos/cosmos-sdk/blob/v0.42.4/types/coin.go#L599-L601).
* See `GasPrice` in @cosmjs/stargate for a more generic matcher.
*
* Separators are not yet supported.
*/
static fromString(gasPrice: string): GasPrice;

@@ -17,0 +28,0 @@ }

31

build/fee.js

@@ -7,2 +7,16 @@ "use strict";

/**
* Denom checker for the Cosmos SDK 0.42 denom pattern
* (https://github.com/cosmos/cosmos-sdk/blob/v0.42.4/types/coin.go#L599-L601).
*
* This is like a regexp but with helpful error messages.
*/
function checkDenom(denom) {
if (denom.length < 3 || denom.length > 128) {
throw new Error("Denom must be between 3 and 128 characters");
}
}
/**
* A gas price, i.e. the price of a single unit of gas. This is typically a fraction of
* the smallest fee token unit, such as 0.012utoken.
*
* This is the same as GasPrice from @cosmjs/launchpad but those might diverge in the future.

@@ -15,11 +29,18 @@ */

}
/**
* Parses a gas price formatted as `<amount><denom>`, e.g. `GasPrice.fromString("0.012utoken")`.
*
* The denom must match the Cosmos SDK 0.42 pattern (https://github.com/cosmos/cosmos-sdk/blob/v0.42.4/types/coin.go#L599-L601).
* See `GasPrice` in @cosmjs/stargate for a more generic matcher.
*
* Separators are not yet supported.
*/
static fromString(gasPrice) {
const matchResult = gasPrice.match(/^(?<amount>.+?)(?<denom>[a-z]+)$/);
// Use Decimal.fromUserInput and checkDenom for detailed checks and helpful error messages
const matchResult = gasPrice.match(/^([0-9.]+)([a-z][a-z0-9]*)$/i);
if (!matchResult) {
throw new Error("Invalid gas price string");
}
const { amount, denom } = matchResult.groups;
if (denom.length < 3 || denom.length > 127) {
throw new Error("Gas price denomination must be between 3 and 127 characters");
}
const [_, amount, denom] = matchResult;
checkDenom(denom);
const fractionalDigits = 18;

@@ -26,0 +47,0 @@ const decimalAmount = math_1.Decimal.fromUserInput(amount, fractionalDigits);

@@ -14,11 +14,42 @@ "use strict";

});
it("can be constructed from a config string", () => {
const inputs = ["3.14", "3", "0.14"];
inputs.forEach((input) => {
const gasPrice = fee_1.GasPrice.fromString(`${input}utest`);
expect(gasPrice.amount.toString()).toEqual(input);
expect(gasPrice.denom).toEqual("utest");
describe("fromString", () => {
it("works", () => {
const inputs = {
// Test amounts
"3.14utest": { amount: "3.14", denom: "utest" },
"3utest": { amount: "3", denom: "utest" },
"0.14utest": { amount: "0.14", denom: "utest" },
// Test denoms
"0.14sht": { amount: "0.14", denom: "sht" },
"0.14testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest": {
amount: "0.14",
denom: "testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest",
},
"0.14ucoin2": { amount: "0.14", denom: "ucoin2" },
// eslint-disable-next-line @typescript-eslint/naming-convention
"0.14FOOBAR": { amount: "0.14", denom: "FOOBAR" },
};
for (const [input, expected] of Object.entries(inputs)) {
const gasPrice = fee_1.GasPrice.fromString(input);
expect(gasPrice.amount.toString()).withContext(`Input: ${input}`).toEqual(expected.amount);
expect(gasPrice.denom).withContext(`Input: ${input}`).toEqual(expected.denom);
}
});
it("errors for invalid gas price", () => {
// Checks basic format <amount><denom>
expect(() => fee_1.GasPrice.fromString("")).toThrowError(/Invalid gas price string/i);
expect(() => fee_1.GasPrice.fromString("utkn")).toThrowError(/Invalid gas price string/i);
expect(() => fee_1.GasPrice.fromString("@utkn")).toThrowError(/Invalid gas price string/i);
expect(() => fee_1.GasPrice.fromString("234")).toThrowError(/Invalid gas price string/i);
expect(() => fee_1.GasPrice.fromString("-234tkn")).toThrowError(/Invalid gas price string/i);
// Checks details of <denom>
expect(() => fee_1.GasPrice.fromString("234t")).toThrowError(/denom must be between 3 and 128 characters/i);
expect(() => fee_1.GasPrice.fromString("234tt")).toThrowError(/denom must be between 3 and 128 characters/i);
expect(() => fee_1.GasPrice.fromString("234ttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt")).toThrowError(/denom must be between 3 and 128 characters/i);
// Checks details of <amount>
expect(() => fee_1.GasPrice.fromString("3.utkn")).toThrowError(/Fractional part missing/i);
expect(() => fee_1.GasPrice.fromString("..utkn")).toThrowError(/More than one separator found/i);
});
});
});
//# sourceMappingURL=fee.spec.js.map

2

build/signingstargateclient.d.ts

@@ -68,3 +68,3 @@ import { StdFee } from "@cosmjs/amino";

protected constructor(tmClient: Tendermint34Client | undefined, signer: OfflineSigner, options: SigningStargateClientOptions);
sendTokens(senderAddress: string, recipientAddress: string, transferAmount: readonly Coin[], memo?: string): Promise<BroadcastTxResponse>;
sendTokens(senderAddress: string, recipientAddress: string, amount: readonly Coin[], memo?: string): Promise<BroadcastTxResponse>;
delegateTokens(delegatorAddress: string, validatorAddress: string, amount: Coin, memo?: string): Promise<BroadcastTxResponse>;

@@ -71,0 +71,0 @@ undelegateTokens(delegatorAddress: string, validatorAddress: string, amount: Coin, memo?: string): Promise<BroadcastTxResponse>;

@@ -95,3 +95,3 @@ "use strict";

}
async sendTokens(senderAddress, recipientAddress, transferAmount, memo = "") {
async sendTokens(senderAddress, recipientAddress, amount, memo = "") {
const sendMsg = {

@@ -102,3 +102,3 @@ typeUrl: "/cosmos.bank.v1beta1.MsgSend",

toAddress: recipientAddress,
amount: [...transferAmount],
amount: [...amount],
},

@@ -105,0 +105,0 @@ };

@@ -263,3 +263,3 @@ "use strict";

const client = await signingstargateclient_1.SigningStargateClient.connectWithSigner(testutils_spec_1.simapp.tendermintUrl, wallet);
const transferAmount = proto_signing_1.coins(7890, "ucosm");
const amount = proto_signing_1.coins(7890, "ucosm");
const beneficiaryAddress = testutils_spec_1.makeRandomAddress();

@@ -274,3 +274,3 @@ const memo = "for dinner";

// send
const result = await client.sendTokens(testutils_spec_1.faucet.address0, beneficiaryAddress, transferAmount, memo);
const result = await client.sendTokens(testutils_spec_1.faucet.address0, beneficiaryAddress, amount, memo);
stargateclient_1.assertIsBroadcastTxSuccess(result);

@@ -280,3 +280,3 @@ expect(result.rawLog).toBeTruthy();

const after = await client.getBalance(beneficiaryAddress, "ucosm");
expect(after).toEqual(transferAmount[0]);
expect(after).toEqual(amount[0]);
});

@@ -287,3 +287,3 @@ it("works with legacy Amino signer", async () => {

const client = await signingstargateclient_1.SigningStargateClient.connectWithSigner(testutils_spec_1.simapp.tendermintUrl, wallet);
const transferAmount = proto_signing_1.coins(7890, "ucosm");
const amount = proto_signing_1.coins(7890, "ucosm");
const beneficiaryAddress = testutils_spec_1.makeRandomAddress();

@@ -298,3 +298,3 @@ const memo = "for dinner";

// send
const result = await client.sendTokens(testutils_spec_1.faucet.address0, beneficiaryAddress, transferAmount, memo);
const result = await client.sendTokens(testutils_spec_1.faucet.address0, beneficiaryAddress, amount, memo);
stargateclient_1.assertIsBroadcastTxSuccess(result);

@@ -304,3 +304,3 @@ expect(result.rawLog).toBeTruthy();

const after = await client.getBalance(beneficiaryAddress, "ucosm");
expect(after).toEqual(transferAmount[0]);
expect(after).toEqual(amount[0]);
});

@@ -307,0 +307,0 @@ });

@@ -79,2 +79,11 @@ import { Tendermint34Client } from "@cosmjs/tendermint-rpc";

}
/**
* The response after successfully broadcasting a transaction.
* Success or failure refer to the execution result.
*
* The name is a bit misleading as this contains the result of the execution
* in a block. Both `BroadcastTxSuccess` and `BroadcastTxFailure` contain a height
* field, which is the height of the block that contains the transaction. This means
* transactions that were never included in a block cannot be expressed with this type.
*/
export declare type BroadcastTxResponse = BroadcastTxSuccess | BroadcastTxFailure;

@@ -118,4 +127,15 @@ export declare function isBroadcastTxFailure(result: BroadcastTxResponse): result is BroadcastTxFailure;

disconnect(): void;
/**
* Broadcasts a signed transaction to the network and monitors its inclusion in a block.
*
* If broadcasting is rejected by the node for some reason (e.g. because of a CheckTx failure),
* an error is thrown.
*
* If the transaction is not included in a block before the provided timeout, this errors with a `TimeoutError`.
*
* If the transaction is included in a block, a `BroadcastTxResponse` is returned. The caller then
* usually needs to check for execution success or failure.
*/
broadcastTx(tx: Uint8Array, timeoutMs?: number, pollIntervalMs?: number): Promise<BroadcastTxResponse>;
private txsQuery;
}

@@ -174,2 +174,13 @@ "use strict";

}
/**
* Broadcasts a signed transaction to the network and monitors its inclusion in a block.
*
* If broadcasting is rejected by the node for some reason (e.g. because of a CheckTx failure),
* an error is thrown.
*
* If the transaction is not included in a block before the provided timeout, this errors with a `TimeoutError`.
*
* If the transaction is included in a block, a `BroadcastTxResponse` is returned. The caller then
* usually needs to check for execution success or failure.
*/
async broadcastTx(tx, timeoutMs = 60000, pollIntervalMs = 3000) {

@@ -197,7 +208,14 @@ let timedOut = false;

};
return new Promise((resolve, reject) => this.forceGetTmClient()
.broadcastTxSync({ tx })
.then(({ hash }) => pollForTx(encoding_1.toHex(hash).toUpperCase()))
.then(resolve, reject)
.finally(() => clearTimeout(txPollTimeout)));
const broadcasted = await this.forceGetTmClient().broadcastTxSync({ tx });
if (broadcasted.code) {
throw new Error(`Broadcasting transaction failed with code ${broadcasted.code} (codespace: ${broadcasted.codeSpace}). Log: ${broadcasted.log}`);
}
const transactionId = encoding_1.toHex(broadcasted.hash).toUpperCase();
return new Promise((resolve, reject) => pollForTx(transactionId).then((value) => {
clearTimeout(txPollTimeout);
resolve(value);
}, (error) => {
clearTimeout(txPollTimeout);
reject(error);
}));
}

@@ -204,0 +222,0 @@ async txsQuery(query) {

@@ -235,8 +235,3 @@ "use strict";

const { accountNumber, sequence } = (await client.getSequence(address));
const feeAmount = [
{
amount: "2000",
denom: "ucosm",
},
];
const feeAmount = proto_signing_1.coins(2000, "ucosm");
const gasLimit = 200000;

@@ -261,2 +256,50 @@ const authInfoBytes = proto_signing_1.makeAuthInfoBytes([pubkey], feeAmount, gasLimit, sequence);

});
it("errors immediately for a CheckTx failure", async () => {
testutils_spec_1.pendingWithoutSimapp();
const client = await stargateclient_1.StargateClient.connect(testutils_spec_1.simapp.tendermintUrl);
const wallet = await proto_signing_1.DirectSecp256k1HdWallet.fromMnemonic(testutils_spec_1.faucet.mnemonic);
const [{ address, pubkey: pubkeyBytes }] = await wallet.getAccounts();
const pubkey = proto_signing_1.encodePubkey({
type: "tendermint/PubKeySecp256k1",
value: encoding_1.toBase64(pubkeyBytes),
});
const registry = new proto_signing_1.Registry();
const invalidRecipientAddress = "tgrade1z363ulwcrxged4z5jswyt5dn5v3lzsemwz9ewj"; // wrong bech32 prefix
const txBodyFields = {
typeUrl: "/cosmos.tx.v1beta1.TxBody",
value: {
messages: [
{
typeUrl: "/cosmos.bank.v1beta1.MsgSend",
value: {
fromAddress: address,
toAddress: invalidRecipientAddress,
amount: [
{
denom: "ucosm",
amount: "1234567",
},
],
},
},
],
},
};
const txBodyBytes = registry.encode(txBodyFields);
const { accountNumber, sequence } = (await client.getSequence(address));
const feeAmount = proto_signing_1.coins(2000, "ucosm");
const gasLimit = 200000;
const authInfoBytes = proto_signing_1.makeAuthInfoBytes([pubkey], feeAmount, gasLimit, sequence);
const chainId = await client.getChainId();
const signDoc = proto_signing_1.makeSignDoc(txBodyBytes, authInfoBytes, chainId, accountNumber);
const { signature } = await wallet.signDirect(address, signDoc);
const txRaw = tx_1.TxRaw.fromPartial({
bodyBytes: txBodyBytes,
authInfoBytes: authInfoBytes,
signatures: [encoding_1.fromBase64(signature.signature)],
});
const txRawBytes = Uint8Array.from(tx_1.TxRaw.encode(txRaw).finish());
await expectAsync(client.broadcastTx(txRawBytes)).toBeRejectedWithError(/invalid recipient address/i);
client.disconnect();
});
it("respects user timeouts rather than RPC timeouts", async () => {

@@ -294,8 +337,3 @@ testutils_spec_1.pendingWithoutSlowSimapp();

const chainId = await client.getChainId();
const feeAmount = [
{
amount: "2000",
denom: "ucosm",
},
];
const feeAmount = proto_signing_1.coins(2000, "ucosm");
const gasLimit = 200000;

@@ -302,0 +340,0 @@ const { accountNumber: accountNumber1, sequence: sequence1 } = (await client.getSequence(address));

{
"name": "@cosmjs/stargate",
"version": "0.25.2",
"version": "0.25.3",
"description": "Utilities for Cosmos SDK 0.40",

@@ -46,13 +46,13 @@ "contributors": [

"@confio/ics23": "^0.6.3",
"@cosmjs/amino": "^0.25.2",
"@cosmjs/encoding": "^0.25.2",
"@cosmjs/math": "^0.25.2",
"@cosmjs/proto-signing": "^0.25.2",
"@cosmjs/stream": "^0.25.2",
"@cosmjs/tendermint-rpc": "^0.25.2",
"@cosmjs/utils": "^0.25.2",
"@cosmjs/amino": "^0.25.3",
"@cosmjs/encoding": "^0.25.3",
"@cosmjs/math": "^0.25.3",
"@cosmjs/proto-signing": "^0.25.3",
"@cosmjs/stream": "^0.25.3",
"@cosmjs/tendermint-rpc": "^0.25.3",
"@cosmjs/utils": "^0.25.3",
"long": "^4.0.0",
"protobufjs": "~6.10.2"
},
"gitHead": "dab008f2f524aab5063fdda3ad510376425dc50a"
"gitHead": "ba7fd927d73ea56f85d8ff841282b88e4baeb718"
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc