Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update address to follow specs #552

Merged
merged 4 commits into from
Dec 18, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/abi/codec/address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,13 @@ export class AddressBinaryCodec {
* Encodes an AddressValue to a buffer.
*/
encodeNested(primitive: AddressValue): Buffer {
return primitive.valueOf().pubkey();
return primitive.valueOf().getPublicKey();
}

/**
* Encodes an AddressValue to a buffer.
*/
encodeTopLevel(primitive: AddressValue): Buffer {
return primitive.valueOf().pubkey();
return primitive.valueOf().getPublicKey();
}
}
2 changes: 1 addition & 1 deletion src/abi/interaction.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ describe("test smart contract interactor", function () {
const hexBar = "4241522d356263303866";
const hexLKMEX = "4c4b4d45582d616162393130";
const hexNFT = "4d4f532d623962346232";
const hexContractAddress = new Address(contract.getAddress().toBech32()).hex();
const hexContractAddress = new Address(contract.getAddress().toBech32()).toHex();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this could have been:

const hexContractAddress = contract.getAddress().toHex();

const hexDummyFunction = "64756d6d79";

// ESDT, single
Expand Down
2 changes: 1 addition & 1 deletion src/abi/query.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import BigNumber from "bignumber.js";
import { assert } from "chai";
import { Address } from "../address";
import { ContractFunction } from "./function";
import { Query } from "./query";
import { BigUIntValue, U32Value } from "./typesystem";
import BigNumber from "bignumber.js";
import { BytesValue } from "./typesystem/bytes";

describe("test smart contract queries", () => {
Expand Down
2 changes: 1 addition & 1 deletion src/abi/smartContract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ export class SmartContract implements ISmartContract {
* @param nonce The owner nonce used for the deployment transaction
*/
static computeAddress(owner: Address, nonce: bigint): Address {
const deployer = Address.fromBech32(owner.toBech32());
const deployer = Address.newFromBech32(owner.toBech32());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

owner was already of type Address.

const addressComputer = new AddressComputer();
return addressComputer.computeContractAddress(deployer, BigInt(nonce.valueOf()));
}
Expand Down
2 changes: 1 addition & 1 deletion src/accountManagement/accountTransactionsFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export class AccountTransactionsFactory {
createTransactionForSettingGuardian(sender: Address, options: SetGuardianInput): Transaction {
const dataParts = [
"SetGuardian",
Address.fromBech32(options.guardianAddress.bech32()).toHex(),
Address.newFromBech32(options.guardianAddress.toBech32()).toHex(),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could have been:

options.guardianAddress.toHex()

Buffer.from(options.serviceID).toString("hex"),
];

Expand Down
6 changes: 3 additions & 3 deletions src/address.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ describe("test address", () => {
});

it("should create address (custom hrp)", async () => {
let address = Address.fromHex(aliceHex, "test");
let address = Address.newFromHex(aliceHex, "test");
assert.deepEqual(address.getPublicKey(), Buffer.from(aliceHex, "hex"));
assert.equal(address.getHrp(), "test");
assert.equal(address.toBech32(), "test1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ss5hqhtr");

address = Address.fromHex(bobHex, "xerd");
address = Address.newFromHex(bobHex, "xerd");
assert.deepEqual(address.getPublicKey(), Buffer.from(bobHex, "hex"));
assert.equal(address.getHrp(), "xerd");
assert.equal(address.toBech32(), "xerd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruq9thc9j");
Expand All @@ -34,7 +34,7 @@ describe("test address", () => {
it("should create empty address", async () => {
const nobody = Address.empty();

assert.isEmpty(nobody.hex());
assert.isEmpty(nobody.toHex());
assert.isEmpty(nobody.toBech32());
assert.deepEqual(nobody.toJSON(), { bech32: "", pubkey: "" });
});
Expand Down
14 changes: 7 additions & 7 deletions src/address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import { CURRENT_NUMBER_OF_SHARDS_WITHOUT_META, METACHAIN_ID, WasmVirtualMachine } from "./constants";
import * as errors from "./errors";
import { bigIntToBuffer } from "./tokenOperations/codec";
const createKeccakHash = require("keccak");

Check warning on line 7 in src/address.ts

View workflow job for this annotation

GitHub Actions / build (16.x)

Require statement not part of import statement

/**
* The length (in bytes) of a public key (from which a bech32 address can be obtained).
Expand Down Expand Up @@ -93,7 +93,7 @@
}

/**
* Use {@link newFromBech32} instead.
* @deprecated Use {@link newFromBech32} instead.
*/
static fromBech32(value: string): Address {
// On this legacy flow, we do not accept addresses with custom hrp (in order to avoid behavioral breaking changes).
Expand All @@ -113,7 +113,7 @@
}

/**
* Use {@link newFromHex} instead.
* @deprecated Use {@link newFromHex} instead.
*/
static fromHex(value: string, hrp?: string): Address {
return Address.newFromHex(value, hrp);
Expand Down Expand Up @@ -147,7 +147,7 @@
}

/**
* Use {@link toHex} instead.
* @deprecated Use {@link toHex} instead.
*/
hex(): string {
return this.toHex();
Expand All @@ -165,7 +165,7 @@
}

/**
* Use {@link toBech32} instead.
* @deprecated Use {@link toBech32} instead.
*/
bech32(): string {
return this.toBech32();
Expand All @@ -179,13 +179,13 @@
return "";
}

let words = bech32.toWords(this.pubkey());
let words = bech32.toWords(this.getPublicKey());
let address = bech32.encode(this.hrp, words);
return address;
}

/**
* Use {@link getPublicKey} instead.
* @deprecated Use {@link getPublicKey} instead.
*/
pubkey(): Buffer {
return this.getPublicKey();
Expand Down Expand Up @@ -249,7 +249,7 @@
}

/**
* Use {@link isSmartContract} instead.
* @deprecated Use {@link isSmartContract} instead.
*/
isContractAddress(): boolean {
return this.isSmartContract();
Expand Down
4 changes: 2 additions & 2 deletions src/compatibility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ export class Compatibility {
* For internal use only.
*/
static guardAddressIsSetAndNonZero(address: Address | undefined, context: string, resolution: string) {
if (!address || address.bech32() == "") {
if (!address || address.toBech32() == "") {
console.warn(
`${context}: address should be set; ${resolution}. In the future, this will throw an exception instead of emitting a WARN.`,
);
} else if (address.bech32() == Address.Zero().toBech32()) {
} else if (address.toBech32() == Address.Zero().toBech32()) {
console.warn(
`${context}: address should not be the 'zero' address (also known as the 'contracts deployment address'); ${resolution}. In the future, this will throw an exception instead of emitting a WARN.`,
);
Expand Down
5 changes: 4 additions & 1 deletion src/delegation/delegationTransactionsFactory.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ describe("test delegation transactions factory", function () {
transaction.sender,
Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"),
);
assert.deepEqual(transaction.receiver, Address.fromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX, config.addressHrp));
assert.deepEqual(
transaction.receiver,
Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX, config.addressHrp),
);
assert.isDefined(transaction.data);
assert.deepEqual(transaction.data, Buffer.from("createNewDelegationContract@010f0cf064dd59200000@0a"));
assert.equal(transaction.gasLimit, 60126500n);
Expand Down
2 changes: 1 addition & 1 deletion src/delegation/delegationTransactionsFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export class DelegationTransactionsFactory {
constructor(options: { config: IConfig }) {
this.config = options.config;
this.argSerializer = new ArgSerializer();
this.delegationManagerAddress = Address.fromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX, this.config.addressHrp);
this.delegationManagerAddress = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX, this.config.addressHrp);
}

createTransactionForNewDelegationContract(
Expand Down
2 changes: 1 addition & 1 deletion src/message.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Address } from "./address";
import { DEFAULT_MESSAGE_VERSION, MESSAGE_PREFIX, SDK_JS_SIGNER, UNKNOWN_SIGNER } from "./constants";

const createKeccakHash = require("keccak");

Check warning on line 4 in src/message.ts

View workflow job for this annotation

GitHub Actions / build (16.x)

Require statement not part of import statement

export class Message {
/**
Expand Down Expand Up @@ -86,7 +86,7 @@

let address: Address | undefined = undefined;
if (packedMessage.address) {
address = Address.fromBech32(packedMessage.address);
address = Address.newFromBech32(packedMessage.address);
}

const version = packedMessage.version || DEFAULT_MESSAGE_VERSION;
Expand Down
10 changes: 5 additions & 5 deletions src/networkProviders/apiNetworkProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export class ApiNetworkProvider implements INetworkProvider {
}

async getAccount(address: Address): Promise<AccountOnNetwork> {
const response = await this.doGetGeneric(`accounts/${address.bech32()}`);
const response = await this.doGetGeneric(`accounts/${address.toBech32()}`);
const account = AccountOnNetwork.fromHttpResponse(response);
return account;
}
Expand All @@ -81,7 +81,7 @@ export class ApiNetworkProvider implements INetworkProvider {
): Promise<FungibleTokenOfAccountOnNetwork[]> {
pagination = pagination || defaultPagination;

const url = `accounts/${address.bech32()}/tokens?${this.buildPaginationParams(pagination)}`;
const url = `accounts/${address.toBech32()}/tokens?${this.buildPaginationParams(pagination)}`;
const response: any[] = await this.doGetGeneric(url);
const tokens = response.map((item) => FungibleTokenOfAccountOnNetwork.fromHttpResponse(item));

Expand All @@ -96,7 +96,7 @@ export class ApiNetworkProvider implements INetworkProvider {
): Promise<NonFungibleTokenOfAccountOnNetwork[]> {
pagination = pagination || defaultPagination;

const url = `accounts/${address.bech32()}/nfts?${this.buildPaginationParams(pagination)}`;
const url = `accounts/${address.toBech32()}/nfts?${this.buildPaginationParams(pagination)}`;
const response: any[] = await this.doGetGeneric(url);
const tokens = response.map((item) => NonFungibleTokenOfAccountOnNetwork.fromApiHttpResponse(item));

Expand All @@ -109,7 +109,7 @@ export class ApiNetworkProvider implements INetworkProvider {
address: Address,
tokenIdentifier: string,
): Promise<FungibleTokenOfAccountOnNetwork> {
const response = await this.doGetGeneric(`accounts/${address.bech32()}/tokens/${tokenIdentifier}`);
const response = await this.doGetGeneric(`accounts/${address.toBech32()}/tokens/${tokenIdentifier}`);
const tokenData = FungibleTokenOfAccountOnNetwork.fromHttpResponse(response);
return tokenData;
}
Expand All @@ -120,7 +120,7 @@ export class ApiNetworkProvider implements INetworkProvider {
nonce: number,
): Promise<NonFungibleTokenOfAccountOnNetwork> {
const nonceAsHex = numberToPaddedHex(nonce);
const response = await this.doGetGeneric(`accounts/${address.bech32()}/nfts/${collection}-${nonceAsHex}`);
const response = await this.doGetGeneric(`accounts/${address.toBech32()}/nfts/${collection}-${nonceAsHex}`);
const tokenData = NonFungibleTokenOfAccountOnNetwork.fromApiHttpResponse(response);
return tokenData;
}
Expand Down
14 changes: 7 additions & 7 deletions src/networkProviders/proxyNetworkProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,13 @@ export class ProxyNetworkProvider implements INetworkProvider {
}

async getAccount(address: Address): Promise<AccountOnNetwork> {
const response = await this.doGetGeneric(`address/${address.bech32()}`);
const response = await this.doGetGeneric(`address/${address.toBech32()}`);
const account = AccountOnNetwork.fromHttpResponse(response.account);
return account;
}

async getGuardianData(address: Address): Promise<GuardianData> {
const response = await this.doGetGeneric(`address/${address.bech32()}/guardian-data`);
const response = await this.doGetGeneric(`address/${address.toBech32()}/guardian-data`);
const accountGuardian = GuardianData.fromHttpResponse(response.guardianData);
return accountGuardian;
}
Expand All @@ -74,7 +74,7 @@ export class ProxyNetworkProvider implements INetworkProvider {
address: Address,
_pagination?: IPagination,
): Promise<FungibleTokenOfAccountOnNetwork[]> {
const url = `address/${address.bech32()}/esdt`;
const url = `address/${address.toBech32()}/esdt`;
const response = await this.doGetGeneric(url);
const responseItems: any[] = Object.values(response.esdts);
// Skip NFTs / SFTs.
Expand All @@ -90,7 +90,7 @@ export class ProxyNetworkProvider implements INetworkProvider {
address: Address,
_pagination?: IPagination,
): Promise<NonFungibleTokenOfAccountOnNetwork[]> {
const url = `address/${address.bech32()}/esdt`;
const url = `address/${address.toBech32()}/esdt`;
const response = await this.doGetGeneric(url);
const responseItems: any[] = Object.values(response.esdts);
// Skip fungible tokens.
Expand All @@ -108,7 +108,7 @@ export class ProxyNetworkProvider implements INetworkProvider {
address: Address,
tokenIdentifier: string,
): Promise<FungibleTokenOfAccountOnNetwork> {
const response = await this.doGetGeneric(`address/${address.bech32()}/esdt/${tokenIdentifier}`);
const response = await this.doGetGeneric(`address/${address.toBech32()}/esdt/${tokenIdentifier}`);
const tokenData = FungibleTokenOfAccountOnNetwork.fromHttpResponse(response.tokenData);
return tokenData;
}
Expand All @@ -119,7 +119,7 @@ export class ProxyNetworkProvider implements INetworkProvider {
nonce: number,
): Promise<NonFungibleTokenOfAccountOnNetwork> {
const response = await this.doGetGeneric(
`address/${address.bech32()}/nft/${collection}/nonce/${nonce.valueOf()}`,
`address/${address.toBech32()}/nft/${collection}/nonce/${nonce.valueOf()}`,
);
const tokenData = NonFungibleTokenOfAccountOnNetwork.fromProxyHttpResponseByNonce(response.tokenData);
return tokenData;
Expand Down Expand Up @@ -185,7 +185,7 @@ export class ProxyNetworkProvider implements INetworkProvider {
const encodedIdentifier = Buffer.from(identifier);

const queryResponse = await this.queryContract({
contract: Address.fromHex(ESDT_CONTRACT_ADDRESS_HEX),
contract: Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX),
function: "getTokenProperties",
arguments: [new Uint8Array(encodedIdentifier)],
});
Expand Down
4 changes: 2 additions & 2 deletions src/proto/serializer.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,8 @@ describe("serialize transactions", () => {
const transaction = new Transaction({
nonce: 204n,
value: 1000000000000000000n,
sender: Address.fromBech32("erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8"),
receiver: Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"),
sender: Address.newFromBech32("erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8"),
receiver: Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"),
senderUsername: "carol",
receiverUsername: "alice",
gasLimit: 50000n,
Expand Down
4 changes: 2 additions & 2 deletions src/smartContracts/smartContractTransactionsFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export class SmartContractTransactionsFactory {
this.abi = options.abi;
this.tokenComputer = new TokenComputer();
this.dataArgsBuilder = new TokenTransfersDataBuilder();
this.contractDeployAddress = Address.fromHex(CONTRACT_DEPLOY_ADDRESS_HEX, this.config.addressHrp);
this.contractDeployAddress = Address.newFromHex(CONTRACT_DEPLOY_ADDRESS_HEX, this.config.addressHrp);
}

createTransactionForDeploy(sender: Address, options: resources.ContractDeployInput): Transaction {
Expand Down Expand Up @@ -185,7 +185,7 @@ export class SmartContractTransactionsFactory {
contract: Address;
newOwner: Address;
}): Transaction {
const dataParts = ["ChangeOwnerAddress", Address.fromBech32(options.newOwner.toBech32()).toHex()];
const dataParts = ["ChangeOwnerAddress", Address.newFromBech32(options.newOwner.toBech32()).toHex()];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could have been:

options.newOwner.toHex()


return new TransactionBuilder({
config: this.config,
Expand Down
2 changes: 1 addition & 1 deletion src/tokenManagement/tokenManagementTransactionsFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export class TokenManagementTransactionsFactory {
this.argSerializer = new ArgSerializer();
this.trueAsString = "true";
this.falseAsString = "false";
this.esdtContractAddress = Address.fromHex(ESDT_CONTRACT_ADDRESS_HEX, this.config.addressHrp);
this.esdtContractAddress = Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, this.config.addressHrp);
}

createTransactionForIssuingFungible(sender: Address, options: resources.IssueFungibleInput): Transaction {
Expand Down
8 changes: 4 additions & 4 deletions src/transaction.local.net.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,15 @@ describe("test transaction", function () {
let transactionOne = new Transaction({
sender: alice.address,
receiver: bob.address,
value: TokenTransfer.newFromNativeAmount(42n).amount,
value: TokenTransfer.newFromNativeAmount(42000000000000000000n).amount,
gasLimit: BigInt(network.MinGasLimit),
chainID: network.ChainID,
});

let transactionTwo = new Transaction({
sender: alice.address,
receiver: bob.address,
value: TokenTransfer.newFromNativeAmount(43n).amount,
value: TokenTransfer.newFromNativeAmount(43000000000000000000n).amount,
gasLimit: BigInt(network.MinGasLimit),
chainID: network.ChainID,
});
Expand All @@ -73,7 +73,7 @@ describe("test transaction", function () {
let newBalanceOfBob = new BigNumber((await bob.getBalance(provider)).toString());

assert.deepEqual(
TokenTransfer.newFromNativeAmount(85n).amount,
TokenTransfer.newFromNativeAmount(85000000000000000000n).amount,
BigInt(newBalanceOfBob.minus(initialBalanceOfBob).toString()),
);
});
Expand Down Expand Up @@ -178,7 +178,7 @@ describe("test transaction", function () {
const newBalanceOfBob = new BigNumber((await bob.getBalance(provider)).toString());

assert.deepEqual(
TokenTransfer.newFromNativeAmount(42n).amount,
TokenTransfer.newFromNativeAmount(42000000000000000000n).amount,
BigInt(newBalanceOfBob.minus(initialBalanceOfBob).toString()),
);
});
Expand Down
2 changes: 1 addition & 1 deletion src/utils.codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,6 @@ export function bigIntToHex(value: BigNumber.Value): string {
}

export function addressToHex(address: Address): string {
const buffer = Address.fromBech32(address.toString()).pubkey();
const buffer = Address.newFromBech32(address.toString()).getPublicKey();
return buffer.toString("hex");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is not needed since an Address can be eaasily converted to hex string. If still needed perhaps simply return address.toHex()?

}
Loading