Git Product home page Git Product logo

mx-sdk-js-core's Introduction

MultiversX SDK for JavaScript and TypeScript

MultiversX SDK for JavaScript and TypeScript (written in TypeScript).

Documentation

Distribution

npm

Installation

sdk-core is delivered via npm and it can be installed as follows:

npm install @multiversx/sdk-core

Development

Feel free to skip this section if you are not a contributor.

Prerequisites

browserify is required to compile the browser-friendly versions of sdk-core. It can be installed as follows:

npm install --global browserify

Building the library

In order to compile the library, run the following:

npm install
npm run compile
npm run compile-browser

Running the tests

In order to run the tests on NodeJS, do as follows:

npm run tests-unit
npm run tests-localnet
npm run tests-devnet
npm run tests-testnet

Before running the tests in the browser, make sure you have the package http-server installed globally.

npm install --global http-server

In order to run the tests in the browser, do as follows:

make clean && npm run browser-tests

For the localnet tests, make sure you have a local testnet up & running. In order to start a local testnet, follow this.

mx-sdk-js-core's People

Contributors

andreibancioiu avatar andreigiura avatar arhtudormorar avatar bcosma avatar bogdan-rosianu avatar camilbancioiu avatar ccorcoveanu avatar claudiu725 avatar claudiulataretu avatar ctindogaru avatar danielailie avatar dependabot[bot] avatar fixone avatar iulianpascalau avatar javier-nft avatar jbaron-mx avatar juliancwirko avatar kraus-milan avatar maximechbt avatar michavie avatar miiu96 avatar miromargineanu avatar mwfiae avatar nvergez avatar pctj101 avatar popenta avatar radumojic avatar ramonalobont avatar schimih avatar stanislavsava 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

Watchers

 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

mx-sdk-js-core's Issues

Decoding a Nested Structure - Decoding Smart Contract Data Client Side Issue

Screen Shot 2021-11-16 at 8 02 51 PM

base64 data: AAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA73eAAAAAAAFpiYAAAAAA
Hex data: 00000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003bdde000000000005a626000000000

Hex data manually "decoded":

00000001 // List with 1 Gamestate

0000000000000000 // GameState Fee 0
0000000000000000 //GameState End 0
0000000000000000 //GameState current leader
00000000 //empty list of participants
0000000000000000 // GameState PrizePool 0
0000000000000000 //GameState Dethrone count

00000000003bdde0 //Game Price Pool
00000000005a6260 //Game Fund Pool
00000000 //empty list of tickets

For now i just have a list of u64 that a can query using a storage mapper.

Contract Address on Testnet: erd1qqqqqqqqqqqqqpgq0cj4ns6605zwx2fg64y0hcazwykr7ahrj9tsadt320

    "buildInfo": {
        "rustc": {
            "version": "1.58.0-nightly",
            "commitHash": "82af160c2cb9c349a0373cba98d8ad7f911f0d34",
            "commitDate": "2021-11-10",
            "channel": "Nightly",
            "short": "rustc 1.58.0-nightly (82af160c2 2021-11-10)"
        },
        "contractCrate": {
            "name": "adder",
            "version": "0.0.0"
        },
        "framework": {
            "name": "elrond-wasm",
            "version": "0.22.6"
        }
    },
    "name": "KothElrond",
    "constructor": {
        "inputs": [],
        "outputs": []
    },
    "endpoints": [
        {
            "name": "contractOwner",
            "mutability": "readonly",
            "inputs": [],
            "outputs": [
                {
                    "type": "Address"
                }
            ]
        },
        {
            "name": "getGame",
            "mutability": "readonly",
            "inputs": [],
            "outputs": [
                {
                    "type": "Game"
                }
            ]
        },
        {
            "name": "getGameState",
            "mutability": "readonly",
            "inputs": [],
            "outputs": [
                {
                    "type": "GameState"
                }
            ]
        },
        {
            "name": "getGamePrizeTicket",
            "mutability": "readonly",
            "inputs": [],
            "outputs": [
                {
                    "type": "GamePrizeTicket"
                }
            ]
        }
    ],
    "hasCallback": false,
    "types": {
        "Game": {
            "type": "struct",
            "fields": [
                {
                    "name": "current_games",
                    "type": "List<GameState>"
                },
                {
                    "name": "game_prize_pool",
                    "type": "u64"
                },
                {
                    "name": "game_fund_pool",
                    "type": "u64"
                },
                {
                    "name": "game_prize_tickets",
                    "type": "List<GamePrizeTicket>"
                }
            ]
        },
        "GamePrizeTicket": {
            "type": "struct",
            "fields": [
                {
                    "name": "game_prize_ticket_user",
                    "type": "u64"
                }
            ]
        },
        "GameState": {
            "type": "struct",
            "fields": [
                {
                    "name": "game_state_fee",
                    "type": "u64"
                },
                {
                    "name": "game_state_end_date",
                    "type": "u64"
                },
                {
                    "name": "game_state_current_leader",
                    "type": "u64"
                },
                {
                    "name": "game_state_particpants_list",
                    "type": "List<u64>"
                },
                {
                    "name": "game_state_prize_pool",
                    "type": "u64"
                },
                {
                    "name": "game_state_dethrone_count",
                    "type": "u64"
                }
            ]
        }
    }
}```

Feature request: signMessage implemented for all login methods.

I'm developing a platform highly dependent on signing a message, so I can authenticate server requests.

export interface IDappProvider {
....
signMessage(transaction: SignableMessage, options?: {
callbackUrl?: string;
}): Promise;
....
}

Is there any timeline for this method to be implemented in other login methods apart from the Extension?
At least Maiar App, that's the most used one so far.

Thanksss!

MapMapper/SetMapper ABI deserialization

Hi, try to write ABI for smart contract. One of the views looks like this:

#[view]
#[storage_mapper("allowed_tokens_set")]
    fn allowed_tokens_set(&self) -> SetMapper<TokenIdentifier>;

As you can see it returns SetMapper (my knowledge in Rust is poor), as I understand it is a simple List

When i get info from this method raw data consists of array which contains 3 elements, but after deserialization i get first element from this array and nothing more

ABI:

const ABI = {
  name: 'crowdsale',
  constructor: {
    inputs: [],
    outputs: [],
  },
  endpoints: [
    {
      name: 'start_timestamp',
      inputs: [],
      outputs: [
        {
          type: 'u64',
        },
      ],
    },
    {
      name: 'allowed_tokens_set',
      inputs: [],
      outputs: [
        {
          type: 'List<TokenIdentifier>',
        },
      ],
    },
    {
      name: 'allowed_tokens_map',
      inputs: [],
      outputs: [
        {
          type: 'tuple2<TokenIdentifier, u8>',
        },
      ],
    },
  ],
}

Getting data:

const method = 'allowed_tokens_set';
const myAddress = new Address(elraddress);
const contractAddress = new Address(contracts.crowdSale.address);
const contractAbi = new SmartContractAbi(contracts.crowdSale.abi, ['crowdsale']);
const contract = new SmartContract({ address: contractAddress, abi: contractAbi });

const query = contract.createQuery({
    func: new ContractFunction(method),
    args: [],
    caller: myAddress,
 });

 const proxyProvider = new ProxyNetworkProvider('https://testnet-gateway.elrond.com');
 const queryResponse = await proxyProvider.queryContract(query);
 const resultsParser = new ResultsParser();
 const endpointDefinition = contract.getEndpoint(method);
 const bundle = resultsParser.parseQueryResponse(queryResponse, endpointDefinition);
 console.log(bundle.values, queryResponse);

In which place i've done something wrong?(

NativeSerializer cannot parse enum value

Hi,

It seems convertToTypedValue method from NativeSerializer cannot handle enum, the workaround is to not currently use ABI to call endpoints that require enum

I'm using erdjs 10.2.4

Thank you

Proposal: uniformize transaction factories

Summary

Following the design of TokenOperationsFactory, re-structure the other transaction factories and builders.

Current state

There are a number of design inconsistencies among the components responsible with constructing ready-to-sign transactions.

Creating a TokenTransfersFactory, then a number of transfer transactions:

const factory = new TransferTransactionsFactory(new GasEstimator());
const txA = factory.createEGLDTransfer({ ... });
const txB = factory.createESDTTransfer({ ... });

Creating a TokenOperationsFactory, then a number of transactions:

const factory = new TokenOperationsFactory(new TokenOperationsFactoryConfig("D"));
const txA = factory.issueFungible({ ... });
const txB = factory.issueNonFungible({ ... });

Creating a SmartContract object, then a number of interaction transactions:

const smartContract = new SmartContract({ address: "..." });
const txA = smartContract.deploy({ ... });
const txB = smartContract.call({ ... });

Creating a RelayedTransaction(V1|V2)Builder, then craft a transaction:

const builder = new RelayedTransactionV1Builder();
const txA = builder
    .set...()
    ...
    .build();

References:

Design points

  1. All factories would receive a single constructor argument, which is a configuration object (to hold, among others, the chain ID and gas limit configuration) - see TokenOperationsFactory, as an example.
  2. Public methods of a factory would return constructed transactions, ready-to-sign or almost ready-to-sign (depending on whether the user also passed the nonce when calling the method of the factory). See TokenOperationsFactory for an example.

Changes to make

  • TransferTransactionsFactory - will not receive a GasEstimator as a constructor parameter anymore, but a factory config, instead.
  • logic of RelayedTransactionV1Builder and RelayedTransactionV2Builder would be merged into a RelayedTransactionsFactory.
  • logic of SmartContract - which does behave as a transactions factory (in part) would be extracted to a SmartContractTransactionsFactory.

Progressive roll-out

  • The factories would ideally be added in v12, without breaking changes.
  • The superseded components will be marked as deprecated, as the new ones are written and released.
  • When name collision occurs, the new components will be prefixed with Next*. E.g. NextTransferTransactionsFactory.
  • In next major version (e.g. v13), the superseded components will be removed, and the Next* prefix will be dropped.
  • Eventual changes of the Interaction component will be handled separately (another proposal, another change set etc.)

Feedback

Let us know what you think ๐Ÿ™

Error - TransactionWatcher.awaitConditionally(): cannot (yet) fetch data

The error is showing when you explicitly wait for the transaction to be executed.

I've tried multiple solutions, but the error seems to pop up in all of them. The behaviour is nondeterministic, sometimes you see the error, sometimes you don't.

OS used:

  • macOS Monterey 12.2.1

erdjs used:

  • "@elrondnetwork/erdjs": "^9.2.0"

network used:

  • proxy https://devnet-api.elrond.com and chain D

error tracking:

code samples that can generate the error:

await tx.awaitExecuted(provider);

or

let watcher = new TransactionWatcher(tx.getHash(), provider);  
await watcher.awaitStatus(status => status.isExecuted(), onStatusReceived || TransactionWatcher.NoopOnStatusReceived);

suggestions:

  • change the logger level from info to debug so the error doesn't show up to the user. As it stands now, the error can give the user the impression that he messed up something, when in fact, the error is internal and it's inoffensive.
  • increase the polling interval.

Transactions signed Web Wallet + Ledger fail on sending

When signing transactions via the Web Wallet provider, where the user logs in their wallet via Ledger, transactions come back signed without any issue, but when trying to send them via the ProxyProvider I receive the following error:

transaction generation failed: ed25519: invalid signature

After a brief discussion with @StanislavSava, he suggested I open this issue for the Elrond team to pick up from here. I'm not excluding we might be doing something wrong, but I'm looking for some directions.

Just to clarify, we are talking about WalletProvider which is logged in using Ledger, we are not using HwProvider directly.

Elrond Testnet is down

Greetings,

I've been working as a Staff Engineer in Propine. One of my teammates is working to implement with Elrond. He gave me as an info:

Elrond testnet is totally down. Account balance appears as 0 and all transactions are not working. Asked faucet tokens but it's not working as well.

My question is do you know when the testnet will be available for testing ?

ExtensionProvider: Do not support empty TransactionPayload for transaction data

Hello',

I'm trying to homogenize usage of all providers.
When I'm using ExtensionProvider:
If I use sendTransaction without specifying data:
image
(Not OK, I don't see any pending transaction)

If I use sendTransaction with new TransactionPayload(" "):
image
OK

Note: new TransactionPayload("") does not work, data cannot be empty

I didn't find the extension repository so I report the inconsistant behaviour here. ;)

Thanks in advance! :)

Thรฉo Sabattiรฉ

Cannot parse a contract function from Abi with args & multivalue

Error: cannot parse type expression: variadic<multi<array32,u32,array64>>. internal json: {"variadic": {"multi": {"array32": {"u8": {} }: {},"u32": {},"array64": {"u8": {} }}}}.
at TypeExpressionParser.doParse (node_modules/@elrondnetwork/erdjs/src/smartcontracts/typesystem/typeExpressionParser.ts:25:19)

Tokens are missing properties from the API

Hello Team,

I work with the Tokens FungibleTokenOfAccountOnNetwork and NonFungibleTokenOfAccountOnNetwork and I notice they are missing a lot of properties from the API. I try to get the Assets from it with the Token Logo and so but it is not possible at the moment.

Thank you!

[AbiRegistry.create] Cannot map the type "<name>" to a known type

Hi, I getting error when trying create Abi from json.
Looks like it cannot map enum, but it was working fine with another abi json's
I'm using @elrondnetwork/erdjs v11.1.0

core.js:6498 ERROR Error: Uncaught (in promise): Error: Cannot map the type "Status" to a known type
Error: Cannot map the type "Status" to a known type
    at TypeMapper.mapType (typeMapper.js:116:1)
    at typeMapper.js:157:1
    at Array.map (<anonymous>)
    at TypeMapper.mappedFields (typeMapper.js:157:1)
    at TypeMapper.mapStructType (typeMapper.js:147:1)
    at TypeMapper.mapRecursiveType (typeMapper.js:134:1)
    at TypeMapper.mapType (typeMapper.js:106:1)
    at AbiRegistry.remapToKnownTypes (abiRegistry.js:117:1)
    at AbiRegistry.create (abiRegistry.js:37:1)
    at app.component.ts:308:38
    at resolvePromise (zone.js:1211:1)
    at zone.js:1118:1
    at zone.js:1134:1
    at asyncGeneratorStep (asyncToGenerator.js:6:1)
    at _next (asyncToGenerator.js:25:1)
    at asyncToGenerator.js:32:1
    at new ZoneAwarePromise (zone.js:1429:1)
    at asyncToGenerator.js:21:1
    at AppComponent.ngOnInit (app.component.ts:29:16)
    at callHook (core.js:2538:1)

Code to reporduce

const abiJson = {
	"buildInfo": {
		"rustc": {
			"version": "1.66.0-nightly",
			"commitHash": "2019147c5642c08cdb9ad4cacd97dd1fa4ffa701",
			"commitDate": "2022-09-19",
			"channel": "Nightly",
			"short": "rustc 1.66.0-nightly (2019147c5 2022-09-19)"
		},
		"contractCrate": {
			"name": "loan-data",
			"version": "0.0.0",
			"git_version": "d1f960a-modified"
		},
		"framework": {
			"name": "elrond-wasm",
			"version": "0.35.0"
		}
	},
	"name": "LoanDataContract",
	"constructor": {
		"inputs": [],
		"outputs": []
	},
	"endpoints": [
		{
			"name": "getById",
			"mutability": "readonly",
			"inputs": [
				{
					"name": "id",
					"type": "BigUint"
				}
			],
			"outputs": [
				{
					"type": "LoanInfo"
				}
			]
		},
		{
			"name": "getList",
			"mutability": "readonly",
			"inputs": [
				{
					"name": "page",
					"type": "u64"
				},
				{
					"name": "size",
					"type": "u16"
				}
			],
			"outputs": [
				{
					"type": "variadic<LoanShortInfo>",
					"multi_result": true
				}
			]
		},
		{
			"name": "create",
			"mutability": "mutable",
			"inputs": [
				{
					"name": "data",
					"type": "LoanCreateOptions"
				}
			],
			"outputs": [
				{
					"type": "LoanInfo"
				}
			]
		},
		{
			"name": "createByArgs",
			"mutability": "mutable",
			"inputs": [
				{
					"name": "amount",
					"type": "BigUint"
				},
				{
					"name": "loaner_address",
					"type": "Address"
				},
				{
					"name": "token",
					"type": "EgldOrEsdtTokenIdentifier"
				},
				{
					"name": "status",
					"type": "Status"
				},
				{
					"name": "note",
					"type": "bytes"
				}
			],
			"outputs": [
				{
					"type": "LoanInfo"
				}
			]
		},
		{
			"name": "updateStatus",
			"mutability": "mutable",
			"inputs": [
				{
					"name": "id",
					"type": "BigUint"
				},
				{
					"name": "status",
					"type": "Status"
				}
			],
			"outputs": [
				{
					"type": "Status"
				}
			]
		},
		{
			"name": "setArrayOfStruct",
			"mutability": "mutable",
			"inputs": [
				{
					"name": "list",
					"type": "variadic<Item>",
					"multi_arg": true
				}
			],
			"outputs": []
		},
		{
			"name": "setArrayOfAddresses",
			"mutability": "mutable",
			"inputs": [
				{
					"name": "list",
					"type": "variadic<Address>",
					"multi_arg": true
				}
			],
			"outputs": []
		},
		{
			"name": "setArrayOfBigInt",
			"mutability": "mutable",
			"inputs": [
				{
					"name": "list",
					"type": "variadic<BigInt>",
					"multi_arg": true
				}
			],
			"outputs": []
		}
	],
	"events": [],
	"hasCallback": false,
	"types": {
		"Item": {
			"type": "struct",
			"fields": [
				{
					"name": "amount",
					"type": "BigUint"
				},
				{
					"name": "address",
					"type": "Address"
				}
			]
		},
		"LoanCreateOptions": {
			"type": "struct",
			"fields": [
				{
					"name": "amount",
					"type": "BigUint"
				},
				{
					"name": "loaner_address",
					"type": "Address"
				},
				{
					"name": "token",
					"type": "EgldOrEsdtTokenIdentifier"
				},
				{
					"name": "status",
					"type": "Status"
				},
				{
					"name": "note",
					"type": "bytes"
				}
			]
		},
		"LoanInfo": {
			"type": "struct",
			"fields": [
				{
					"name": "id",
					"type": "BigUint"
				},
				{
					"name": "amount",
					"type": "BigUint"
				},
				{
					"name": "loaner_address",
					"type": "Address"
				},
				{
					"name": "token",
					"type": "EgldOrEsdtTokenIdentifier"
				},
				{
					"name": "timestamp",
					"type": "u64"
				},
				{
					"name": "status",
					"type": "Status"
				},
				{
					"name": "note",
					"type": "bytes"
				}
			]
		},
		"LoanShortInfo": {
			"type": "struct",
			"fields": [
				{
					"name": "id",
					"type": "BigUint"
				},
				{
					"name": "amount",
					"type": "BigUint"
				},
				{
					"name": "loaner_address",
					"type": "Address"
				},
				{
					"name": "token",
					"type": "EgldOrEsdtTokenIdentifier"
				}
			]
		},
		"Status": {
			"type": "enum",
			"variants": [
				{
					"name": "Redeemed",
					"discriminant": 0
				},
				{
					"name": "NotRedeemed",
					"discriminant": 1
				}
			]
		}
	}
};

const scAbi = new SmartContractAbi(AbiRegistry.create(abiJson));

console.log('scAbi', scAbi);

Missing devDependency `ledgerhq__hw-transport`

In vesrion 9 the following error appears in NodeJs context:
node_modules/@elrondnetwork/erdjs/out/dapp/hwProvider.d.ts:2:39 - error TS2307: Cannot find module 'ledgerhq__hw-transport' or its corresponding type declarations.

This is fixed by adding in devDependencies the following:
"@types/ledgerhq__hw-transport": "^4.21.4"

This should be included in the library IMO.

Problem with send transaction logged with maiar app

When i login in my Dapp with web wallet, i can send transactions and can query smart contract with no problems, but when i logged with maiar app, when i try to send transaction to my smart contract the console show me:
Uncaught (in promise) TypeError: transaction.send is not a function
at WalletConnectProvider. (walletConnectProvider.ts:137:1)

I send the transaction with provider like:
provider.sendTransaction(tx);

I use erjs 10.1.0 for my Dapp, but i have this problem... any idea or help?

NativeSerializer cannot parse ManagedByteArray value

Hi,

It seems convertToTypedValue method from NativeSerializer cannot handle ManagedByteArray, the workaround is to not currently use ABI to call endpoints that require ManagedByteArray

Error: Nested error: convertToTypedValue: unhandled type Array

I'm using the latest erdjs version.

Thank you.

Cannot sign message from extensionProvider

Description

We're trying to call provider.signMessage() with the following code:

const sm = new SignableMessage({
  message: Buffer.from('0x' + Buffer.from(data).toString('hex'), 'ascii'),
})

And send message with

provider.signMessage(sm)
            .then(e => { return e.toJSON().toString()})
            .catch(err => { console.error(err); return ''; })

Then I got blank page then I received an error

Extension window was closed without response.

Investigation

We read the source code, found signMessage called startExtMsgChannel. Then we debug this function found error may happends https://github.com/ElrondNetwork/elrond-sdk-erdjs/blob/main/src/dapp/extensionProvider.ts#L204-L208
Then we cannot go deeper, cause the extension wallet seems not open sourced.

TransactionOnNetwork doesn't contain smart contract results in the npm package

Hi everyone,

sadly this is still an issue:

While the code in the repo looks (and probably works) fine.
https://github.com/ElrondNetwork/elrond-sdk-erdjs/blob/main/src/transactionOnNetwork.ts#L73

transactionOnNetwork.smartContractResults = SmartContractResults.fromHttpResponse(response.smartContractResults || []);

The version published on npm contains an error:

transactionOnNetwork.results = smartContractResults_1.SmartContractResults.fromHttpResponse(response.results || []);

As you can see it tries to use the results field instead of the smartContractResults field. Resulting in no results being included in the transaction.

No support for signing messages with walletConnectProvider

Currently only the extension and ledger providers support signing messages. Will support for signing messages with the Maiar app be added? Without it developing dapps that use a backend authentication via signatures is more or less impossible for mobile users.

ESDT getTxFieldsForEsdtTransfer helper returning invalid data

Hi!

After running a few tests with getTxFieldsForEsdtTransfer fn, I believe I found an issue (assuming this isn't the expected behaviour).
After encoding the amount, there's no extra step to prepend "0" when the string length is odd. Calling extractFieldsFromEsdtTransferDataField fn right after will throw an error, stating that the "call data" isn't valid.

I believe that including a transformation similar to getHexMagnitudeOfBigInt fn after encoding the amount should fix it.

Example

describe("test getTxFieldsForEsdtTransfer & extractFieldsFromEsdtTransferDataField", () => {
  it("should throw an error when encodedAmount str length is odd", () => {
    let {data} = EsdtHelpers.getTxFieldsForEsdtTransfer("4142432d317132773365", "1000");

    assert.equal(data, "ESDTTransfer@4142432d317132773365@3e8");

    assert.throws(
      () => EsdtHelpers.extractFieldsFromEsdtTransferDataField(data),
        Error,
      "Invalid smart contract call data fieldESDTTransfer@4142432d317132773365@3e8"
    );
  })
})

Upgrade breaks Interaction serialization with native variadic arguments

Upgrading from 12.1.0 breaks transactions using native variadic arguments, with this error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'belongsToTypesystem')
    at eu (_app-e1ba62606a0e66e8.js:5:31477)
    at Object.ec [as nativeToTypedValues] (_app-e1ba62606a0e66e8.js:5:31004)
    at methods.<computed> [as someMethod] (_app-e1ba62606a0e66e8.js:5:42871)
    at U (3032-5df52ac79f3887e8.js:1:27869)
    at async Object.S [as someOtherMethod] (3032-5df52ac79f3887e8.js:1:26988)

Worked before and fails after upgrade for Interactions:

const interactionArgs = [
    someValue,
    ...['a', 'b', 'c'], // <--- used to work, but now causes errors with latest versions
  ]

Using VariadicValue is a temporary fix, but ideally, native values would keep working

Likely caused by this change here: 973c823

Arguments serialization error

I have this code in reactjs

export const mergeTokens = async ({ userAddress, lkmexArray }) => {
  const Args = [
    new AddressValue(new Address(contractAddr)),
    new BigUIntValue(new BigNumber(lkmexArray.length)),
  ];

  for (const token of lkmexArray) {
    Args.push(
      BytesValue.fromUTF8(token.collection),
      new BigUIntValue(new BigNumber(token.nonce)),
      new BigUIntValue(new BigNumber(token.balance))
    );
  }

  Args.push(BytesValue.fromUTF8("mergeTokens"));

  console.log("Args", Args);
  const payload = TransactionPayload.contractCall()
    .setFunction(new ContractFunction("MultiESDTNFTTransfer"))
    .setArgs(Args)
    .build();
  const transactionData = {
    addr: userAddress,
    payload: payload,
  };
  return await sendTransaction(transactionData);
 
};

and you will taste in you will say everything is fine, indeed it works fine but in development but when I make the build got this :

argSerializer.ts:137 Uncaught (in promise) TypeError: t.isSet is not a function
    at a (argSerializer.ts:137)
    at n.value (argSerializer.ts:128)
    at n.value (argSerializer.ts:113)
    at n.value (argSerializer.ts:103)
    at d (transactionPayloadBuilders.ts:167)
    at e.value (transactionPayloadBuilders.ts:160)
    at index.js:32
    at l (runtime.js:63)
    at Generator._invoke (runtime.js:294)
    at Generator.next (runtime.js:119)

metion that the Args in log is always the same and try to remove the new BigNumber and didint work in build ider, try other version and I had other diferentes errors, what can I do to archive this simple call ?

My package.json : 
`"dependencies": {
    "@chakra-ui/icons": "^1.0.14",
    "@chakra-ui/react": "^1.8.5",
    "@chakra-ui/theme-tools": "^1.1.9",
    "@elrondnetwork/dapp-core": "1.0.0",
    "@elrondnetwork/erdjs": "^9.2.2",
    "@emotion/react": "^11.8.1",
    "@emotion/styled": "^11.8.1",
    "@mui/icons-material": "^5.4.2",
    "@mui/material": "^5.4.4",
    "@reduxjs/toolkit": "^1.7.2",
    "bech32-converting": "^1.0.8",
    "big-number": "^2.0.0",
    "bignumber.js": "9.0.1",
    "classnames": "2.3.1",
    "framer-motion": "^4.1.17",
    "lodash": "^4.17.21",
    "moment": "^2.29.1",
    "npm": "^8.3.1",
    "react": "^17.0.2",
    "react-animate-on-scroll": "^2.1.5",
    "react-cookie": "^4.1.1",
    "react-custom-scrollbars": "^4.2.1",
    "react-dom": "17.0.2",
    "react-icons": "^4.2.0",
    "react-lazyload": "^3.2.0",
    "react-quill": "^1.3.5",
    "react-redux": "^7.2.6",
    "react-router-dom": "^6.2.1",
    "react-scripts": "4.0.3",
    "react-spring": "^9.4.3",
    "react-table": "^7.7.0",
    "react-tsparticles": "^1.42.1",
    "sweetalert2": "^11.4.4",
    "swiper": "8.0.0"
  },

Argument Serialization Error with Interaction in version 9.2.0

Hello,

When I use the Interaction class with the "withSingleESDTTransfer" method to build a Transaction, then I get this error since the Version 9.2.0. The error I did not get in 9.1.0.

Uncaught (in promise) TypeError: t.isSet is not a function
at r (app.js)
at t.ArgSerializer.valuesToBuffers (app.js)
at t.ArgSerializer.valuesToStrings (app.js)
at t.ArgSerializer.valuesToString (app.js)
at s (app.js)
at t.ContractCallPayloadBuilder.build (app.js)
at w.call (app.js)
at t.Interaction.buildTransaction (app.js)

It could be a bug.

Thank you!

axios.defaults.transformResponse setting causes arweave (and other string only axios) to fail

Erdjs introduces a changes in 2 files to axios which causes arweave-js to fail

https://github.com/ElrondNetwork/elrond-sdk-erdjs/blob/main/src/apiProvider.ts#L94
https://github.com/ElrondNetwork/elrond-sdk-erdjs/blob/main/src/proxyProvider.ts#L184

// See: https://github.com/axios/axios/issues/983
axios.defaults.transformResponse = [
  function(data) {
    return JSONbig.parse(data);
  },
];

An example of where this causes problems is if another npm package wants to fetch a pure string from another endpoint, even with content type text/html, JSONbig.parse(data) fails to parse a string which is invalid JSON.

As documented here, it takes a slightly strange work-around to deal with this
ArweaveTeam/arweave-js#97

Would it be better to include this tranformResponse configuration along with each axios request to avoid disturbing other npm packages?

Custom signin process / Sign in transaction with ibm hyper protect crypto services using the enterprise pkcs11(ep11)

Greetings,

I've been working as an engineer for https://propine.com. Our solution uses ibm hyper protect crypto services using the enterprise pkcs11(ep11) to sign transactions or create a new address.

Unfortunately:
My team has an issue with the following error:
[Error]: Request error on url [transaction/send]: [transaction generation failed: ed25519: invalid signature]

The hex is valid. As a validator: We're using: https://github.com/ElrondNetwork/elrond-sdk-erdjs/blob/main/src/signature.ts#L39

Source code snippet:

const signingMessage = rawTx
      .serializeForSigning(rawTx.getSender())
      .toString("hex");
      
// Custom ibm hyper protect crypto services using the enterprise pkcs11(ep11) signature generation
const { signature } = await sign();
const elrondSignature = Signature.toBuf(signature);
const signs = new ElrondSignature(elrondSignature);

rawTx.applySignature(signs, senderAddress);
const txHash = await this.proxyProvider.sendTransaction(rawTx);
const transactionWatcher = new TransactionWatcher(this.proxyProvider);
await transactionWatcher.awaitCompleted(rawTx);

Add the possibility to mix TypedValues and native js types when using methods from Interaction

As said in telegram https://t.me/MultiversXDevelopers/110664
It could be great to have the possibility to mix both typed values and native js types when calling a method from a contract using Interactions.

https://github.com/multiversx/mx-sdk-js-core/blob/main/src/smartcontracts/nativeSerializer.ts#L22
The assert would go away and we could push the value directly into the array when belongsToTypesystem is true.

The problem came from a need to send an Enum as a parameter but since Enum is not taken into account I had to use methodsExplicit and do everything by hand.

Angular 12 (webpack 5) and erdjs throws errors

How to reproduce:

  1. Create a fresh Angular 12 project ng new after installing the global cli for Angular npm install -g @angular/cli
  2. Install erdjs npm i @elrondnetwork/erdjs
  3. Pop in the first lines of code from erdjs docs let provider = new ProxyProvider("https://localhost:7950"); in the home component and start the dev server using ng serve

You will get the following errors:
image

Went over and installed

"browserify": "^17.0.0",
"crypto-browserify": "^3.12.0",
"https-browserify": "^1.0.0",
"path-browserify": "^1.0.1",
"stream-browserify": "^3.0.0",

Then added them as paths in tsconfig.json

"compilerOptions":{
    "paths": {
      "crypto": ["./node_modules/crypto-browserify"],
      "stream": ["./node_modules/stream-browserify"],
      "path": ["./node_modules/path-browserify"],
    }
}

Great, the webpack errors are gone. We're left with the filesystem (fs). After some research, I decided that a "browserify" version of fs might also fix the problem. So went over and installed browserify-fs npm i browserify-fs and also added in the above compilerOptions -> paths object. Now it looks like this:

"compilerOptions":{
    "paths": {
      "crypto": ["./node_modules/crypto-browserify"],
      "stream": ["./node_modules/stream-browserify"],
      "path": ["./node_modules/path-browserify"],
      "fs": ["./node_modules/browserify-fs"]
    }
}

Go ahead and restart the dev server with ng serve. Now the compiler doesn't throw any more errors, but a quick look at the actual app and we will notice that things are not fixed.
We notice that "process" is undefined in the Chrome Developer Console
image

Went over to polyfills.ts and added these lines:

import { Buffer } from 'buffer';
global.Buffer = Buffer;
global.process = {
   env: { DEBUG: undefined },
   version: '',
   } as any;

I skipped a few steps because only adding global.process would then throw the undefined Buffer error, so I just added Buffer aswell along with global.

We are now left with the error "__dirname is not defined"
image

which I am clueless of how to fix and already think that all the workarounds might eventually just create a waterfall crash.

Conclusions:

This last bit seems to be a duplicate of : #77 but I feel like the whole road to get to the error described here is also quite cumbersome as you just fix error after error only to be faced with another one.

Is there a compatibility missmatch? Is the erdjs package only meant to be used on NodeJS and not in the browser? Or is it just a problem because of the new Webpack version and we're just missing the real fix?

Uncaught (in promise) Error: Cannot GET address/<wallet address>

I am running into an error trying to create a tx on the dev-net. This error message isn't helping me.

Uncaught (in promise) Error: Cannot GET address/<--my wallet address revoked-->: [[object Object]]
at ProxyProvider.handleApiError (proxyProvider.js?2fbe:205)
at ProxyProvider.eval (proxyProvider.js?2fbe:174)
at Generator.throw ()
at rejected (proxyProvider.js?2fbe:25)

Here's my code:

  async function mint() {
   const transaction = await newTransaction(
     address,
     quantity * config.nftPriceInEgld
   );

   let provider = ExtensionProvider.getInstance();
   await provider.init();

   let hash = await provider.sendTransaction(transaction);
   console.log(hash);
 }
  async function newTransaction(senderAddress, egldAmount = 1) {
    const gasLimit = 500000;
    const chainId = 'D';

    let proxy = new ProxyProvider(config.network);
    let account = new Account(new Address(address));
    await account.sync(proxy);
    console.log(account);

    return new Transaction({
      sender: new Address(senderAddress),
      receiver: new Address(config.internalWalletAddress),
      value: Balance.egld(egldAmount),
      gasLimit: new GasLimit(gasLimit),
      chainID: new ChainID(chainId),
      nonce: account.nonce
    });
  }

BooleanValue is always encoded as false

Here is a reproductible example :

const booleanString = "true"
const value = NativeSerializer.nativeToTypedValues(
    [booleanString],
    new EndpointDefinition(
        "test",
        [
            new EndpointParameterDefinition("test", "test", new BooleanType())
        ],
        [],
        new EndpointModifiers("mutable", [])
    )
)[0]
const codec = new BinaryCodec()
const encodedTopLevel = codec.encodeTopLevel(value)
const encodedNested = codec.encodeNested(value)
console.log({
    encodedTopLevel: encodedTopLevel.toString("hex"),
    encodedNested: encodedNested.toString("hex")
})

And what is logged :

{ encodedTopLevel: '', encodedNested: '00' }

The result is the same if I replace "true" by "1"

I'm using @multiversx/sdk-core: ^11.3.0

Getting error: cannot find event of type ESDTSetRole

Hi, i am having a issue related to parseSetSpecialRole().
This is how i am doing the transaction:

const transaction2 = factory.setSpecialRoleOnFungible({
    manager: signer.getAddress(),
    user: signer.getAddress(),
    tokenIdentifier: tx1OnOutcome.tokenIdentifier,
    addRoleLocalMint: true,
    addRoleLocalBurn: true,
  });

  const tx2 = await processTransaction(transaction2, signer, signerAccount);
  const tx2Hash = await provider.sendTransaction(tx2);
  const tx2OnNetwork = await watcher.awaitCompleted(tx2);
  console.log(`tx2 completed`);
  console.log('Hash2: ', tx2Hash);
  const tx2Outcome = parser.parseSetSpecialRole(tx2OnNetwork);

async function processTransaction(transaction, signer, signerAccount) {
  console.log('signer address in processTransaction:', signer.getAddress().toString());
  await transaction.setNonce(signerAccount.getNonceThenIncrement());
  let serializedTransaction = await transaction.serializeForSigning(); // Serializing the transaction to a sequence of bytes, preparing it to be signed
  let transactionSignature = await signer.sign(serializedTransaction); // signing the transaction
  transaction.applySignature(transactionSignature); // applying the signature on the transaction
  return transaction;
}

The error i got :

TransactionCompletionStrategy.isCompleted(), found hyperblock nonce: 5828203
tx2 completed
Hash2:  dace5af85aa70a861426d98a0292e794571f640726587851fca95acd74ac86d7
/home/abinash/Desktop/issueToken (copy)/node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsOutcomeParser.js:141
            throw new errors_1.ErrCannotParseTransactionOutcome(transaction.hash, `cannot find event of type ${identifier}`);
                  ^

ErrCannotParseTransactionOutcome [Error]: cannot parse outcome of transaction dace5af85aa70a861426d98a0292e794571f640726587851fca95acd74ac86d7: cannot find event of type ESDTSetRole
    at TokenOperationsOutcomeParser.findSingleEventByIdentifier (/home/abinash/Desktop/issueToken (copy)/node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsOutcomeParser.js:141:19)
    at TokenOperationsOutcomeParser.parseSetSpecialRole (/home/abinash/Desktop/issueToken (copy)/node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsOutcomeParser.js:34:28)
    at MakeToken (/home/abinash/Desktop/issueToken (copy)/index.js:82:29) {
  inner: undefined
}

But the strange thing is my transaction is showing successful for special role setting, please see here:
https://devnet-explorer.multiversx.com/transactions/dace5af85aa70a861426d98a0292e794571f640726587851fca95acd74ac86d7

The log:
image
Please help me on this.

Publish `@elrondnetwork/hw-app-elrond` on Github

Hi!

@elrondnetwork/elrond-sdk-erdjs-hw-provider depends on @elrondnetwork/hw-app-elrond.

I would like to create a pull request for this package in order to remove its dependency on node-hid.

Would it be possible to publish @elrondnetwork/hw-app-elrond on Github?

Migration support: "v9" to "v10" (April 2022)

sdk-js-core 10 brought a series of breaking changes. Most importantly, the packages walletcore, dapp, contractWrappers and the network providers (ApiProvider, ProxyProvider) have been extracted to separate repositories - consequently, they are now distributed as separate NPM packages. sdk-core does not depend anymore on the libraries fs, crypto and axios.

The classes responsible with parsing contract results or query responses, and the ones responsible with transaction completion detection have been rewritten, as well.

Furthermore, we have removed a couple of previously-thought as utility functions, in order to simplify and improve the codebase of sdk-core.

Balance vs. TokenPayment

In sdk-core 10, the classes Balance and BalanceBuilder do not exist anymore.

Instead, a TokenPayment or an IAccountBalance (a simple BigNumber) should be used instead, depending on the case.

sdk-core 9x:

let balance = Balance.egld(1);

sdk-core 10:

let paymentEGLD = TokenPayment.egldFromAmount("1");
let paymentFungible = TokenPayment.fungibleFromBigInteger(identifier, "1000000", numDecimals);
let paymentNonFungible = TokenPayment.nonFungible(identifier, nonce);

Transaction broadcasting and fetching

The following utility functions are not available anymore: transaction.send(), transaction.getAsOnNetwork().

Instead, one should directly call a network provider:

await networkProvider.sendTransaction(tx);
await networkProvider.getTransaction(txHash)

Transaction awaiting

In sdk-core 10, the following utility functions are not available anymore: transaction.awaitExecuted(), transaction.awaitPending().

Instead, one should directly use the TransactionWatcher:

let transactionWatcher = new TransactionWatcher(networkProvider);
await watcher.awaitCompleted(tx);

Fetching network configuration

In sdk-core 10, we have removed the utility functions NetworkConfig.getDefault() and NetworkConfig.sync().

Instead, one should fetch the network configuration as follows:

let networkConfig = await provider.getNetworkConfig();

Then cache the response, if needed.

Nonce, gas limit, gas price, chain ID

In sdk-core 10, the classes Nonce, GasLimit, GasPrice and ChainID do not exist anymore.

Instead, one should simply use primitives when creating transactions / interactions:

let tx = new Transaction({
    nonce: 7,
    data: new TransactionPayload("helloWorld"),
    gasLimit: 70000,
    gasPrice: 1000000000,
    receiver: new Address("erd1..."),
    value: TokenPayment.egldFromAmount(1),
    chainID: "D"
});

Creating contract queries

The function smartContract.runQuery() has been removed, in order to decouple the SmartContract class from the network provider.

In sdk-core 10, one should do as follows:

let query = smartContract.createQuery({ /* ... */ });
let queryResponse = await networkProvider.queryContract(query);

smartContract.createQuery() + provider.queryContract() have to be used, instead.

Creating interactions using "contract.methods"

In erdsdk-corejs 10, when using contract.methods.myContractFunction([a, b, c]), the type inference system comes into play.

That is, you cannot write the following anymore:

let interaction = <Interaction>this.contract.methods.getLotteryInfo([
    BytesValue.fromUTF8("my-lottery")
]);

Instead, you have to either not provide typed values ar arguments (automatic type inference will be applied):

let interaction = <Interaction>this.contract.methods.getLotteryInfo(["my-lottery")]);

- or to provide typed values, as before, but using the methodsExplicit object:

let interaction = <Interaction>this.contract.methodsExplicit.getLotteryInfo([
    BytesValue.fromUTF8("my-lottery")
]);

Parsing contract results

The modules designed to parse the contract results have been rewritten in sdk-core 10. ExecutionResultsBundle and QueryResponseBundle have been removed, and replaced by TypedOutcomeBundle (and its untyped counterpart, UntypedOutcomeBundle). SmartContractResults has been changed to not use the concepts immediate result and resulting calls anymore. Instead, interpreting SmartContractResults.items is now the responsibility of the ResultsParser. interpretQueryResponse() and interpretExecutionResults() do not exist on the Interaction object anymore. DefaultInteractionRunner has been removed, as well.

The functions getReceipt(), getSmartContractResults() and getLogs() of TransactionOnNetwork have been removed. The underlying properties are now public. Furthermore, TransactionOnNetwork is now defined within @multiversx/sdk-network-providers.

In order to parse contract results in sdk-core 10, please follow this guide.

EsdtHelpers and ScArgumentsParser vs. transaction-decoder

In sdk-core 10, the classes EsdtHelpers and ScArgumentsParser have been removed.

Instead, one should reference and use the package @multiversx/sdk-transaction-decoder.

ChainID is now required

ChainID is now a required parameter of the Transaction constructor.

Furthermore, interaction.withChainID("D") must be used before calling interaction.buildTransaction().

let tx = interaction
    .withNonce(7)
    .withGasLimit(20000000)
    .withChainID("D")
    .buildTransaction();

Add a local wallet provider

A provider that loads a local wallet would be a nice improvement. It would be particularly useful for scripts that deploy smart contracts.

Another use case would be to make a web wallet. People could add their keystore in a website and use it to sign transactions directly in the app.

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.