@alephium/web3 0.43.0 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,7 @@ class ArrayCodec {
50
50
  }
51
51
  fromArray(inputs) {
52
52
  return {
53
- length: compact_int_codec_1.compactUnsignedIntCodec.fromU32(inputs.length),
53
+ length: compact_int_codec_1.compactSignedIntCodec.fromI32(inputs.length),
54
54
  value: inputs
55
55
  };
56
56
  }
@@ -32,7 +32,7 @@ class AssetOutputCodec {
32
32
  constructor() {
33
33
  this.parser = binary_parser_1.Parser.start()
34
34
  .nest('amount', {
35
- type: compact_int_codec_1.compactUnsignedIntCodec.parser
35
+ type: compact_int_codec_1.compactSignedIntCodec.parser
36
36
  })
37
37
  .nest('lockupScript', {
38
38
  type: lockup_script_codec_1.lockupScriptCodec.parser
@@ -111,12 +111,12 @@ class AssetOutputCodec {
111
111
  };
112
112
  });
113
113
  const tokens = {
114
- length: compact_int_codec_1.compactUnsignedIntCodec.fromU32(tokensValue.length),
114
+ length: compact_int_codec_1.compactSignedIntCodec.fromI32(tokensValue.length),
115
115
  value: tokensValue
116
116
  };
117
117
  const additionalDataValue = (0, utils_1.hexToBinUnsafe)(fixedOutput.message);
118
118
  const additionalData = {
119
- length: compact_int_codec_1.compactUnsignedIntCodec.fromU32(additionalDataValue.length),
119
+ length: compact_int_codec_1.compactSignedIntCodec.fromI32(additionalDataValue.length),
120
120
  value: additionalDataValue
121
121
  };
122
122
  return {
@@ -25,22 +25,22 @@ class ByteStringCodec {
25
25
  constructor() {
26
26
  this.parser = new binary_parser_1.Parser()
27
27
  .nest('length', {
28
- type: compact_int_codec_1.compactUnsignedIntCodec.parser
28
+ type: compact_int_codec_1.compactSignedIntCodec.parser
29
29
  })
30
30
  .buffer('value', {
31
31
  length: function (ctx) {
32
- return compact_int_codec_1.compactUnsignedIntCodec.toU32(this['length']);
32
+ return compact_int_codec_1.compactSignedIntCodec.toI32(this['length']);
33
33
  }
34
34
  });
35
35
  }
36
36
  encode(input) {
37
- return (0, utils_1.concatBytes)([compact_int_codec_1.compactUnsignedIntCodec.encode(input.length), input.value]);
37
+ return (0, utils_1.concatBytes)([compact_int_codec_1.compactSignedIntCodec.encode(input.length), input.value]);
38
38
  }
39
39
  decode(input) {
40
40
  return this.parser.parse(input);
41
41
  }
42
42
  encodeBytes(input) {
43
- return (0, utils_1.concatBytes)([compact_int_codec_1.compactUnsignedIntCodec.encodeU32(input.length), input]);
43
+ return (0, utils_1.concatBytes)([compact_int_codec_1.compactSignedIntCodec.encodeI32(input.length), input]);
44
44
  }
45
45
  decodeBytes(input) {
46
46
  return this.decode(input).value;
@@ -21,11 +21,8 @@ export declare class CompactUnsignedIntCodec implements Codec<DecodedCompactInt>
21
21
  encode(input: DecodedCompactInt): Uint8Array;
22
22
  encodeU32(value: number): Uint8Array;
23
23
  encodeU256(value: bigint): Uint8Array;
24
- decodeU32(input: Uint8Array): number;
25
24
  decodeU256(input: Uint8Array): bigint;
26
25
  decode(input: Uint8Array): DecodedCompactInt;
27
- toU32(value: DecodedCompactInt): number;
28
- fromU32(value: number): DecodedCompactInt;
29
26
  toU256(value: DecodedCompactInt): bigint;
30
27
  fromU256(value: bigint): DecodedCompactInt;
31
28
  }
@@ -102,10 +102,6 @@ class CompactUnsignedIntCodec {
102
102
  return new Uint8Array([header, ...bytes]);
103
103
  }
104
104
  }
105
- decodeU32(input) {
106
- const decoded = this.decode(input);
107
- return this.toU32(decoded);
108
- }
109
105
  decodeU256(input) {
110
106
  const decoded = this.decode(input);
111
107
  return this.toU256(decoded);
@@ -113,17 +109,11 @@ class CompactUnsignedIntCodec {
113
109
  decode(input) {
114
110
  return this.parser.parse(input);
115
111
  }
116
- toU32(value) {
117
- const body = new Uint8Array([value.mode, ...value.rest]);
118
- return decodePositiveInt(value.mode, body);
119
- }
120
- fromU32(value) {
121
- return this.decode(this.encodeU32(value));
122
- }
123
112
  toU256(value) {
124
113
  const mode = value.mode & maskRest;
125
114
  if (fixedSize(mode)) {
126
- return BigInt(this.toU32(value));
115
+ const body = new Uint8Array([value.mode, ...value.rest]);
116
+ return BigInt(decodePositiveInt(value.mode, body));
127
117
  }
128
118
  else {
129
119
  (0, codec_1.assert)(value.rest.length <= 32, 'Expect <= 32 bytes for U256');
@@ -47,8 +47,8 @@ class ContractCodec {
47
47
  }
48
48
  decodeContract(input) {
49
49
  const halfDecoded = this.decode(input);
50
- const fieldLength = compact_int_codec_1.compactUnsignedIntCodec.toU32(halfDecoded.fieldLength);
51
- const methodIndexes = halfDecoded.methodIndexes.value.map((v) => compact_int_codec_1.compactUnsignedIntCodec.toU32(v));
50
+ const fieldLength = compact_int_codec_1.compactSignedIntCodec.toI32(halfDecoded.fieldLength);
51
+ const methodIndexes = halfDecoded.methodIndexes.value.map((v) => compact_int_codec_1.compactSignedIntCodec.toI32(v));
52
52
  const methods = [];
53
53
  for (let i = 0, start = 0; i < methodIndexes.length; i++) {
54
54
  const end = methodIndexes[i];
@@ -70,7 +70,7 @@ class ContractOutputCodec {
70
70
  };
71
71
  });
72
72
  const tokens = {
73
- length: compact_int_codec_1.compactUnsignedIntCodec.fromU32(tokensValue.length),
73
+ length: compact_int_codec_1.compactSignedIntCodec.fromI32(tokensValue.length),
74
74
  value: tokensValue
75
75
  };
76
76
  return { amount, lockupScript, tokens };
@@ -53,13 +53,13 @@ class MethodCodec {
53
53
  .uint8('isPublic')
54
54
  .uint8('assetModifier')
55
55
  .nest('argsLength', {
56
- type: compact_int_codec_1.compactUnsignedIntCodec.parser
56
+ type: compact_int_codec_1.compactSignedIntCodec.parser
57
57
  })
58
58
  .nest('localsLength', {
59
- type: compact_int_codec_1.compactUnsignedIntCodec.parser
59
+ type: compact_int_codec_1.compactSignedIntCodec.parser
60
60
  })
61
61
  .nest('returnLength', {
62
- type: compact_int_codec_1.compactUnsignedIntCodec.parser
62
+ type: compact_int_codec_1.compactSignedIntCodec.parser
63
63
  })
64
64
  .nest('instrs', {
65
65
  type: instr_codec_1.instrsCodec.parser
@@ -67,9 +67,9 @@ class MethodCodec {
67
67
  }
68
68
  encode(input) {
69
69
  const result = [input.isPublic, input.assetModifier];
70
- result.push(...compact_int_codec_1.compactUnsignedIntCodec.encode(input.argsLength));
71
- result.push(...compact_int_codec_1.compactUnsignedIntCodec.encode(input.localsLength));
72
- result.push(...compact_int_codec_1.compactUnsignedIntCodec.encode(input.returnLength));
70
+ result.push(...compact_int_codec_1.compactSignedIntCodec.encode(input.argsLength));
71
+ result.push(...compact_int_codec_1.compactSignedIntCodec.encode(input.localsLength));
72
+ result.push(...compact_int_codec_1.compactSignedIntCodec.encode(input.returnLength));
73
73
  result.push(...instr_codec_1.instrsCodec.encode(input.instrs.value));
74
74
  return new Uint8Array(result);
75
75
  }
@@ -80,9 +80,9 @@ class MethodCodec {
80
80
  return {
81
81
  isPublic: decodedMethod.isPublic === 1,
82
82
  ...decodeAssetModifier(decodedMethod.assetModifier),
83
- argsLength: compact_int_codec_1.compactUnsignedIntCodec.toU32(decodedMethod.argsLength),
84
- localsLength: compact_int_codec_1.compactUnsignedIntCodec.toU32(decodedMethod.localsLength),
85
- returnLength: compact_int_codec_1.compactUnsignedIntCodec.toU32(decodedMethod.returnLength),
83
+ argsLength: compact_int_codec_1.compactSignedIntCodec.toI32(decodedMethod.argsLength),
84
+ localsLength: compact_int_codec_1.compactSignedIntCodec.toI32(decodedMethod.localsLength),
85
+ returnLength: compact_int_codec_1.compactSignedIntCodec.toI32(decodedMethod.returnLength),
86
86
  instrs: decodedMethod.instrs.value
87
87
  };
88
88
  }
@@ -90,9 +90,9 @@ class MethodCodec {
90
90
  return {
91
91
  isPublic: method.isPublic ? 1 : 0,
92
92
  assetModifier: encodeAssetModifier(method),
93
- argsLength: compact_int_codec_1.compactUnsignedIntCodec.fromU32(method.argsLength),
94
- localsLength: compact_int_codec_1.compactUnsignedIntCodec.fromU32(method.localsLength),
95
- returnLength: compact_int_codec_1.compactUnsignedIntCodec.fromU32(method.returnLength),
93
+ argsLength: compact_int_codec_1.compactSignedIntCodec.fromI32(method.argsLength),
94
+ localsLength: compact_int_codec_1.compactSignedIntCodec.fromI32(method.localsLength),
95
+ returnLength: compact_int_codec_1.compactSignedIntCodec.fromI32(method.returnLength),
96
96
  instrs: instr_codec_1.instrsCodec.fromArray(method.instrs)
97
97
  };
98
98
  }
@@ -40,7 +40,7 @@ class ScriptCodec {
40
40
  return { methods };
41
41
  }
42
42
  encodeScript(inputTxScript) {
43
- const methodLength = compact_int_codec_1.compactUnsignedIntCodec.fromU32(inputTxScript.methods.length);
43
+ const methodLength = compact_int_codec_1.compactSignedIntCodec.fromI32(inputTxScript.methods.length);
44
44
  const decodedMethods = inputTxScript.methods.map((method) => method_codec_1.MethodCodec.fromMethod(method));
45
45
  return this.encode({ methods: { value: decodedMethods, length: methodLength } });
46
46
  }
@@ -1,5 +1,5 @@
1
1
  import { NamedVals, node, NodeProvider, Number256, Token, Val } from '../api';
2
- import { SignDeployContractTxParams, SignDeployContractTxResult, SignExecuteScriptTxParams, SignerProvider, Address } from '../signer';
2
+ import { SignDeployContractTxParams, SignDeployContractTxResult, SignExecuteScriptTxParams, SignerProvider, Address, SignExecuteScriptTxResult } from '../signer';
3
3
  import { Optional, HexString } from '../utils';
4
4
  import { EventSubscribeOptions, EventSubscription } from './events';
5
5
  import { Method } from '../codec';
@@ -220,6 +220,14 @@ export interface CallContractResult<R> {
220
220
  events: ContractEvent[];
221
221
  debugMessages: DebugMessage[];
222
222
  }
223
+ export interface SignExecuteContractMethodParams<T extends Arguments = Arguments> {
224
+ args: T;
225
+ signer: SignerProvider;
226
+ attoAlphAmount?: Number256;
227
+ tokens?: Token[];
228
+ gasAmount?: number;
229
+ gasPrice?: Number256;
230
+ }
223
231
  export declare const CreateContractEventAddresses: string[];
224
232
  export declare const DestroyContractEventAddresses: string[];
225
233
  export type ContractCreatedEventFields = {
@@ -267,6 +275,7 @@ export declare function decodeEvent<F extends Fields, M extends ContractEvent<F>
267
275
  export declare function subscribeContractEvent<F extends Fields, M extends ContractEvent<F>>(contract: Contract, instance: ContractInstance, options: EventSubscribeOptions<M>, eventName: string, fromCount?: number): EventSubscription;
268
276
  export declare function subscribeContractEvents(contract: Contract, instance: ContractInstance, options: EventSubscribeOptions<ContractEvent<any>>, fromCount?: number): EventSubscription;
269
277
  export declare function callMethod<I extends ContractInstance, F extends Fields, A extends Arguments, R>(contract: ContractFactory<I, F>, instance: ContractInstance, methodName: string, params: Optional<CallContractParams<A>, 'args'>, getContractByCodeHash: (codeHash: string) => Contract): Promise<CallContractResult<R>>;
278
+ export declare function signExecuteMethod<I extends ContractInstance, F extends Fields, A extends Arguments, R>(contract: ContractFactory<I, F>, instance: ContractInstance, methodName: string, params: Optional<SignExecuteContractMethodParams<A>, 'args'>): Promise<SignExecuteScriptTxResult>;
270
279
  export declare function multicallMethods<I extends ContractInstance, F extends Fields>(contract: ContractFactory<I, F>, instance: ContractInstance, calls: Record<string, Optional<CallContractParams<any>, 'args'>>, getContractByCodeHash: (codeHash: string) => Contract): Promise<Record<string, CallContractResult<any>>>;
271
280
  export declare function getContractEventsCurrentCount(contractAddress: Address): Promise<number>;
272
281
  export declare const getContractIdFromUnsignedTx: (nodeProvider: NodeProvider, unsignedTx: string) => Promise<HexString>;
@@ -40,7 +40,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
40
40
  return result;
41
41
  };
42
42
  Object.defineProperty(exports, "__esModule", { value: true });
43
- exports.getTokenIdFromUnsignedTx = exports.getContractIdFromUnsignedTx = exports.getContractEventsCurrentCount = exports.multicallMethods = exports.callMethod = exports.subscribeContractEvents = exports.subscribeContractEvent = exports.decodeEvent = exports.subscribeContractDestroyedEvent = exports.subscribeContractCreatedEvent = exports.fetchContractState = exports.ContractInstance = exports.getMapItem = exports.RalphMap = exports.testMethod = exports.addStdIdToFields = exports.subscribeEventsFromContract = exports.decodeContractDestroyedEvent = exports.decodeContractCreatedEvent = exports.DestroyContractEventAddresses = exports.CreateContractEventAddresses = exports.ExecutableScript = exports.ContractFactory = exports.randomTxId = exports.fromApiEventFields = exports.fromApiArray = exports.getDefaultValue = exports.fromApiFields = exports.Script = exports.Contract = exports.Artifact = exports.Struct = exports.DEFAULT_COMPILER_OPTIONS = exports.DEFAULT_NODE_COMPILER_OPTIONS = exports.StdIdFieldName = void 0;
43
+ exports.getTokenIdFromUnsignedTx = exports.getContractIdFromUnsignedTx = exports.getContractEventsCurrentCount = exports.multicallMethods = exports.signExecuteMethod = exports.callMethod = exports.subscribeContractEvents = exports.subscribeContractEvent = exports.decodeEvent = exports.subscribeContractDestroyedEvent = exports.subscribeContractCreatedEvent = exports.fetchContractState = exports.ContractInstance = exports.getMapItem = exports.RalphMap = exports.testMethod = exports.addStdIdToFields = exports.subscribeEventsFromContract = exports.decodeContractDestroyedEvent = exports.decodeContractCreatedEvent = exports.DestroyContractEventAddresses = exports.CreateContractEventAddresses = exports.ExecutableScript = exports.ContractFactory = exports.randomTxId = exports.fromApiEventFields = exports.fromApiArray = exports.getDefaultValue = exports.fromApiFields = exports.Script = exports.Contract = exports.Artifact = exports.Struct = exports.DEFAULT_COMPILER_OPTIONS = exports.DEFAULT_NODE_COMPILER_OPTIONS = exports.StdIdFieldName = void 0;
44
44
  const fs_1 = require("fs");
45
45
  const api_1 = require("../api");
46
46
  const ralph = __importStar(require("./ralph"));
@@ -1042,6 +1042,182 @@ async function callMethod(contract, instance, methodName, params, getContractByC
1042
1042
  return callResult;
1043
1043
  }
1044
1044
  exports.callMethod = callMethod;
1045
+ async function signExecuteMethod(contract, instance, methodName, params) {
1046
+ const methodIndex = contract.contract.getMethodIndex(methodName);
1047
+ const functionSig = contract.contract.functions[methodIndex];
1048
+ const usePreapprovedAssets = contract.contract.decodedMethods[methodIndex].usePreapprovedAssets;
1049
+ const bytecodeTemplate = getBytecodeTemplate(methodIndex, usePreapprovedAssets, functionSig, contract.contract.structs, params.attoAlphAmount, params.tokens);
1050
+ const fieldsSig = toFieldsSig(contract.contract.name, functionSig);
1051
+ const bytecode = ralph.buildScriptByteCode(bytecodeTemplate, { __contract__: instance.contractId, ...params.args }, fieldsSig, contract.contract.structs);
1052
+ const signer = params.signer;
1053
+ const selectedAccount = await signer.getSelectedAccount();
1054
+ const signerParams = {
1055
+ signerAddress: selectedAccount.address,
1056
+ signerKeyType: selectedAccount.keyType,
1057
+ bytecode: bytecode,
1058
+ attoAlphAmount: params.attoAlphAmount,
1059
+ tokens: params.tokens,
1060
+ gasAmount: params.gasAmount,
1061
+ gasPrice: params.gasPrice
1062
+ };
1063
+ return await signer.signAndSubmitExecuteScriptTx(signerParams);
1064
+ }
1065
+ exports.signExecuteMethod = signExecuteMethod;
1066
+ function getBytecodeTemplate(methodIndex, usePreapprovedAssets, functionSig, structs, attoAlphAmount, tokens) {
1067
+ // For the default TxScript main function
1068
+ const numberOfMethods = '01';
1069
+ const isPublic = '01';
1070
+ const modifier = usePreapprovedAssets ? '03' : '00';
1071
+ const argsLength = '00';
1072
+ const returnsLength = '00';
1073
+ const [templateVarStoreLocalInstrs, templateVarsLength] = getTemplateVarStoreLocalInstrs(functionSig, structs);
1074
+ const approveAlphInstrs = getApproveAlphInstrs(usePreapprovedAssets ? attoAlphAmount : undefined);
1075
+ const approveTokensInstrs = getApproveTokensInstrs(usePreapprovedAssets ? tokens : undefined);
1076
+ const callerInstrs = getCallAddressInstrs(approveAlphInstrs.length / 2 + approveTokensInstrs.length / 3);
1077
+ // First template var is the contract
1078
+ const functionArgsNum = encodeU256Const(BigInt(templateVarsLength - 1));
1079
+ const localsLength = encodeI32(templateVarStoreLocalInstrs.length / 2);
1080
+ const templateVarLoadLocalInstrs = getTemplateVarLoadLocalInstrs(functionSig, structs);
1081
+ const functionReturnTypesLength = functionSig.returnTypes.reduce((acc, returnType) => acc + ralph.typeLength(returnType, structs), 0);
1082
+ const functionReturnPopInstrs = encodeInstr(codec_1.Pop).repeat(functionReturnTypesLength);
1083
+ const functionReturnNum = encodeU256Const(BigInt(functionReturnTypesLength));
1084
+ const contractTemplateVar = '{0}'; // always the 1st argument
1085
+ const externalCallInstr = encodeInstr((0, codec_1.CallExternal)(methodIndex));
1086
+ const numberOfInstrs = encodeI32(callerInstrs.length +
1087
+ approveAlphInstrs.length +
1088
+ approveTokensInstrs.length +
1089
+ templateVarStoreLocalInstrs.length +
1090
+ templateVarLoadLocalInstrs.length +
1091
+ functionReturnTypesLength +
1092
+ 4 // functionArgsNum, functionReturnNum, contractTemplate, externalCallInstr
1093
+ );
1094
+ return (numberOfMethods +
1095
+ isPublic +
1096
+ modifier +
1097
+ argsLength +
1098
+ localsLength +
1099
+ returnsLength +
1100
+ numberOfInstrs +
1101
+ callerInstrs.join('') +
1102
+ approveAlphInstrs.join('') +
1103
+ approveTokensInstrs.join('') +
1104
+ templateVarStoreLocalInstrs.join('') +
1105
+ templateVarLoadLocalInstrs.join('') +
1106
+ functionArgsNum +
1107
+ functionReturnNum +
1108
+ contractTemplateVar +
1109
+ externalCallInstr +
1110
+ functionReturnPopInstrs);
1111
+ }
1112
+ function getApproveAlphInstrs(attoAlphAmount) {
1113
+ const approveAlphInstrs = [];
1114
+ if (attoAlphAmount) {
1115
+ const approvedAttoAlphAmount = encodeU256Const(BigInt(attoAlphAmount));
1116
+ approveAlphInstrs.push(approvedAttoAlphAmount);
1117
+ approveAlphInstrs.push(encodeInstr(codec_1.ApproveAlph));
1118
+ }
1119
+ return approveAlphInstrs;
1120
+ }
1121
+ function getApproveTokensInstrs(tokens) {
1122
+ const approveTokensInstrs = [];
1123
+ if (tokens) {
1124
+ tokens.forEach((token) => {
1125
+ const tokenIdBin = (0, utils_1.hexToBinUnsafe)(token.id);
1126
+ approveTokensInstrs.push(encodeInstr((0, codec_1.ByteConst)({
1127
+ length: codec_1.compactSignedIntCodec.fromI32(tokenIdBin.length),
1128
+ value: tokenIdBin
1129
+ })));
1130
+ approveTokensInstrs.push(encodeU256Const(BigInt(token.amount)));
1131
+ approveTokensInstrs.push(encodeInstr(codec_1.ApproveToken));
1132
+ });
1133
+ }
1134
+ return approveTokensInstrs;
1135
+ }
1136
+ function getCallAddressInstrs(approveAssetsNum) {
1137
+ const callerInstrs = [];
1138
+ if (approveAssetsNum > 0) {
1139
+ callerInstrs.push(encodeInstr(codec_1.CallerAddress));
1140
+ const dup = encodeInstr(codec_1.Dup);
1141
+ if (approveAssetsNum > 1) {
1142
+ callerInstrs.push(...new Array(approveAssetsNum - 1).fill(dup));
1143
+ }
1144
+ }
1145
+ return callerInstrs;
1146
+ }
1147
+ function getTemplateVarStoreLocalInstrs(functionSig, structs) {
1148
+ let templateVarIndex = 1; // Start from 1 since first one is always the contract id
1149
+ let localsLength = 0;
1150
+ const templateVarStoreInstrs = [];
1151
+ functionSig.paramTypes.forEach((paramType) => {
1152
+ const fieldsLength = ralph.typeLength(paramType, structs);
1153
+ if (fieldsLength > 1) {
1154
+ for (let i = 0; i < fieldsLength; i++) {
1155
+ templateVarStoreInstrs.push(`{${templateVarIndex + i}}`);
1156
+ }
1157
+ for (let i = 0; i < fieldsLength; i++) {
1158
+ templateVarStoreInstrs.push(encodeStoreLocalInstr(localsLength + (fieldsLength - i - 1)));
1159
+ }
1160
+ localsLength = localsLength + fieldsLength;
1161
+ }
1162
+ templateVarIndex = templateVarIndex + fieldsLength;
1163
+ });
1164
+ return [templateVarStoreInstrs, templateVarIndex];
1165
+ }
1166
+ function getTemplateVarLoadLocalInstrs(functionSig, structs) {
1167
+ let templateVarIndex = 1;
1168
+ let loadIndex = 0;
1169
+ const templateVarLoadInstrs = [];
1170
+ functionSig.paramTypes.forEach((paramType) => {
1171
+ const fieldsLength = ralph.typeLength(paramType, structs);
1172
+ if (fieldsLength === 1) {
1173
+ templateVarLoadInstrs.push(`{${templateVarIndex}}`);
1174
+ }
1175
+ if (fieldsLength > 1) {
1176
+ for (let i = 0; i < fieldsLength; i++) {
1177
+ templateVarLoadInstrs.push(encodeLoadLocalInstr(loadIndex + i));
1178
+ }
1179
+ loadIndex = loadIndex + fieldsLength;
1180
+ }
1181
+ templateVarIndex = templateVarIndex + fieldsLength;
1182
+ });
1183
+ return templateVarLoadInstrs;
1184
+ }
1185
+ function encodeStoreLocalInstr(index) {
1186
+ if (index < 0 || index > 0xff) {
1187
+ throw new Error(`StoreLocal index ${index} must be between 0 and 255 inclusive`);
1188
+ }
1189
+ return encodeInstr((0, codec_1.StoreLocal)(index));
1190
+ }
1191
+ function encodeLoadLocalInstr(index) {
1192
+ if (index < 0 || index > 0xff) {
1193
+ throw new Error(`LoadLocal index ${index} must be between 0 and 255 inclusive`);
1194
+ }
1195
+ return encodeInstr((0, codec_1.LoadLocal)(index));
1196
+ }
1197
+ function encodeI32(value) {
1198
+ return (0, utils_1.binToHex)(codec_1.compactSignedIntCodec.encodeI32(value));
1199
+ }
1200
+ function encodeU256Const(value) {
1201
+ if (value < 0) {
1202
+ throw new Error(`value ${value} must be non-negative`);
1203
+ }
1204
+ if (value < 6) {
1205
+ return (BigInt(0x0c) + value).toString(16).padStart(2, '0');
1206
+ }
1207
+ else {
1208
+ return encodeInstr((0, codec_1.U256Const)(codec_1.compactUnsignedIntCodec.fromU256(BigInt(value))));
1209
+ }
1210
+ }
1211
+ function encodeInstr(instr) {
1212
+ return (0, utils_1.binToHex)(codec_1.instrCodec.encode(instr));
1213
+ }
1214
+ function toFieldsSig(contractName, functionSig) {
1215
+ return {
1216
+ names: ['__contract__'].concat(functionSig.paramNames),
1217
+ types: [contractName].concat(functionSig.paramTypes),
1218
+ isMutable: [false].concat(functionSig.paramIsMutable)
1219
+ };
1220
+ }
1045
1221
  async function multicallMethods(contract, instance, calls, getContractByCodeHash) {
1046
1222
  const callEntries = Object.entries(calls);
1047
1223
  const callsParams = callEntries.map((entry) => {
@@ -60,6 +60,7 @@ export declare function tryDecodeMapDebugLog(message: string): {
60
60
  } | undefined;
61
61
  export declare function decodePrimitive(value: Uint8Array, type: string): Val;
62
62
  export declare function primitiveToByteVec(value: Val, type: string): Uint8Array;
63
+ export declare function typeLength(typ: string, structs: Struct[]): number;
63
64
  export declare function flattenFields(fields: Fields, names: string[], types: string[], isMutable: boolean[], structs: Struct[]): {
64
65
  name: string;
65
66
  type: string;
@@ -18,7 +18,7 @@ along with the library. If not, see <http://www.gnu.org/licenses/>.
18
18
  */
19
19
  var _a;
20
20
  Object.defineProperty(exports, "__esModule", { value: true });
21
- exports.buildDebugBytecode = exports.encodeContractField = exports.buildContractByteCode = exports.encodeContractFields = exports.buildScriptByteCode = exports.flattenFields = exports.primitiveToByteVec = exports.decodePrimitive = exports.tryDecodeMapDebugLog = exports.calcFieldSize = exports.encodeMapPrefix = exports.parseMapType = exports.splitFields = exports.encodeScriptField = exports.encodeScriptFieldAsString = exports.encodePrimitiveValues = exports.addressVal = exports.byteVecVal = exports.u256Val = exports.i256Val = exports.boolVal = exports.encodeVmAddress = exports.encodeVmByteVec = exports.encodeVmU256 = exports.encodeVmI256 = exports.encodeVmBool = exports.VmValType = exports.encodeAddress = exports.encodeByteVec = exports.encodeU256 = exports.encodeI256 = exports.decodeBool = exports.encodeBool = void 0;
21
+ exports.buildDebugBytecode = exports.encodeContractField = exports.buildContractByteCode = exports.encodeContractFields = exports.buildScriptByteCode = exports.flattenFields = exports.typeLength = exports.primitiveToByteVec = exports.decodePrimitive = exports.tryDecodeMapDebugLog = exports.calcFieldSize = exports.encodeMapPrefix = exports.parseMapType = exports.splitFields = exports.encodeScriptField = exports.encodeScriptFieldAsString = exports.encodePrimitiveValues = exports.addressVal = exports.byteVecVal = exports.u256Val = exports.i256Val = exports.boolVal = exports.encodeVmAddress = exports.encodeVmByteVec = exports.encodeVmU256 = exports.encodeVmI256 = exports.encodeVmBool = exports.VmValType = exports.encodeAddress = exports.encodeByteVec = exports.encodeU256 = exports.encodeI256 = exports.decodeBool = exports.encodeBool = void 0;
22
22
  const api_1 = require("../api");
23
23
  const utils_1 = require("../utils");
24
24
  const codec_1 = require("../codec");
@@ -402,6 +402,21 @@ function primitiveToByteVec(value, type) {
402
402
  }
403
403
  }
404
404
  exports.primitiveToByteVec = primitiveToByteVec;
405
+ function typeLength(typ, structs) {
406
+ if (api_1.PrimitiveTypes.includes(typ)) {
407
+ return 1;
408
+ }
409
+ if (typ.startsWith('[')) {
410
+ const [baseType, size] = (0, api_1.decodeArrayType)(typ);
411
+ return size * typeLength(baseType, structs);
412
+ }
413
+ const struct = structs.find((s) => s.name === typ);
414
+ if (struct !== undefined) {
415
+ return struct.fieldTypes.reduce((acc, fieldType) => acc + typeLength(fieldType, structs), 0);
416
+ }
417
+ return 1;
418
+ }
419
+ exports.typeLength = typeLength;
405
420
  function flattenFields(fields, names, types, isMutable, structs) {
406
421
  return names.flatMap((name, index) => {
407
422
  if (!(name in fields)) {
package/package.json CHANGED
@@ -1,14 +1,20 @@
1
1
  {
2
2
  "name": "@alephium/web3",
3
- "version": "0.43.0",
3
+ "version": "0.45.0",
4
4
  "description": "A JS/TS library to interact with the Alephium platform",
5
5
  "license": "GPL",
6
6
  "main": "dist/src/index.js",
7
7
  "browser": "dist/alephium-web3.min.js",
8
8
  "types": "dist/src/index.d.ts",
9
9
  "exports": {
10
- "node": "./dist/src/index.js",
11
- "default": "./dist/alephium-web3.min.js"
10
+ "node": {
11
+ "types": "./dist/src/index.d.ts",
12
+ "default": "./dist/src/index.js"
13
+ },
14
+ "default": {
15
+ "types": "./dist/src/index.d.ts",
16
+ "default": "./dist/alephium-web3.min.js"
17
+ }
12
18
  },
13
19
  "typesVersions": {
14
20
  "*": {
@@ -16,7 +16,7 @@ You should have received a copy of the GNU Lesser General Public License
16
16
  along with the library. If not, see <http://www.gnu.org/licenses/>.
17
17
  */
18
18
  import { Parser } from 'binary-parser'
19
- import { compactSignedIntCodec, compactUnsignedIntCodec, DecodedCompactInt } from './compact-int-codec'
19
+ import { compactSignedIntCodec, DecodedCompactInt } from './compact-int-codec'
20
20
  import { Codec } from './codec'
21
21
 
22
22
  export interface DecodedArray<T> {
@@ -55,7 +55,7 @@ export class ArrayCodec<T> implements Codec<T[]> {
55
55
 
56
56
  fromArray(inputs: T[]): DecodedArray<T> {
57
57
  return {
58
- length: compactUnsignedIntCodec.fromU32(inputs.length),
58
+ length: compactSignedIntCodec.fromI32(inputs.length),
59
59
  value: inputs
60
60
  }
61
61
  }
@@ -17,7 +17,7 @@ along with the library. If not, see <http://www.gnu.org/licenses/>.
17
17
  */
18
18
  import { Parser } from 'binary-parser'
19
19
  import { ArrayCodec, DecodedArray } from './array-codec'
20
- import { DecodedCompactInt, compactUnsignedIntCodec } from './compact-int-codec'
20
+ import { DecodedCompactInt, compactSignedIntCodec, compactUnsignedIntCodec } from './compact-int-codec'
21
21
  import { signedIntCodec } from './signed-int-codec'
22
22
  import { longCodec } from './long-codec'
23
23
  import { ByteString, byteStringCodec } from './bytestring-codec'
@@ -40,7 +40,7 @@ export interface AssetOutput {
40
40
  export class AssetOutputCodec implements Codec<AssetOutput> {
41
41
  parser = Parser.start()
42
42
  .nest('amount', {
43
- type: compactUnsignedIntCodec.parser
43
+ type: compactSignedIntCodec.parser
44
44
  })
45
45
  .nest('lockupScript', {
46
46
  type: lockupScriptCodec.parser
@@ -124,12 +124,12 @@ export class AssetOutputCodec implements Codec<AssetOutput> {
124
124
  }
125
125
  })
126
126
  const tokens: DecodedArray<Token> = {
127
- length: compactUnsignedIntCodec.fromU32(tokensValue.length),
127
+ length: compactSignedIntCodec.fromI32(tokensValue.length),
128
128
  value: tokensValue
129
129
  }
130
130
  const additionalDataValue = hexToBinUnsafe(fixedOutput.message)
131
131
  const additionalData: ByteString = {
132
- length: compactUnsignedIntCodec.fromU32(additionalDataValue.length),
132
+ length: compactSignedIntCodec.fromI32(additionalDataValue.length),
133
133
  value: additionalDataValue
134
134
  }
135
135
 
@@ -16,7 +16,7 @@ You should have received a copy of the GNU Lesser General Public License
16
16
  along with the library. If not, see <http://www.gnu.org/licenses/>.
17
17
  */
18
18
  import { Parser } from 'binary-parser'
19
- import { DecodedCompactInt, compactUnsignedIntCodec } from './compact-int-codec'
19
+ import { DecodedCompactInt, compactSignedIntCodec } from './compact-int-codec'
20
20
  import { Codec } from './codec'
21
21
  import { concatBytes } from '../utils'
22
22
 
@@ -28,16 +28,16 @@ export interface ByteString {
28
28
  export class ByteStringCodec implements Codec<ByteString> {
29
29
  parser = new Parser()
30
30
  .nest('length', {
31
- type: compactUnsignedIntCodec.parser
31
+ type: compactSignedIntCodec.parser
32
32
  })
33
33
  .buffer('value', {
34
34
  length: function (ctx) {
35
- return compactUnsignedIntCodec.toU32(this['length']! as any as DecodedCompactInt)
35
+ return compactSignedIntCodec.toI32(this['length']! as any as DecodedCompactInt)
36
36
  }
37
37
  })
38
38
 
39
39
  encode(input: ByteString): Uint8Array {
40
- return concatBytes([compactUnsignedIntCodec.encode(input.length), input.value])
40
+ return concatBytes([compactSignedIntCodec.encode(input.length), input.value])
41
41
  }
42
42
 
43
43
  decode(input: Uint8Array): ByteString {
@@ -45,7 +45,7 @@ export class ByteStringCodec implements Codec<ByteString> {
45
45
  }
46
46
 
47
47
  encodeBytes(input: Uint8Array): Uint8Array {
48
- return concatBytes([compactUnsignedIntCodec.encodeU32(input.length), input])
48
+ return concatBytes([compactSignedIntCodec.encodeI32(input.length), input])
49
49
  }
50
50
 
51
51
  decodeBytes(input: Uint8Array): Uint8Array {
@@ -110,11 +110,6 @@ export class CompactUnsignedIntCodec implements Codec<DecodedCompactInt> {
110
110
  }
111
111
  }
112
112
 
113
- decodeU32(input: Uint8Array): number {
114
- const decoded = this.decode(input)
115
- return this.toU32(decoded)
116
- }
117
-
118
113
  decodeU256(input: Uint8Array): bigint {
119
114
  const decoded = this.decode(input)
120
115
  return this.toU256(decoded)
@@ -124,19 +119,11 @@ export class CompactUnsignedIntCodec implements Codec<DecodedCompactInt> {
124
119
  return this.parser.parse(input)
125
120
  }
126
121
 
127
- toU32(value: DecodedCompactInt): number {
128
- const body = new Uint8Array([value.mode, ...value.rest])
129
- return decodePositiveInt(value.mode, body)
130
- }
131
-
132
- fromU32(value: number): DecodedCompactInt {
133
- return this.decode(this.encodeU32(value))
134
- }
135
-
136
122
  toU256(value: DecodedCompactInt): bigint {
137
123
  const mode = value.mode & maskRest
138
124
  if (fixedSize(mode)) {
139
- return BigInt(this.toU32(value))
125
+ const body = new Uint8Array([value.mode, ...value.rest])
126
+ return BigInt(decodePositiveInt(value.mode, body))
140
127
  } else {
141
128
  assert(value.rest.length <= 32, 'Expect <= 32 bytes for U256')
142
129
  return BigIntCodec.decode(value.rest, false)
@@ -60,8 +60,8 @@ export class ContractCodec implements Codec<HalfDecodedContract> {
60
60
 
61
61
  decodeContract(input: Uint8Array): Contract {
62
62
  const halfDecoded = this.decode(input)
63
- const fieldLength = compactUnsignedIntCodec.toU32(halfDecoded.fieldLength)
64
- const methodIndexes = halfDecoded.methodIndexes.value.map((v) => compactUnsignedIntCodec.toU32(v))
63
+ const fieldLength = compactSignedIntCodec.toI32(halfDecoded.fieldLength)
64
+ const methodIndexes = halfDecoded.methodIndexes.value.map((v) => compactSignedIntCodec.toI32(v))
65
65
  const methods: Method[] = []
66
66
  for (let i = 0, start = 0; i < methodIndexes.length; i++) {
67
67
  const end = methodIndexes[i]
@@ -17,7 +17,7 @@ along with the library. If not, see <http://www.gnu.org/licenses/>.
17
17
  */
18
18
  import { Parser } from 'binary-parser'
19
19
  import { DecodedArray } from './array-codec'
20
- import { DecodedCompactInt, compactUnsignedIntCodec } from './compact-int-codec'
20
+ import { DecodedCompactInt, compactSignedIntCodec, compactUnsignedIntCodec } from './compact-int-codec'
21
21
  import { P2C } from './lockup-script-codec'
22
22
  import { Codec } from './codec'
23
23
  import { Token, tokensCodec } from './token-codec'
@@ -82,7 +82,7 @@ export class ContractOutputCodec implements Codec<ContractOutput> {
82
82
  }
83
83
  })
84
84
  const tokens: DecodedArray<Token> = {
85
- length: compactUnsignedIntCodec.fromU32(tokensValue.length),
85
+ length: compactSignedIntCodec.fromI32(tokensValue.length),
86
86
  value: tokensValue
87
87
  }
88
88