public void Multiple_params_with_one_of_them_a_tuple_dynamic_first(AbiEncodingStyle encodingStyle) { AbiType type = new AbiTuple(AbiType.UInt256, AbiType.Address, AbiType.Bool); AbiSignature signature = new AbiSignature("abc", AbiType.String, type); ValueTuple <UInt256, Address, bool> staticTuple = new ValueTuple <UInt256, Address, bool>((UInt256)1000, Address.SystemUser, true); const string stringParam = "hello there!"; byte[] encoded = _abiEncoder.Encode(encodingStyle, signature, stringParam, staticTuple); object[] arguments = _abiEncoder.Decode(encodingStyle, signature, encoded); Assert.AreEqual(stringParam, arguments[0]); Assert.AreEqual(staticTuple, arguments[1]); }
public static IEnumerable <GeneratedEventMetadata> Parse(string contractName, string @namespace, SolcNet.DataDescription.Output.Contract contract) { foreach (var item in contract.Abi) { if (item.Type == AbiType.Event) { string eventSignatureHash = AbiSignature.GetSignatureHash(item); yield return(new GeneratedEventMetadata { EventSignatureHash = eventSignatureHash, EventClrTypeName = $"{@namespace}.{contractName}.{item.Name}", IndexedArgsCounts = item.Inputs.Count(a => a.Indexed.GetValueOrDefault()) }); } } }
public async Task Can_claim_payment() { DepositService depositService = new DepositService(_ndmBridge, _abiEncoder, _wallet, _contractAddress); Keccak assetId = Keccak.Compute("data asset"); uint expiryTime = 1547051589; BigInteger value = (BigInteger)336.Ether() / 100; uint units = 336U; byte[] salt = new byte[16]; AbiSignature depositAbiDef = new AbiSignature("deposit", new AbiBytes(32), new AbiUInt(32), new AbiUInt(96), new AbiUInt(32), new AbiBytes(16), AbiType.Address, AbiType.Address); byte[] depositData = _abiEncoder.Encode(AbiEncodingStyle.Packed, depositAbiDef, assetId.Bytes, units, value, expiryTime, salt, _providerAccount, _consumerAccount); Keccak depositId = Keccak.Compute(depositData); Deposit deposit = new Deposit(depositId, units, expiryTime, (UInt256)value); Keccak depositTxHash = await depositService.MakeDepositAsync(_consumerAccount, deposit, 20.GWei()); TxReceipt depositTxReceipt = _bridge.GetReceipt(depositTxHash); TestContext.WriteLine("GAS USED FOR DEPOSIT: {0}", depositTxReceipt.GasUsed); Assert.AreEqual(StatusCode.Success, depositTxReceipt.StatusCode, $"deposit made {depositTxReceipt.Error} {Encoding.UTF8.GetString(depositTxReceipt.ReturnValue ?? new byte[0])}"); // calls revert and cannot reuse the same state - use only for manual debugging // Assert.True(depositService.VerifyDeposit(deposit.Id), "deposit verified"); DataRequest dataRequest = new DataRequest(assetId, units, (UInt256)value, expiryTime, salt, _providerAccount, _consumerAccount, new Signature(new byte[65])); Assert.AreEqual(deposit.Id, depositId, "depositID"); await ClaimPaymentFor(dataRequest, depositId, 0, 27, _providerAccount); foreach (GethLikeTxTrace gethLikeTxTrace in _bridge.GethTracer.BuildResult().Skip(1)) { TestContext.WriteLine(new EthereumJsonSerializer().Serialize(gethLikeTxTrace, true)); } }
public void Test_packed(AbiEncodingStyle encodingStyle) { Keccak assetId = Keccak.Compute("assetId"); uint expiryTime = (uint)new Timestamper().EpochSeconds + 86000; UInt256 value = 1.Ether(); uint units = 10U; byte[] salt = new byte[16]; AbiSignature abiDef = new AbiSignature("example", new AbiBytes(32), new AbiUInt(32), new AbiUInt(96), new AbiUInt(32), new AbiBytes(16), AbiType.Address, AbiType.Address); byte[] encoded = _abiEncoder.Encode(AbiEncodingStyle.Packed, abiDef, assetId.Bytes, units, value, expiryTime, salt, Address.Zero, Address.Zero); Assert.AreEqual(108, encoded.Length); }
private Transaction BuildSimulateValidationTransaction( UserOperation userOperation, BlockHeader parent, IReleaseSpec spec) { AbiSignature abiSignature = _entryPointContractAbi.Functions["simulateValidation"].GetCallInfo().Signature; UserOperationAbi userOperationAbi = userOperation.Abi; byte[] computedCallData = _abiEncoder.Encode( AbiEncodingStyle.IncludeSignature, abiSignature, userOperationAbi); Transaction transaction = _userOperationTxBuilder.BuildTransaction((long)userOperation.PreVerificationGas + (long)userOperation.VerificationGas, computedCallData, Address.Zero, parent, spec, true); return(transaction); }
public void Test_abi_encoding() { string text = string.Empty; string[] potentialLocations = new string[] { Path.Combine(TestContext.CurrentContext.TestDirectory, "basic_abi_tests.json"), Path.Combine(TestContext.CurrentContext.WorkDirectory, "basic_abi_tests.json"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory ?? string.Empty, "basic_abi_tests.json"), Path.Combine(AppDomain.CurrentDomain.DynamicDirectory ?? string.Empty, "basic_abi_tests.json"), }; foreach (string potentialLocation in potentialLocations) { try { text = File.ReadAllText(potentialLocation); break; } catch (IOException) { TestContext.WriteLine($"Could not find test in {potentialLocation}"); } } Dictionary <string, AbiTest> tests = JsonConvert.DeserializeObject <Dictionary <string, AbiTest> >(text); foreach ((string testName, AbiTest abiTest) in tests) { AbiSignature signature = new AbiSignature( testName, abiTest.Types.Select(t => _abiTypes[t]).ToArray()); AbiEncoder encoder = new AbiEncoder(); byte[] abi = encoder.Encode(AbiEncodingStyle.None, signature, abiTest.Args.Select(JsonToObject).ToArray()); abi.Should().BeEquivalentTo(Bytes.FromHexString(abiTest.Result)); } }
public static Destination GetTransactionKey(Transaction tx) { byte[] fnSignature = tx.Data?.Length >= 4 ? AbiSignature.GetAddress(tx.Data) : FnSignatureEmpty; return(new Destination(tx.To, fnSignature, UInt256.Zero)); }
public async Task Can_claim_early_refund() { uint timestamp = 1546871954; _bridge.NextBlockPlease(timestamp); DepositService depositService = new DepositService(_ndmBridge, _abiEncoder, _wallet, _contractAddress); Keccak assetId = Keccak.Compute("data asset"); uint expiryTime = timestamp + (uint)TimeSpan.FromDays(4).TotalSeconds; UInt256 value = 1.Ether(); uint units = 10U; byte[] pepper = new byte[16]; AbiSignature depositAbiDef = new AbiSignature("deposit", new AbiBytes(32), new AbiUInt(32), new AbiUInt(96), new AbiUInt(32), new AbiBytes(16), AbiType.Address, AbiType.Address); byte[] depositData = _abiEncoder.Encode(AbiEncodingStyle.Packed, depositAbiDef, assetId.Bytes, units, value, expiryTime, pepper, _providerAccount, _consumerAccount); Keccak depositId = Keccak.Compute(depositData); Deposit deposit = new Deposit(depositId, units, expiryTime, value); Keccak depositTxHash = await depositService.MakeDepositAsync(_consumerAccount, deposit, 20.GWei()); _bridge.IncrementNonce(_consumerAccount); TxReceipt depositTxReceipt = _bridge.GetReceipt(depositTxHash); TestContext.WriteLine("GAS USED FOR DEPOSIT: {0}", depositTxReceipt.GasUsed); Assert.AreEqual(StatusCode.Success, depositTxReceipt.StatusCode, $"deposit made {depositTxReceipt.Error} {Encoding.UTF8.GetString(depositTxReceipt.ReturnValue ?? new byte[0])}"); // calls revert and cannot reuse the same state - use only for manual debugging // Assert.True(depositService.VerifyDeposit(deposit.Id), "deposit verified"); uint claimableAfter = timestamp + (uint)TimeSpan.FromDays(1).TotalSeconds; AbiSignature earlyRefundAbiDef = new AbiSignature("earlyRefund", new AbiBytes(32), new AbiUInt(32)); byte[] earlyRefundData = _abiEncoder.Encode(AbiEncodingStyle.Packed, earlyRefundAbiDef, depositId.Bytes, claimableAfter); RefundService refundService = new RefundService(_ndmBridge, _abiEncoder, _depositRepository, _contractAddress, LimboLogs.Instance); // it will not work so far as we do everything within the same block and timestamp is wrong uint newTimestamp = 1546871954 + (uint)TimeSpan.FromDays(2).TotalSeconds; _bridge.NextBlockPlease(newTimestamp); Signature earlySig = _wallet.Sign(Keccak.Compute(earlyRefundData), _providerAccount); EarlyRefundClaim earlyRefundClaim = new EarlyRefundClaim(depositId, assetId, units, value, expiryTime, pepper, _providerAccount, claimableAfter, earlySig, _consumerAccount); UInt256 balanceBefore = _state.GetBalance(_consumerAccount); Keccak refundTxHash = await refundService.ClaimEarlyRefundAsync(_consumerAccount, earlyRefundClaim, 20.GWei()); TxReceipt refundReceipt = _bridge.GetReceipt(refundTxHash); TestContext.WriteLine("GAS USED FOR EARLY REFUND CLAIM: {0}", refundReceipt.GasUsed); Assert.AreEqual(StatusCode.Success, refundReceipt.StatusCode, $"early refund claim {refundReceipt.Error} {Encoding.UTF8.GetString(refundReceipt.ReturnValue ?? new byte[0])}"); UInt256 balanceAfter = _state.GetBalance(_consumerAccount); Assert.Greater(balanceAfter, balanceBefore); }
string GenerateFunction(Abi methodAbi) { var callDataParams = new List <string>(); string functionSig = AbiSignature.GetFullSignature(methodAbi); callDataParams.Add($"\"{functionSig}\""); string inputConstructorArg = string.Empty; bool hasInputs = methodAbi.Inputs.Length > 0; if (hasInputs) { var inputs = GenerateInputs(methodAbi.Inputs); inputConstructorArg = GenerateInputString(inputs); for (var i = 0; i < inputs.Length; i++) { var input = inputs[i]; string encoderLine; if (input.AbiType.IsMultiDimensionalArray) { encoderLine = $"EncoderFactory.LoadMultiDimArrayEncoder(\"{input.SolidityTypeName}\", {input.Identifier})"; } else if (input.AbiType.IsArrayType) { string arrayElementType = GetArrayElementClrTypeName(input.AbiType); string arrayItemEncoder = $"EncoderFactory.LoadEncoder(\"{input.AbiType.ArrayItemInfo.SolidityName}\", default({arrayElementType}))"; encoderLine = $"EncoderFactory.LoadEncoder(\"{input.SolidityTypeName}\", {input.Identifier}, {arrayItemEncoder})"; } else { encoderLine = $"EncoderFactory.LoadEncoder(\"{input.SolidityTypeName}\", {input.Identifier})"; } callDataParams.Add(encoderLine); } } string callDataString = string.Join(", ", callDataParams); var outputs = GenerateOutputs(methodAbi.Outputs); string outputParams = GenerateOutputString(outputs); string outputClrTypes = string.Empty; if (outputs.Length > 0) { outputClrTypes = "<" + string.Join(", ", outputs.Select(s => s.ClrTypeName)) + ">"; } string returnType; if (outputs.Length == 0) { returnType = string.Empty; } else if (outputs.Length == 1) { returnType = $"<{outputs[0].ClrTypeName}>"; } else { returnType = $"<({outputParams})>"; } string[] decoderParams = new string[outputs.Length]; for (var i = 0; i < outputs.Length; i++) { string decoder; if (outputs[i].AbiType.IsMultiDimensionalArray) { var clrType = GetArrayElementClrTypeName(outputs[i].AbiType); decoder = $"DecoderFactory.GetMultiDimArrayDecoder<{clrType}>(\"{outputs[i].AbiType.SolidityName}\")"; } else if (outputs[i].AbiType.IsArrayType) { string arrayElementType = GetArrayElementClrTypeName(outputs[i].AbiType); decoder = $"DecoderFactory.GetArrayDecoder(EncoderFactory.LoadEncoder(\"{outputs[i].AbiType.ArrayItemInfo.SolidityName}\", default({arrayElementType})))"; } else { decoder = "DecoderFactory.Decode"; } decoderParams[i] = $"\"{methodAbi.Outputs[i].Type}\", {decoder}"; } string decoderStr; if (outputs.Length > 0) { decoderStr = "this, callData, " + string.Join(", ", decoderParams); } else { decoderStr = "this, callData"; } var methodName = ReservedKeywords.EscapeIdentifier(methodAbi.Name); var(summaryDoc, paramsDoc) = GetSummaryXmlDoc(methodAbi); return($@" /// <summary>{summaryDoc}</summary> {paramsDoc} public EthFunc{returnType} {methodName}({inputConstructorArg}) {{ var callData = {typeof(EncoderUtil).FullName}.GetFunctionCallBytes({callDataString}); return EthFunc.Create{outputClrTypes}({decoderStr}); }} "); }
public AbiEncodingInfo(AbiEncodingStyle encodingStyle, AbiSignature signature) { EncodingStyle = encodingStyle; Signature = signature; }
public void FunctionSelector() { var result = AbiSignature.GetMethodIDHex("baz(uint32,bool)", hexPrefix: true); Assert.Equal("0xcdcd77c0", result); }