Git Product home page Git Product logo

osmojs's Introduction

OsmoJS

OsmosJS makes it easy to compose and broadcast Osmosis and Cosmos messages, with all of the proto and amino encoding handled for you.


install

npm install osmojs

Table of contents

Usage

RPC Clients

import { osmosis } from 'osmojs';

const { createRPCQueryClient } = osmosis.ClientFactory;
const client = await createRPCQueryClient({ rpcEndpoint: RPC_ENDPOINT });

// now you can query the cosmos modules
const balance = await client.cosmos.bank.v1beta1
    .allBalances({ address: 'osmo1addresshere' });

// you can also query the osmosis pools
const response = await client.osmosis.gamm.v1beta1.pools();

** Every RPC endpoint is available! Simply use vscode or another tool to visually explore through autocomplete all of the RPC endpoints available on the RPCQueryClient!

Composing Messages

Import the osmosis object from osmojs.

In this case, we're show the messages available from the osmosis.gamm.v1beta1 module:

import { osmosis } from 'osmojs';

const {
    joinPool,
    exitPool,
    exitSwapExternAmountOut,
    exitSwapShareAmountIn,
    joinSwapExternAmountIn,
    joinSwapShareAmountOut,
    swapExactAmountIn,
    swapExactAmountOut
} = osmosis.gamm.v1beta1.MessageComposer.withTypeUrl;

To see a complete list of messages, see all the messages below.

Now you can construct messages. If you use vscode or another typescript-enabled IDE, you should also be able to use ctrl+space to see auto-completion of the fields required for the message.

import { coin } from '@cosmjs/amino';

const msg = swapExactAmountIn({
  sender,
  routes,
  tokenIn: coin(amount, denom),
  tokenOutMinAmount
});

To calculate the routes and tokenOutMinAmount, you can use @osmonauts/math:

import { getRoutesForTrade, calcAmountWithSlippage } from "@osmonauts/math";

const routes = getRoutesForTrade({
  trade: {
    sell: {
      denom: tokenIn.denom,
      amount: tokenInAmount,
    },
    buy: {
      denom: tokenOut.denom,
      amount: tokenOutAmount,
    },
  },
  pairs,
});

const tokenOutMinAmount = calcAmountWithSlippage(tokenOutAmount, slippage);

For more details, check out the swap-tokens example.

Lockup Messages

import { osmosis } from 'osmojs';
const {
    beginUnlocking,
    beginUnlockingAll,
    lockTokens
} = osmosis.lockup.MessageComposer.withTypeUrl;

Superfluid Messages

import { osmosis } from 'osmojs';
const {
    lockAndSuperfluidDelegate,
    superfluidDelegate,
    superfluidUnbondLock,
    superfluidUndelegate
} = osmosis.superfluid.MessageComposer.withTypeUrl;

Incentives Messages

import { osmosis } from 'osmojs';
const {
    addToGauge,
    createGauge
} = osmosis.incentives.MessageComposer.withTypeUrl;

Gamm Messages

import { osmosis } from 'osmojs';
const {
    joinPool,
    exitPool,
    exitSwapExternAmountOut,
    exitSwapShareAmountIn,
    joinSwapExternAmountIn,
    joinSwapShareAmountOut,
    swapExactAmountIn,
    swapExactAmountOut
} = osmosis.gamm.v1beta1.MessageComposer.withTypeUrl;

CosmWasm Messages

import { cosmwasm } from "osmojs";

const {
    clearAdmin,
    executeContract,
    instantiateContract,
    migrateContract,
    storeCode,
    updateAdmin
} = cosmwasm.wasm.v1.MessageComposer.withTypeUrl;

IBC Messages

import { ibc } from 'osmojs';

const {
    transfer
} = ibc.applications.transfer.v1.MessageComposer.withTypeUrl

Cosmos Messages

import { cosmos } from 'osmojs';

const {
    fundCommunityPool,
    setWithdrawAddress,
    withdrawDelegatorReward,
    withdrawValidatorCommission
} = cosmos.distribution.v1beta1.MessageComposer.fromPartial;

const {
    multiSend,
    send
} = cosmos.bank.v1beta1.MessageComposer.fromPartial;

const {
    beginRedelegate,
    createValidator,
    delegate,
    editValidator,
    undelegate
} = cosmos.staking.v1beta1.MessageComposer.fromPartial;

const {
    deposit,
    submitProposal,
    vote,
    voteWeighted
} = cosmos.gov.v1beta1.MessageComposer.fromPartial;

Calculating Fees

Make sure to create a fee object in addition to your message.

For most messages, you can use the predefined fee objects.

import { FEES } from '@osmonauts/utils';

const fee = FEES.osmosis.swapExactAmountIn();

You can also specify low, medium, or high for fees:

const fee = FEES.osmosis.swapExactAmountIn('low');
const fee = FEES.osmosis.swapExactAmountIn('medium');
const fee = FEES.osmosis.swapExactAmountIn('high');

Or you can construct manually if you wish:

import { coins } from '@cosmjs/amino';

const fee = {
    amount: coins(0, 'uosmo'),
    gas: '250000'
}

if you are broadcasting multiple messages in a batch, you should simulate your tx and estimate the fee

import { Dec, IntPretty } from '@keplr-wallet/unit';

const gasEstimated = await stargateClient.simulate(address, msgs, memo);
const fee = {
  amount: coins(0, 'uosmo'),
  gas: new IntPretty(new Dec(gasEstimated).mul(new Dec(1.3)))
    .maxDecimals(0)
    .locale(false)
    .toString()
};

Connecting with Wallets and Signing Messages

⚡️ For web interfaces, we recommend using cosmos-kit. Continue below to see how to manually construct signers and clients.

Here are the docs on creating signers in cosmos-kit that can be used with Keplr and other wallets.

Initializing the Stargate Client

Use getSigningOsmosisClient to get your SigningStargateClient, with the Osmosis proto/amino messages full-loaded. No need to manually add amino types, just require and initialize the client:

import { getSigningOsmosisClient } from 'osmojs';

const client = await getSigningOsmosisClient({
  rpcEndpoint,
  signer // OfflineSigner
});

Creating Signers

To broadcast messages, you can create signers with a variety of options:

Amino Signer

Likely you'll want to use the Amino, so unless you need proto, you should use this one:

import { getOfflineSignerAmino as getOfflineSigner } from 'cosmjs-utils';

Proto Signer

import { getOfflineSignerProto as getOfflineSigner } from 'cosmjs-utils';

WARNING: NOT RECOMMENDED TO USE PLAIN-TEXT MNEMONICS. Please take care of your security and use best practices such as AES encryption and/or methods from 12factor applications.

import { chains } from 'chain-registry';

const mnemonic =
  'unfold client turtle either pilot stock floor glow toward bullet car science';
  const chain = chains.find(({ chain_name }) => chain_name === 'osmosis');
  const signer = await getOfflineSigner({
    mnemonic,
    chain
  });

Broadcasting messages

Now that you have your client, you can broadcast messages:

const { send } = cosmos.bank.v1beta1.MessageComposer.withTypeUrl;

const msg = send({
    amount: [
    {
        denom: 'uosmo',
        amount: '1000'
    }
    ],
    toAddress: address,
    fromAddress: address
});

const fee: StdFee = {
    amount: [
    {
        denom: 'uosmo',
        amount: '864'
    }
    ],
    gas: '86364'
};
const response = await stargateClient.signAndBroadcast(address, [msg], fee);

Advanced Usage

If you want to manually construct a stargate client

import { OfflineSigner, GeneratedType, Registry } from "@cosmjs/proto-signing";
import { AminoTypes, SigningStargateClient } from "@cosmjs/stargate";

import {
    cosmosAminoConverters,
    cosmosProtoRegistry,
    cosmwasmAminoConverters,
    cosmwasmProtoRegistry,
    ibcProtoRegistry,
    ibcAminoConverters,
    osmosisAminoConverters,
    osmosisProtoRegistry
} from 'osmojs';

const signer: OfflineSigner = /* create your signer (see above)  */
const rpcEndpoint = 'https://rpc.cosmos.directory/osmosis'; // or another URL

const protoRegistry: ReadonlyArray<[string, GeneratedType]> = [
    ...cosmosProtoRegistry,
    ...cosmwasmProtoRegistry,
    ...ibcProtoRegistry,
    ...osmosisProtoRegistry
];

const aminoConverters = {
    ...cosmosAminoConverters,
    ...cosmwasmAminoConverters,
    ...ibcAminoConverters,
    ...osmosisAminoConverters
};

const registry = new Registry(protoRegistry);
const aminoTypes = new AminoTypes(aminoConverters);

const stargateClient = await SigningStargateClient.connectWithSigner(rpcEndpoint, signer, {
    registry,
    aminoTypes
});

Developing

When first cloning the repo:

yarn
yarn build

And then get all submodules if necessary:

git submodule update --init

Codegen

Contract schemas live in ./contracts, and protos in ./proto. Look inside of scripts/codegen.js and configure the settings for bundling your SDK and contracts into osmojs:

yarn codegen

Note: please get all sub-modules before generating code, since some proto files within default config are included in sub-modules.

Publishing

Build the types and then publish:

yarn build:ts
yarn publish

Related

Checkout these related projects:

  • @cosmology/telescope Your Frontend Companion for Building with TypeScript with Cosmos SDK Modules.
  • @cosmwasm/ts-codegen Convert your CosmWasm smart contracts into dev-friendly TypeScript classes.
  • chain-registry Everything from token symbols, logos, and IBC denominations for all assets you want to support in your application.
  • cosmos-kit Experience the convenience of connecting with a variety of web3 wallets through a single, streamlined interface.
  • create-cosmos-app Set up a modern Cosmos app by running one command.
  • interchain-ui The Interchain Design System, empowering developers with a flexible, easy-to-use UI kit.
  • starship Unified Testing and Development for the Interchain.

Credits

🛠 Built by Cosmology — if you like our tools, please consider delegating to our validator ⚛️

Disclaimer

AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED “AS IS”, AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.

No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.

osmojs's People

Contributors

anmol1696 avatar daniel-farina avatar fatsheep1919 avatar marslavish avatar prettymuchbryce avatar pyramation avatar theothersideofgods avatar zetazzz avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

osmojs's Issues

Misbehavior With Amino Types

Hello, I'm using osmojs for sinfonia-ui, but I found two errors inside the AminoConverter:

  1. The amino converter related to /osmosis.lockup.MsgLockTokens should produce as a return for the "toAmino" function an object with the following structure:
{
  owner: string;
  duration: string;
  coins: Coin[];
}

Although, it returns an object with the following structure:

{
    owner: string;
    duration: {
        seconds: string;
        nanos: number;
    };
    coins: {
        denom: string;
        amount: string;
    }[];
}

As it's possible to see, here the duration field is returned as an object with seconds and nanos attributes, instead of a single string.

That's how I implemented it on sinfonia:
https://github.com/bitsongofficial/sinfonia-ui/blob/9aaa13947b971d220ae64600704645faf2133efb/src/signing/amino-types.ts#L89

  1. The amino type related to the message /osmosis.lockup.MsgBeginUnlocking seems to be wrong, it isn't osmosis/lockup/begin-unlocking as in line 24, since on osmosis it's defined such as osmosis/lockup/begin-unlock-period-lock as in line 14. You could get another reference directly from the osmosis frontend

Getting date.getTime is not a function

Getting date.getTime is not a function error from toTimestamp present in helpers.ts
On broadcasting '/cosmos.authz.v1beta1.MsgGrant' message
On 16.9.0 osmojs version

function toTimestamp(date) {
      const seconds = numberToLong(date.getTime() / 1e3);
      const nanos = date.getTime() % 1e3 * 1e6;
      return {
        seconds,
        nanos
      };
    }

Date object parsing error

When the osmojs library parses a date object to a timestamp on the accountLockedPastTimeDenom rpc method, an error is generated within a osmojs helper function due to a floating point number being passed to a BigInt().

Test case

Here is a simple testcase equating to the following osmoisd call

osmosisd query lockup account-locked-pastime-denom osmo1ep6h8wpy348qx8rq8vcmep0dctl9epgyuvdlhn 1691405330 gamm/pool/15
import { osmosis } from 'osmojs';

const endpoint = "https://rpc.osmosis.zone:443";
const account = "osmo1ep6h8wpy348qx8rq8vcmep0dctl9epgyuvdlhn";
const denom = "gamm/pool/15"

async function main() {
    const { createRPCQueryClient } = osmosis.ClientFactory;
    const client = await createRPCQueryClient({ rpcEndpoint: endpoint });
    let d: Date = new Date();

    const locks = await client.osmosis.lockup.accountLockedPastTimeDenom({
        owner: account,
        denom: denom,
        timestamp: d,

    })

    console.log(locks)
};

main().catch(console.error);
RangeError: The number 1691405445.575 cannot be converted to a BigInt because it is not an integer
    at BigInt (<anonymous>)
    at numberToLong (/node_modules/osmojs/src/codegen/helpers.ts:256:10)
    at toTimestamp (/node_modules/osmojs/src/codegen/helpers.ts:215:19)
    at Object.encode (/node_modules/osmojs/src/codegen/osmosis/lockup/query.ts:1827:35)
    at QueryClientImpl.accountLockedPastTimeDenom (/node_modules/osmojs/src/codegen/osmosis/lockup/query.rpc.Query.ts:123:52)
    at Object.accountLockedPastTimeDenom (/node_modules/osmojs/src/codegen/osmosis/lockup/query.rpc.Query.ts:212:27)
    at main (/src/bug.ts:14:47)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

I think the issue is in this function

export function toTimestamp(date: Date): Timestamp {
  const seconds = numberToLong(date.getTime() / 1_000);
  const nanos = (date.getTime() % 1000) * 1000000;
  return {
    seconds,
    nanos
  };
}

The argument to the numberToLong function divides date.getTime() by 1_000 and eventually passing this to BigInt() causes an error. This can also be seen in the console

let d = new Date();
d.getTime();
1691405875895
d.getTime() / 1_000
1691405875.895
BigInt(d.getTime()) // works
1691405875895n 
BigInt(d.getTime() / 1_000) // fails
Uncaught RangeError: 1691405875.895 can't be converted to BigInt because it isn't an integer

I think the helpers file is generated by https://github.com/cosmology-tech/telescope but I am unfamiliar with this project. If you can suggest where to find the generated function I can draft a PR if this is a valid issue.

Where to find a working, complete example of a swap?

Hi,
been trying to create a swap server-sided for a while now and no luck. I would like to know if there is a complete demo somewhere? All code examples have issues when put together and some of the code has moved folders making it hard to piece together a simple swap from one token to another.

Are there any gists or docs you could point to where a full working swap example exists between say OSMOS and ATOM exists?

Thanks

Type URL '/ibc.applications.transfer.v1.MsgTransfer' does not exist in the Amino message type register.

Hello,

I am trying to signAndBroadcast an IBC Transfer using /ibc.applications.transfer.v1.MsgTransfer, this works ok when using a directSigner, but when trying through a Ledger Nano using ledger-amino I can see in the code that it tries to call signAmino, which tries to find '/ibc.applications.transfer.v1.MsgTransfer, in aminoTypes.

However, while creating the client, I have no way of adding this as the constructor just spreads the default values as can be seen here.

Could you explain why is that? Should I make the Ledger signer as Direct as well? Thank you for your help!

decoding RPC for Pools Request doesn't decode Pool automatically

not sure if this is intended, but decoding RPC for Pools Request doesn't decode Pool automatically.

import { osmosis } from "osmojs";

import { createProtobufRpcClient, QueryClient } from "@cosmjs/stargate";
import { Tendermint34Client } from "@cosmjs/tendermint-rpc";

export const main = async () => {

    const tmClient = await Tendermint34Client.connect(RPC_ENDPOINT);
    const QueryClientImpl = osmosis.gamm.v1beta1.QueryClientImpl;
    const client = new QueryClient(tmClient);
    const rpc = createProtobufRpcClient(client);
    const queryService = new QueryClientImpl(rpc);
    const res = await queryService.pools({})

   // THIS WORKS but has to be manually applied
    res.pools.map(({ typeUrl, value }) => {
        console.log(osmosis.gamm.v1beta1.Pool.decode(value));
    })
};

main().then(() => {
    console.log('all done')
})

Random "signature verification failed" errors on WithdrawPosition txs

Title:

Random "signature verification failed" errors on WithdrawPosition txs

Description:

When executing transactions to withdraw a position, I occasionally encounter a failure in the transaction simulation and broadcasting process. The error returned is "Failed to simulate and broadcast after 3 attempts: Error: Broadcasting transaction failed with code 4 (codespace: sdk). Log: signature verification failed; please verify account number (12345), sequence (123) and chain-id (osmosis-1): unauthorized." This issue arises sporadically and does not consistently reproduce with the same conditions.

Environment Details:

  • OsmoJS Version: v16.9.0
  • Node.js Version: v20.11.0

Implementation

// all imports for the signing client

async init() {
  this.signer = await Secp256k1HdWallet.fromMnemonic(
    this.accountMnemonic,
    {
      prefix: "osmo",
      hdPaths: [makeCosmoshubPath(this.accountIndex)]
    }
  );

  this.address = (await this.signer.getAccounts())[0].address

  const protoRegistry: ReadonlyArray<[string, GeneratedType]> = [
    ...cosmosProtoRegistry,
    ...cosmwasmProtoRegistry,
    ...ibcProtoRegistry,
    ...osmosisProtoRegistry
  ];

  const aminoConverters = {
    ...cosmosAminoConverters,
    ...cosmwasmAminoConverters,
    ...ibcAminoConverters,
    ...osmosisAminoConverters
  };

  const registry = new Registry(protoRegistry);
  const aminoTypes = new AminoTypes(aminoConverters);

  this.client = await SigningStargateClient.connectWithSigner(this.rpcEndpoint, this.signer, {
    registry,
    aminoTypes
  });
}

import {MsgWithdrawPosition} from "osmojs/dist/codegen/osmosis/concentratedliquidity/v1beta1/tx";
import {Position} from "osmojs/dist/codegen/osmosis/concentratedliquidity/v1beta1/position";

async withdrawPosition(position: Position): Promise<DeliverTxResponse> {
	let value: MsgWithdrawPosition = {
		positionId: position.positionId,
		sender: this.address,
		liquidityAmount: position.liquidity,
	}

	return await this.submitTx([{
		typeUrl: "/osmosis.concentratedliquidity.v1beta1.MsgWithdrawPosition",
		value
	}])
}

async submitTx() {
	const gasWanted: number = await this.client.simulate(this.address, [messages[i]])
	const fee = await this.calculateFee(gasWanted);
	const response = await this.client.signAndBroadcast(this.address, [messages[i]], fee);
}

private async calculateFee(gasWanted: number): Promise<StdFee> {
	const gas = Math.ceil(gasWanted * 1.3);
	const amount = String(Math.ceil((0.0025 * 1) * gas)); // TODO Implement EIP1559
	return {
		amount: [{denom: "uosmo", amount}],
		gas: gas.toString(),
	}
}

Actual Behavior:

The transaction intermittently fails with a signature verification error, despite extensive testing across 5 different public RPCs and accounts on the mainnet. These tests, conducted simultaneously to rule out time-related factors, yielded inconsistent results—successes mixed with failures—without any discernible pattern. The issue's sporadic nature, occurring in about half of the attempts, and the straightforward code complicate pinpointing the cause, as failures seem random and without a clear failure pattern.

Error Messages:

Failed to simulate and broadcast after 3 attempts: Error: Broadcasting transaction failed with code 4 (codespace: sdk). Log: signature verification failed; please verify account number (12345), sequence (123) and chain-id (osmosis-1): unauthorized.

Additional Context:

  • The issue occurs randomly and is not tied to a specific Position object or transaction payload.
  • Example payload that failed:
    messages[i]: {
      typeUrl: '/osmosis.concentratedliquidity.v1beta1.MsgWithdrawPosition',
      value: {
        positionId: 123456n,
        sender: 'osmo1qnzhuj123459uffn8uyny12345wx3x0lv12345',
        liquidityAmount: '12345678901234567890.15243459811674906'
      }
    }

I suspect this could be related to how transaction simulation and sequence numbers are handled or possibly an issue with the chain-id validation process. Any insights or suggestions on how to troubleshoot or resolve this issue would be greatly appreciated.

npm run error

npm install osmojs
npm ERR! code ETARGET
npm ERR! notarget No matching version found for @cosmjs/stream@^0.29.3.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.

npm ERR! A complete log of this run can be found in:

what should i do

Geometric TWAP query bug

OSMO to ATOM pool geometric TWAP query is giving "52431954000000000". You need to shift this by 18 decimals to get the decimal value. This is surely a bug?

  return await client.osmosis.twap.v1beta1.geometricTwapToNow({
    poolId: Long.fromNumber(poolId),
    baseAsset,
    quoteAsset,

    startTime: startTime
      ? startTime
      : // Default is 60 minutes ago
        new Date(new Date().getTime() - 1000 * 60 * 60),
  });

export 'Long'.'UZERO' (imported as 'Long') was not found in

hello my tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,

// add esModuleInterop
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]

my react App.tsx code

import logo from './logo.svg';
import './App.css';
// this problem code
import { osmosis } from 'osmojs';


// start App
function App() {
  const { createRPCQueryClient } = osmosis.ClientFactory;
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.tsx</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}
export default App;

i refer #18, then fix my tsconfig.json
but, i see this error

Screen Shot 2022-10-14 at 4 01 33 PM

how can i fix error ?

import * as Long from 'long';

This module can only be referenced with ECMAScript imports/exports by turning on the 'esModuleInterop' flag and referencing its default export.

import * as Long from 'long';

Need an upgrade for ibc-go proto

There seems to be a misalignment between the latest cosmos proto and the osmojs ones for the IBC transactions.

As you can see, the proto file available on the cosmos repo in the ibc-go folder includes the info for the IBC memo parameter:
https://github.com/cosmos/ibc-go/blob/10324f5bf6840892cd7bba8a40231fc52a8b1745/proto/ibc/applications/transfer/v2/packet.proto#L5-L21

As you can see here:

option go_package = "github.com/cosmos/ibc-go/v2/modules/apps/transfer/types";
// FungibleTokenPacketData defines a struct for the packet payload
// See FungibleTokenPacketData spec:
// https://github.com/cosmos/ibc/tree/master/spec/app/ics-020-fungible-token-transfer#data-structures
message FungibleTokenPacketData {
// the token denomination to be transferred
string denom = 1;
// the token amount to be transferred
string amount = 2;
// the sender address
string sender = 3;
// the recipient address on the destination chain
string receiver = 4;
}

osmojs seems to be not yet updated 😬, nor at its last version:

option go_package = "github.com/cosmos/ibc-go/v2/modules/apps/transfer/types";
// FungibleTokenPacketData defines a struct for the packet payload
// See FungibleTokenPacketData spec:
// https://github.com/cosmos/ibc/tree/master/spec/app/ics-020-fungible-token-transfer#data-structures
message FungibleTokenPacketData {
// the token denomination to be transferred
string denom = 1;
// the token amount to be transferred
string amount = 2;
// the sender address
string sender = 3;
// the recipient address on the destination chain
string receiver = 4;
}

On the other hand, it seems that cosmjs already provide such a feature:
https://github.com/confio/cosmjs-types/blob/6e3448a046b86f4448d577a73edf8f2229e8ad61/src/ibc/applications/transfer/v2/packet.ts#L11-L26

Moreover, could you please construct the MessageComposer as you did for the IBC transfer message?

createPosition from osmosis.concentratedliquidity seems to be spotty erroring out most times with invalid coins error

The following request:

{"poolId":"1264","sender":"ADDRESS","tokenMinAmount0":"308115949918710","tokenMinAmount1":"0","tokensProvided":[{"denom":"ibc/EA1D43981D5C9A1C4AAEA9C23BB1D4FA126BA9BC7020A25E0AE4AA841EA25DC5","amount":"324332578861800"},{"denom":"ibc/498A0751C798A0D9A389AA3691123DADA57DAA4FE165D5C75894505B876BA6E4","amount":"787389"}],"upperTick":"-79577000","lowerTick":"-79935800"}

Fails with the error:

Query failed with (6): rpc error: code = Unknown desc = Invalid coins (324332578861800ibc/EA1D43981D5C9A1C4AAEA9C23BB1D4FA126BA9BC7020A25E0AE4AA841EA25DC5,787389ibc/498A0751C798A0D9A389AA3691123DADA57DAA4FE165D5C75894505B876BA6E4) With gas wanted: '0' and gas used: '167024' : unknown request

It works like 1% of the times for different pools. I've tried playing around with different arguments taken straight from keplr for requests that actually work on there but simply won't with osmojs.

Does not work inside Chrome extension

I got a ChunkLoadError inside a Chrome extension using Next.js. For some reason, the browser cannot load the chunk file even though it is created inside the folder.

The full chunk file is attached at bottom.

ChunkLoadError: Loading chunk 322 failed.
(error: chrome-extension://kgbklofchanpakafplbfaddoohgkaccm/_next/static/chunks/322.d3420e7c66971756.js)
    at f.f.j (webpack-fba7874665b47c5e.js:1:2830)
    at webpack-fba7874665b47c5e.js:1:933
    at Array.reduce (<anonymous>)
    at f.e (webpack-fba7874665b47c5e.js:1:899)
    at fU (787-e567954d7f9c47a5.js:3:3046589)
    at async index-943db5bdc3e8ef68.js:1:35124
    at async index-943db5bdc3e8ef68.js:1:34840
index-943db5bdc3e8ef68.js:1 

Here is my webpack.config.js:

 plugins: [
    new webpack.ProvidePlugin({
      Buffer: ["buffer", "Buffer"],
    }),
  ],
  resolve: {
    extensions: [".ts", ".js"],
    fallback: {
      buffer: false,
      crypto: false,
      events: false,
      path: false,
      stream: false,
      string_decoder: false,
    },
  },

322.d3420e7c66971756.js.zip

Nextjs Module import error with `[email protected]` and `[email protected]`. Version `[email protected]` doesnt create this error.

When running pnpm build, the build process fails with the error below. Shows for both [email protected] and [email protected] but not for [email protected]

app/node_modules/.pnpm/[email protected]/node_modules/osmojs/dist/codegen/cosmos/staking/v1beta1/staking.js:1
fortytwo-app:build: import { Header } from "../../../tendermint/types/types";
fortytwo-app:build: ^^^^^^
fortytwo-app:build: 
fortytwo-app:build: SyntaxError: Cannot use import statement outside a module
fortytwo-app:build:     at internalCompileFunction (node:internal/vm:77:18)
fortytwo-app:build:     at wrapSafe (node:internal/modules/cjs/loader:1290:20)
fortytwo-app:build:     at Module._compile (node:internal/modules/cjs/loader:1342:27)
fortytwo-app:build:     at Module._extensions..js (node:internal/modules/cjs/loader:1437:10)
fortytwo-app:build:     at Module.load (node:internal/modules/cjs/loader:1212:32)
fortytwo-app:build:     at Module._load (node:internal/modules/cjs/loader:1028:12)
fortytwo-app:build:     at Module.require (node:internal/modules/cjs/loader:1237:19)
fortytwo-app:build:     at require (node:internal/modules/helpers:176:18)

npm release 16.7.0 is missing some d.ts files

For example, /dist/codegen/cosmos/bundle.d.ts is missing in 16.7.0, but present in 16.6.0.

This causes TypeScript to consider that osmojs has no cosmos export. The export is, however, still there in the Javascript files.

fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);

i want to make a swap by using osmojs

const {
    swapExactAmountIn,
} = osmosis.gamm.v1beta1.MessageComposer.withTypeUrl;

const senderMnemonic = ""

  const chainFind = chains.find(({ chain_name }) => chain_name == 'osmosis');
  const signer = await getOfflineSigner({
    mnemonic:senderMnemonic,
    chain:chainFind
  });

const client = await getSigningOsmosisClient({
    rpcEndpoint:"https://rpc.cosmos.directory/osmosis",
    signer:signer 
});
const fee = {
    amount: coins(0, "uosmo"),
    gas: "500000",
};
const routes = [{
    poolId: "497",
    tokenOutDenom:"ibc/46B44899322F3CD854D2D46DEEF881958467CDD4B3B10086DA49296BBED94BED"
}];

const msg = swapExactAmountIn({
    sender:"osmo1......",
    routes:routes,
    tokenIn: coins("2400", "uosmo"),
    tokenOutMinAmount:"1558"
  });
let result = await client.signAndBroadcast("osmo1......", [msg], fee, '');
console.log(result);

but it failed , the error msg like this :

C:\\node_modules\osmojs\node_modules\long\umd\index.js:318
    return fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
                        ^

TypeError: Cannot read properties of undefined (reading 'low')
    at Function.fromValue (C:\code\cosmosDemoDell\node_modules\osmojs\node_modules\long\umd\index.js:318:25)
    at Object.toAmino (C:\code\cosmosDemoDell\node_modules\osmojs\main\codegen\osmosis\gamm\v1beta1\tx.amino.js:103:33)
    at AminoTypes.toAmino (C:\code\cosmosDemoDell\node_modules\osmojs\node_modules\@cosmjs\stargate\build\aminotypes.js:27:30)
    at C:\code\cosmosDemoDell\node_modules\osmojs\node_modules\@cosmjs\stargate\build\signingstargateclient.js:207:60
    at Array.map (<anonymous>)
    at SigningStargateClient.signAmino (C:\code\cosmosDemoDell\node_modules\osmojs\node_modules\@cosmjs\stargate\build\signingstargateclient.js:207:31)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async SigningStargateClient.signAndBroadcast (C:\code\cosmosDemoDell\node_modules\osmojs\node_modules\@cosmjs\stargate\build\signingstargateclient.js:167:23)
    at async file:///C:/code/cosmosDemoDell/03ibc/03_swapByOsmosis.js:41:14

How to calculate routes for concentrated pools specifically?

Context

I'm trying to build a program that trades on Osmosis. I want to use dynamic routes, meaning don't want to use hard coded routes for my trades.

Problem/Question

I haven't been able to find a method that calculate these routes for me yet. I'm aware of getRoutesForTrade which needs an array called pairs. Here's where the problem(or at least I think) arises because the array pairs is calculated from the pools using the makePoolPairs method. As you can see here the method makePoolPairs filters the pools into gamm pools only.

return pools
    .filter(
      (pool) =>
        pool.poolAssets.length === 2 &&
        pool.poolAssets.every(({ token }) => !token.denom.startsWith("gamm")) &&  // No concentrated liquidity pool allowed
        new BigNumber(calcPoolLiquidity(assets, pool, prices)).gte(liquidityLimit)
    )

I'm also aware that we can fetch the gamm equivalents of these concentratedPools. As application devs;

  • Are we expected to query all gamm pools, calculate routes using those and convert results to concentrated equivalent, if linked?

typeof pool.id is a BigNumber instead of Long

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch @osmonauts/[email protected] for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/@osmonauts/math/dist/pool.js b/node_modules/@osmonauts/math/dist/pool.js
index e000b0e..2920e20 100644
--- a/node_modules/@osmonauts/math/dist/pool.js
+++ b/node_modules/@osmonauts/math/dist/pool.js
@@ -188,7 +188,7 @@ const makePoolPairs = (pools, prices, liquidityLimit = 100000) => {
         if (!assetAinfo || !assetBinfo)
             return;
         return {
-            poolId: typeof pool.id === "string" ? pool.id : pool.id.low.toString(),
+            poolId: typeof pool.id === "string" ? pool.id : pool.id.toString(),
             poolAddress: pool.address,
             baseName: assetAinfo.display,
             baseSymbol: assetAinfo.symbol,

This issue body was partially generated by patch-package.

osmojs testing

Ideally we can have an end-to-end test which will ensure we've done proper amino encoding that will work in production.

current system

These work and run, however, we don't really know if it works with the chain itself. In order for this, we need real end-to-end tests.

seed

  • at least one pool with tokens A, B

cases

  • send tokens
  • swap tokens (@pyramation can help with this)
  • join pool and lock tokens

future

  • ibc transfer tokens

About sending amount coins to an address problem

I ran the following code according to the OsmoJS doc description, and an error occurred. What's the problem?

const signer = await getWalletFromMnemonic({mnemonic, token: 'OSMO'});
const client = await getSigningOsmosisClient({
    rpcEndpoint: rpcEndpoint,
    signer
});

const [firstAccount] = await signer.getAccounts();
const address = firstAccount.address;

const { send } = cosmos.bank.v1beta1.MessageComposer.withTypeUrl;

const msg = send({
    amount: [
    {
        denom: 'uosmo',
        amount: '1000'
    }
    ],
    toAddress: address,
    fromAddress: address
});

const fee = {
    amount: [
    {
        denom: 'uosmo',
        amount: '864'
    }
    ],
    gas: '86364'
};
const response = await client.signAndBroadcast(address, [msg], fee);

err as follows:

/home/huzi/project/tx/node_modules/protobufjs/src/util/longbits.js:116
        ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))
          ^

TypeError: util.Long is not a constructor
    at LongBits.toLong (/home/huzi/project/tx/node_modules/protobufjs/src/util/longbits.js:116:11)
    at Reader.read_uint64 [as uint64] (/home/huzi/project/tx/node_modules/protobufjs/src/reader.js:395:49)
    at Object.decode (/home/huzi/project/tx/node_modules/@cosmology/core/node_modules/osmojs/node_modules/cosmjs-types/cosmos/auth/v1beta1/auth.js:45:52)
    at SigningStargateClient.accountFromAny [as accountParser] (/home/huzi/project/tx/node_modules/@cosmology/core/node_modules/osmojs/node_modules/@cosmjs/stargate/build/accounts.js:33:62)
    at SigningStargateClient.getAccount (/home/huzi/project/tx/node_modules/@cosmology/core/node_modules/osmojs/node_modules/@cosmjs/stargate/build/stargateclient.js:109:35)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async SigningStargateClient.getSequence (/home/huzi/project/tx/node_modules/@cosmology/core/node_modules/osmojs/node_modules/@cosmjs/stargate/build/stargateclient.js:119:25)
    at async SigningStargateClient.sign (/home/huzi/project/tx/node_modules/@cosmology/core/node_modules/osmojs/node_modules/@cosmjs/stargate/build/signingstargateclient.js:187:49)
    at async SigningStargateClient.signAndBroadcast (/home/huzi/project/tx/node_modules/@cosmology/core/node_modules/osmojs/node_modules/@cosmjs/stargate/build/signingstargateclient.js:167:23)
    at async file:///home/huzi/project/tx/core.js:41:18

How to make a swap on osmosis

Hey guys, so I found this repo via cosmjs and cosmology and I have been trying for about 2 days now to make a swap on osmosis with no luck, I followed the examples and even read the core code trying to figure it out but I keep getting a 503 Service Unavailable, No server is available to handle this request error

Could you guys please maybe create an example with the simplest way to use this package to make a simple osmo to atom swap on osmosis?

calculated amount is lesser than min amount if multihop

Hi,
I try to do a Swap by making a correct MsgSwapExactAmountIn,
then using swapExactAmountIn, imported with const { swapExactAmountIn } = osmosis.gamm.v1beta1.MessageComposer.withTypeUrl.

MsgSwapExactAmountIn requires a parameter tokenOutMinAmount.
I suppose this is the amount with slippage, as mentionned here : https://www.npmjs.com/package/@cosmology/core :
const tokenOutMinAmount = calculateAmountWithSlippage( buy.amount, slippage );

So, I send a tokenIn.amount "171925", and a tokenOutMinAmount "163329" (Slippage 5%).
BUT I got the error :
"failed to execute message; message index: 0: ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2 token is lesser than min amount: calculated amount is lesser than min amount".
(Same if I set slippage like 90%)

My tokenIn is TORI, and my tokenOut is ATOM. So I use multihop pattern ti display the correct data to the user. The 2 correct pools are used, the fee are correctly calculated. I just have some difference token dust regarding https://frontier.osmosis.zone/. But it's likely the same expected amounts.

Independently of the point just above, I hope the SwapAmountInRoute[] given to my MsgSwapExactAmountIn are found correctly.
I make SwapAmountInRoute[] with lookupRoutesForTrade, using a Trade made from my two currencies and two amounts.

No issue with direct route like OSMO->ATOM.

Why ?

Here is MsgSwapExactAmountIn : https://github.com/osmosis-labs/osmojs/blob/main/packages/osmojs/src/codegen/osmosis/gamm/v1beta1/tx.ts#L68
Here is swapExactAmountIn : https://github.com/osmosis-labs/osmojs/blob/main/packages/osmojs/types/codegen/osmosis/bundle.d.ts#L188
Here is lookupRoutesForTrade : https://github.com/cosmology-tech/cosmology/blob/main/packages/core/src/utils/osmo/utils.ts#L725
Here is Trade : https://github.com/cosmology-tech/cosmology/blob/main/packages/core/src/types.ts#L140

Wdyt ?
Thank you for your repo and your time.

multiSend example

we may also need to do something special with the signingCosmosClient to make this easier:

an example from the community:

const {
  AminoTypes,
  SigningStargateClient
} = require('@cosmjs/stargate');
const { Registry } = require('@cosmjs/proto-signing');
const { defaultRegistryTypes } = require('@cosmjs/stargate');
const { OfflineSigner } = require('@cosmjs/proto-signing');
const { cosmos } = require('osmojs');

const getSigningCosmosClient = async ({ rpcEndpoint, signer }) => {
  // registry
  const registry = new Registry(defaultRegistryTypes);

  // aminotypes
  const aminoTypes = new AminoTypes({
    ...cosmos.bank.v1beta1.AminoConverter
  });

  cosmos.bank.v1beta1.load(registry);

  const client = await SigningStargateClient.connectWithSigner(
    rpcEndpoint,
    signer,
    { registry, aminoTypes }
  );

  return client;
};

module.exports = { getSigningCosmosClient: getSigningCosmosClient };

// #######################################

// ... and then in my index.js:

const {
  osmosis,
  ibc,
  cosmos,
  getSigningOsmosisClient,
  //getSigningCosmosClient,
  signAndBroadcast,
  FEE_VALUES
} = require('osmojs');

const { getSigningCosmosClient } = require('./cosmosclient.js');

/* ... */

Osmosis testnet was upgraded to Cosmos SDK 0.47 which is incompatible with Tendermint34Client

@cosmjs/tendermint-rpc - I suddenly started getting an error after broadcastTx->decodeTx
"Error: Invalid string. Length must be a multiple of 4"

I opened an issue with cosmjs and they told me this:

Osmosis testnet was upgraded to Cosmos SDK 0.47 as far as I can tell. In that case, using the Tendermint34Client won't work anymore. You need the Tendermint37Client. Can you report this to osmojs where those things are defined?

It looks like we need to be able to specify whether we want to use Tendermint34Client or Tendermint37Client when calling getSigningOsmosisClient()

I'm looking into this personally to see if there's an easy fix but wanted to post this as it's a blocking issue for hummingbot's Osmosis connector

RewardsEstRequest missing height params

Currently in osmosisd,
osmosisd query incentives rewards-estimation
allow to query by block height
--height int Use a specific height to query state at (this can error if the node is pruning state)

But it's missing in RewardsEstRequest
export interface RewardsEstRequest { owner: string; lockIds: Long[]; endEpoch: Long; }

Recommend Projects

  • React photo React

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

  • Vue.js photo Vue.js

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

  • Typescript photo Typescript

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

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

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

Recommend Topics

  • javascript

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

  • web

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

  • server

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

  • Machine learning

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

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

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

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.