1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| function Invoke-SmartContractOperation { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [string]$ContractABI, [ValidateSet('Deploy','Execute','Query')] [string]$OperationType = 'Query' )
$blockchainReport = [PSCustomObject]@{ Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss' TransactionHash = $null GasUsed = 0 ContractAddress = $null }
try { $web3 = New-Web3 -ProviderUrl 'https://mainnet.infura.io/v3/YOUR-API-KEY' switch($OperationType) { 'Deploy' { $txReceipt = $web3.Eth.DeployContract.SendRequestAsync($ContractABI).GetAwaiter().GetResult() $blockchainReport.ContractAddress = $txReceipt.ContractAddress } 'Execute' { $contract = $web3.Eth.GetContract($ContractABI, $blockchainReport.ContractAddress) $function = $contract.GetFunction('executeOperation') $txHash = $function.SendTransactionAsync().GetAwaiter().GetResult() $blockchainReport.TransactionHash = $txHash } 'Query' { $contract = $web3.Eth.GetContract($ContractABI, $blockchainReport.ContractAddress) $result = $contract.GetFunction('getState').CallAsync().GetAwaiter().GetResult() return $result } }
$txReceipt = $web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync($blockchainReport.TransactionHash).GetAwaiter().GetResult() $blockchainReport.GasUsed = $txReceipt.GasUsed } catch { Write-Error "智能合约操作失败: $_" }
$blockchainReport | ConvertTo-Json | Out-File -Path "$env:TEMP/BlockchainReport_$(Get-Date -Format yyyyMMdd).json" return $blockchainReport }
|